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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1324  ! raeburn     4: # $Id: lonnet.pm,v 1.1323 2016/09/21 04:57:52 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;
                     77: 
1.1182    foxr       78: 
1.1173    foxr       79: use Encode;
                     80: 
1.1245    raeburn    81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138    raeburn    82:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
                     83:             %managerstab);
1.871     albertel   84: 
                     85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     86:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     87:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        88:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        89: 
1.1       albertel   90: use IO::Socket;
1.31      www        91: use GDBM_File;
1.208     albertel   92: use HTML::LCParser;
1.88      www        93: use Fcntl qw(:flock);
1.870     albertel   94: use Storable qw(thaw nfreeze);
1.1289    damieng    95: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599     albertel   96: use Cache::Memcached;
1.676     albertel   97: use Digest::MD5;
1.790     albertel   98: use Math::Random;
1.1024    raeburn    99: use File::MMagic;
1.807     albertel  100: use LONCAPA qw(:DEFAULT :match);
1.740     www       101: use LONCAPA::Configuration;
1.1160    www       102: use LONCAPA::lonmetadata;
1.1167    droeschl  103: use LONCAPA::Lond;
1.1117    foxr      104: 
1.1090    raeburn   105: use File::Copy;
1.676     albertel  106: 
1.195     www       107: my $readit;
1.1288    damieng   108: my $max_connection_retries = 20;     # Or some such value.
1.1       albertel  109: 
1.619     albertel  110: require Exporter;
                    111: 
                    112: our @ISA = qw (Exporter);
                    113: our @EXPORT = qw(%env);
                    114: 
1.449     matthew   115: 
1.1187    raeburn   116: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       117: {
                    118:     my $logid;
1.1187    raeburn   119:     sub write_log {
1.1188    raeburn   120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184    raeburn   121:         if ($context eq 'course') {
                    122:             if (($cnum eq '') || ($cdom eq '')) {
                    123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    125:             }
1.957     raeburn   126:         }
1.1184    raeburn   127: 	$logid ++;
1.957     raeburn   128:         my $now = time();
                    129: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1184    raeburn   130:         my $logentry = { 
                    131:                           $id => {
                    132:                                    'exe_uname' => $env{'user.name'},
                    133:                                    'exe_udom'  => $env{'user.domain'},
                    134:                                    'exe_time'  => $now,
                    135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    136:                                    'delflag'   => $delflag,
                    137:                                    'logentry'  => $storehash,
                    138:                                    'uname'     => $uname,
                    139:                                    'udom'      => $udom,
                    140:                                   }
                    141:                        };
                    142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       143:     }
                    144: }
1.1       albertel  145: 
1.163     harris41  146: sub logtouch {
                    147:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  148:     unless (-e "$execdir/logs/lonnet.log") {	
                    149: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  150: 	close $fh;
                    151:     }
                    152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    154: }
                    155: 
1.1       albertel  156: sub logthis {
                    157:     my $message=shift;
                    158:     my $execdir=$perlvar{'lonDaemons'};
                    159:     my $now=time;
                    160:     my $local=localtime($now);
1.448     albertel  161:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    163: 	print $fh $logstring;
1.448     albertel  164: 	close($fh);
                    165:     }
1.1       albertel  166:     return 1;
                    167: }
                    168: 
                    169: sub logperm {
                    170:     my $message=shift;
                    171:     my $execdir=$perlvar{'lonDaemons'};
                    172:     my $now=time;
                    173:     my $local=localtime($now);
1.448     albertel  174:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    175: 	print $fh "$now:$message:$local\n";
                    176: 	close($fh);
                    177:     }
1.1       albertel  178:     return 1;
                    179: }
                    180: 
1.850     albertel  181: sub create_connection {
1.853     albertel  182:     my ($hostname,$lonid) = @_;
1.851     albertel  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  184: 				     Type    => SOCK_STREAM,
                    185: 				     Timeout => 10);
                    186:     return 0 if (!$client);
1.890     albertel  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  188:     my $result = <$client>;
                    189:     chomp($result);
                    190:     return 1 if ($result eq 'done');
                    191:     return 0;
                    192: }
                    193: 
1.983     raeburn   194: sub get_server_timezone {
                    195:     my ($cnum,$cdom) = @_;
                    196:     my $home=&homeserver($cnum,$cdom);
                    197:     if ($home ne 'no_host') {
                    198:         my $cachetime = 24*3600;
                    199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    200:         if (defined($cached)) {
                    201:             return $timezone;
                    202:         } else {
                    203:             my $timezone = &reply('servertimezone',$home);
                    204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    205:         }
                    206:     }
                    207: }
1.850     albertel  208: 
1.1106    raeburn   209: sub get_server_distarch {
                    210:     my ($lonhost,$ignore_cache) = @_;
                    211:     if (defined($lonhost)) {
                    212:         if (!defined(&hostname($lonhost))) {
                    213:             return;
                    214:         }
                    215:         my $cachetime = 12*3600;
                    216:         if (!$ignore_cache) {
                    217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    218:             if (defined($cached)) {
                    219:                 return $distarch;
                    220:             }
                    221:         }
                    222:         my $rep = &reply('serverdistarch',$lonhost);
                    223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    225:                 $rep eq '') {
                    226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    227:         }
                    228:     }
                    229:     return;
                    230: }
                    231: 
1.1315    raeburn   232: sub get_servercerts_info {
                    233:     my ($lonhost,$context) = @_;
                    234:     my ($rep,$uselocal);
                    235:     if (grep { $_ eq $lonhost } &current_machine_ids()) {
                    236:         $uselocal = 1;
                    237:     }
1.1316    raeburn   238:     if (($context ne 'cgi') && ($uselocal)) {
1.1315    raeburn   239:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
1.1323    raeburn   240:         if ($distro eq '') {
                    241:             $uselocal = 0;
                    242:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
1.1315    raeburn   243:             if ($1 < 6) {
                    244:                 $uselocal = 0;
                    245:             }
                    246:         }
                    247:     }
                    248:     if ($uselocal) {
                    249:         $rep = LONCAPA::Lond::server_certs(\%perlvar);
                    250:     } else {
                    251:         $rep=&reply('servercerts',$lonhost);
                    252:     }
                    253:     my ($result,%returnhash);
                    254:     if (defined($lonhost)) {
                    255:         if (!defined(&hostname($lonhost))) {
                    256:             return;
                    257:         }
                    258:     }
                    259:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    260:         ($rep eq 'unknown_cmd')) {
                    261:         $result = $rep;
                    262:     } else {
                    263:         $result = 'ok';
                    264:         my @pairs=split(/\&/,$rep);
                    265:         foreach my $item (@pairs) {
                    266:             my ($key,$value)=split(/=/,$item,2);
                    267:             my $what = &unescape($key);
                    268:             $returnhash{$what}=&thaw_unescape($value);
                    269:         }
                    270:     }
                    271:     return ($result,\%returnhash);
                    272: }
                    273: 
1.993     raeburn   274: sub get_server_loncaparev {
1.1073    raeburn   275:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   276:     if (defined($lonhost)) {
                    277:         if (!defined(&hostname($lonhost))) {
                    278:             undef($lonhost);
                    279:         }
                    280:     }
                    281:     if (!defined($lonhost)) {
                    282:         if (defined(&domain($dom,'primary'))) {
                    283:             $lonhost=&domain($dom,'primary');
                    284:             if ($lonhost eq 'no_host') {
                    285:                 undef($lonhost);
                    286:             }
                    287:         }
                    288:     }
                    289:     if (defined($lonhost)) {
1.1073    raeburn   290:         my $cachetime = 12*3600;
                    291:         if (!$ignore_cache) {
                    292:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    293:             if (defined($cached)) {
                    294:                 return $loncaparev;
                    295:             }
                    296:         }
                    297:         my ($answer,$loncaparev);
                    298:         my @ids=&current_machine_ids();
                    299:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    300:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   301:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   302:                 $loncaparev = $1;
                    303:             }
                    304:         } else {
                    305:             $answer = &reply('serverloncaparev',$lonhost);
                    306:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    307:                 if ($caller eq 'loncron') {
                    308:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   309:                     $ua->timeout(4);
1.1073    raeburn   310:                     my $protocol = $protocol{$lonhost};
                    311:                     $protocol = 'http' if ($protocol ne 'https');
                    312:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    313:                     my $request=new HTTP::Request('GET',$url);
                    314:                     my $response=$ua->request($request);
                    315:                     unless ($response->is_error()) {
                    316:                         my $content = $response->content;
1.1081    raeburn   317:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   318:                             $loncaparev = $1;
                    319:                         }
                    320:                     }
                    321:                 } else {
                    322:                     $loncaparev = $loncaparevs{$lonhost};
                    323:                 }
1.1081    raeburn   324:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   325:                 $loncaparev = $1;
                    326:             }
1.993     raeburn   327:         }
1.1073    raeburn   328:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   329:     }
                    330: }
                    331: 
1.1074    raeburn   332: sub get_server_homeID {
                    333:     my ($hostname,$ignore_cache,$caller) = @_;
                    334:     unless ($ignore_cache) {
                    335:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    336:         if (defined($cached)) {
                    337:             return $serverhomeID;
                    338:         }
                    339:     }
                    340:     my $cachetime = 12*3600;
                    341:     my $serverhomeID;
                    342:     if ($caller eq 'loncron') { 
                    343:         my @machine_ids = &machine_ids($hostname);
                    344:         foreach my $id (@machine_ids) {
                    345:             my $response = &reply('serverhomeID',$id);
                    346:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    347:                 $serverhomeID = $response;
                    348:                 last;
                    349:             }
                    350:         }
                    351:         if ($serverhomeID eq '') {
                    352:             $serverhomeID = $machine_ids[-1];
                    353:         }
                    354:     } else {
                    355:         $serverhomeID = $serverhomeIDs{$hostname};
                    356:     }
                    357:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    358: }
                    359: 
1.1121    raeburn   360: sub get_remote_globals {
                    361:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   362:     my ($result,%returnhash,%whatneeded);
                    363:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   364:         foreach my $what (sort(keys(%{$whathash}))) {
                    365:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   366:             my ($response,$cached);
1.1121    raeburn   367:             unless ($ignore_cache) {
1.1125    raeburn   368:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   369:             }
                    370:             if (defined($cached)) {
1.1125    raeburn   371:                 $returnhash{$what} = $response;
1.1121    raeburn   372:             } else {
1.1125    raeburn   373:                 $whatneeded{$what} = 1;
1.1121    raeburn   374:             }
                    375:         }
1.1125    raeburn   376:         if (keys(%whatneeded) == 0) {
                    377:             $result = 'ok';
                    378:         } else {
1.1121    raeburn   379:             my $requested = &freeze_escape(\%whatneeded);
                    380:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   381:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    382:                 ($rep eq 'unknown_cmd')) {
                    383:                 $result = $rep;
                    384:             } else {
                    385:                 $result = 'ok';
1.1121    raeburn   386:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   387:                 foreach my $item (@pairs) {
                    388:                     my ($key,$value)=split(/=/,$item,2);
                    389:                     my $what = &unescape($key);
                    390:                     my $hashid = $lonhost.'-'.$what;
                    391:                     $returnhash{$what}=&thaw_unescape($value);
                    392:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   393:                 }
                    394:             }
                    395:         }
                    396:     }
1.1125    raeburn   397:     return ($result,\%returnhash);
1.1121    raeburn   398: }
                    399: 
1.1124    raeburn   400: sub remote_devalidate_cache {
1.1241    raeburn   401:     my ($lonhost,$cachekeys) = @_;
                    402:     my $items;
                    403:     return unless (ref($cachekeys) eq 'ARRAY');
                    404:     my $cachestr = join('&',@{$cachekeys});
                    405:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   406:     return $response;
                    407: }
                    408: 
1.1       albertel  409: # -------------------------------------------------- Non-critical communication
                    410: sub subreply {
                    411:     my ($cmd,$server)=@_;
1.838     albertel  412:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      413:     #
                    414:     #  With loncnew process trimming, there's a timing hole between lonc server
                    415:     #  process exit and the master server picking up the listen on the AF_UNIX
                    416:     #  socket.  In that time interval, a lock file will exist:
                    417: 
                    418:     my $lockfile=$peerfile.".lock";
                    419:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1289    damieng   420: 	sleep(0.1);
1.549     foxr      421:     }
                    422:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      423:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      424:     #
1.550     foxr      425:     #   We'll give the connection a few tries before abandoning it.  If
                    426:     #   connection is not possible, we'll con_lost back to the client.
                    427:     #   
                    428:     my $client;
                    429:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    430: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    431: 				      Type    => SOCK_STREAM,
                    432: 				      Timeout => 10);
1.869     albertel  433: 	if ($client) {
1.550     foxr      434: 	    last;		# Connected!
1.850     albertel  435: 	} else {
1.853     albertel  436: 	    &create_connection(&hostname($server),$server);
1.550     foxr      437: 	}
1.1289    damieng   438:         sleep(0.1);	# Try again later if failed connection.
1.550     foxr      439:     }
                    440:     my $answer;
                    441:     if ($client) {
1.704     albertel  442: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      443: 	$answer=<$client>;
                    444: 	if (!$answer) { $answer="con_lost"; }
                    445: 	chomp($answer);
                    446:     } else {
                    447: 	$answer = 'con_lost';	# Failed connection.
                    448:     }
1.1       albertel  449:     return $answer;
                    450: }
                    451: 
                    452: sub reply {
                    453:     my ($cmd,$server)=@_;
1.838     albertel  454:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  455:     my $answer=subreply($cmd,$server);
1.65      www       456:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  457:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       458:                 " $cmd to $server returned $answer</font>");
                    459:     }
1.1       albertel  460:     return $answer;
                    461: }
                    462: 
                    463: # ----------------------------------------------------------- Send USR1 to lonc
                    464: 
                    465: sub reconlonc {
1.891     albertel  466:     my ($lonid) = @_;
                    467:     if ($lonid) {
1.1295    raeburn   468:         my $hostname = &hostname($lonid);
1.891     albertel  469: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    470: 	if ($hostname && -e $peerfile) {
                    471: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    472: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    473: 					     Type    => SOCK_STREAM,
                    474: 					     Timeout => 10);
                    475: 	    if ($client) {
                    476: 		print $client ("reset_retries\n");
                    477: 		my $answer=<$client>;
                    478: 		#reset just this one.
                    479: 	    }
                    480: 	}
                    481: 	return;
                    482:     }
                    483: 
1.836     www       484:     &logthis("Trying to reconnect lonc");
1.1       albertel  485:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  486:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  487: 	my $loncpid=<$fh>;
                    488:         chomp($loncpid);
                    489:         if (kill 0 => $loncpid) {
                    490: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    491:             kill USR1 => $loncpid;
                    492:             sleep 1;
1.1295    raeburn   493:         } else {
1.12      www       494: 	    &logthis(
1.672     albertel  495:                "<font color=\"blue\">WARNING:".
1.12      www       496:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  497:         }
                    498:     } else {
1.836     www       499: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  500:     }
                    501: }
                    502: 
                    503: # ------------------------------------------------------ Critical communication
1.12      www       504: 
1.1       albertel  505: sub critical {
                    506:     my ($cmd,$server)=@_;
1.838     albertel  507:     unless (&hostname($server)) {
1.672     albertel  508:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       509:                " Critical message to unknown server ($server)</font>");
                    510:         return 'no_such_host';
                    511:     }
1.1       albertel  512:     my $answer=reply($cmd,$server);
                    513:     if ($answer eq 'con_lost') {
1.1295    raeburn   514: 	&reconlonc($server);
1.589     albertel  515: 	my $answer=reply($cmd,$server);
1.1       albertel  516:         if ($answer eq 'con_lost') {
                    517:             my $now=time;
                    518:             my $middlename=$cmd;
1.5       www       519:             $middlename=substr($middlename,0,16);
1.1       albertel  520:             $middlename=~s/\W//g;
                    521:             my $dfilename=
1.305     www       522:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    523:             $dumpcount++;
1.1       albertel  524:             {
1.448     albertel  525: 		my $dfh;
                    526: 		if (open($dfh,">$dfilename")) {
                    527: 		    print $dfh "$cmd\n"; 
                    528: 		    close($dfh);
                    529: 		}
1.1       albertel  530:             }
1.1288    damieng   531:             sleep 1;
1.1       albertel  532:             my $wcmd='';
                    533:             {
1.448     albertel  534: 		my $dfh;
                    535: 		if (open($dfh,"<$dfilename")) {
                    536: 		    $wcmd=<$dfh>; 
                    537: 		    close($dfh);
                    538: 		}
1.1       albertel  539:             }
                    540:             chomp($wcmd);
1.7       www       541:             if ($wcmd eq $cmd) {
1.672     albertel  542: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       543:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  544:                 &logperm("D:$server:$cmd");
                    545: 	        return 'con_delayed';
                    546:             } else {
1.672     albertel  547:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       548:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  549:                 &logperm("F:$server:$cmd");
                    550:                 return 'con_failed';
                    551:             }
                    552:         }
                    553:     }
                    554:     return $answer;
1.405     albertel  555: }
                    556: 
1.755     albertel  557: # ------------------------------------------- check if return value is an error
                    558: 
                    559: sub error {
                    560:     my ($result) = @_;
1.756     albertel  561:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  562: 	if ($2 == 2) { return undef; }
                    563: 	return $1;
                    564:     }
                    565:     return undef;
                    566: }
                    567: 
1.783     albertel  568: sub convert_and_load_session_env {
                    569:     my ($lonidsdir,$handle)=@_;
                    570:     my @profile;
                    571:     {
1.917     albertel  572: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    573: 	if (!$opened) {
1.915     albertel  574: 	    return 0;
                    575: 	}
1.783     albertel  576: 	flock($idf,LOCK_SH);
                    577: 	@profile=<$idf>;
                    578: 	close($idf);
                    579:     }
                    580:     my %temp_env;
                    581:     foreach my $line (@profile) {
1.786     albertel  582: 	if ($line !~ m/=/) {
                    583: 	    return 0;
                    584: 	}
1.783     albertel  585: 	chomp($line);
                    586: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    587: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    588:     }
                    589:     unlink("$lonidsdir/$handle.id");
                    590:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    591: 	    0640)) {
                    592: 	%disk_env = %temp_env;
                    593: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    594: 	untie(%disk_env);
                    595:     }
1.786     albertel  596:     return 1;
1.783     albertel  597: }
                    598: 
1.374     www       599: # ------------------------------------------- Transfer profile into environment
1.780     albertel  600: my $env_loaded;
                    601: sub transfer_profile_to_env {
1.788     albertel  602:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    603:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       604: 
1.720     albertel  605:     if (!defined($lonidsdir)) {
                    606: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    607:     }
                    608:     if (!defined($handle)) {
                    609:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    610:     }
                    611: 
1.786     albertel  612:     my $convert;
                    613:     {
1.917     albertel  614:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    615: 	if (!$opened) {
1.915     albertel  616: 	    return;
                    617: 	}
1.786     albertel  618: 	flock($idf,LOCK_SH);
                    619: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    620: 		&GDBM_READER(),0640)) {
                    621: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    622: 	    untie(%disk_env);
                    623: 	} else {
                    624: 	    $convert = 1;
                    625: 	}
                    626:     }
                    627:     if ($convert) {
                    628: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    629: 	    &logthis("Failed to load session, or convert session.");
                    630: 	}
1.374     www       631:     }
1.783     albertel  632: 
1.786     albertel  633:     my %remove;
1.783     albertel  634:     while ( my $envname = each(%env) ) {
1.433     matthew   635:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    636:             if ($time < time-300) {
1.783     albertel  637:                 $remove{$key}++;
1.433     matthew   638:             }
                    639:         }
                    640:     }
1.783     albertel  641: 
1.619     albertel  642:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  643:     $env_loaded=1;
1.783     albertel  644:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   645:         &delenv($expired_key);
1.374     www       646:     }
1.1       albertel  647: }
                    648: 
1.916     albertel  649: # ---------------------------------------------------- Check for valid session 
                    650: sub check_for_valid_session {
1.1245    raeburn   651:     my ($r,$name,$userhashref) = @_;
1.916     albertel  652:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155    raeburn   653:     if ($name eq '') {
                    654:         $name = 'lonID';
                    655:     }
                    656:     my $lonid=$cookies{$name};
1.916     albertel  657:     return undef if (!$lonid);
                    658: 
                    659:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155    raeburn   660:     my $lonidsdir;
                    661:     if ($name eq 'lonDAV') {
                    662:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    663:     } else {
                    664:         $lonidsdir=$r->dir_config('lonIDsDir');
                    665:     }
1.916     albertel  666:     return undef if (!-e "$lonidsdir/$handle.id");
                    667: 
1.917     albertel  668:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    669:     return undef if (!$opened);
1.916     albertel  670: 
                    671:     flock($idf,LOCK_SH);
                    672:     my %disk_env;
                    673:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    674: 	    &GDBM_READER(),0640)) {
                    675: 	return undef;	
                    676:     }
                    677: 
                    678:     if (!defined($disk_env{'user.name'})
                    679: 	|| !defined($disk_env{'user.domain'})) {
                    680: 	return undef;
                    681:     }
1.1245    raeburn   682: 
                    683:     if (ref($userhashref) eq 'HASH') {
                    684:         $userhashref->{'name'} = $disk_env{'user.name'};
                    685:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1212    raeburn   686:     }
1.1245    raeburn   687: 
1.916     albertel  688:     return $handle;
                    689: }
                    690: 
1.830     albertel  691: sub timed_flock {
                    692:     my ($file,$lock_type) = @_;
                    693:     my $failed=0;
                    694:     eval {
                    695: 	local $SIG{__DIE__}='DEFAULT';
                    696: 	local $SIG{ALRM}=sub {
                    697: 	    $failed=1;
                    698: 	    die("failed lock");
                    699: 	};
                    700: 	alarm(13);
                    701: 	flock($file,$lock_type);
                    702: 	alarm(0);
                    703:     };
                    704:     if ($failed) {
                    705: 	return undef;
                    706:     } else {
                    707: 	return 1;
                    708:     }
                    709: }
                    710: 
1.5       www       711: # ---------------------------------------------------------- Append Environment
                    712: 
                    713: sub appenv {
1.949     raeburn   714:     my ($newenv,$roles) = @_;
                    715:     if (ref($newenv) eq 'HASH') {
                    716:         foreach my $key (keys(%{$newenv})) {
                    717:             my $refused = 0;
                    718: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    719:                 $refused = 1;
                    720:                 if (ref($roles) eq 'ARRAY') {
1.1250    raeburn   721:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   722:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    723:                         $refused = 0;
                    724:                     }
                    725:                 }
                    726:             }
                    727:             if ($refused) {
                    728:                 &logthis("<font color=\"blue\">WARNING: ".
                    729:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    730:                          .'</font>');
                    731: 	        delete($newenv->{$key});
                    732:             } else {
                    733:                 $env{$key}=$newenv->{$key};
                    734:             }
                    735:         }
                    736:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    737:         if ($opened
                    738: 	    && &timed_flock($env_file,LOCK_EX)
                    739: 	    &&
                    740: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    741: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    742: 	    while (my ($key,$value) = each(%{$newenv})) {
                    743: 	        $disk_env{$key} = $value;
                    744: 	    }
                    745: 	    untie(%disk_env);
1.35      www       746:         }
1.191     harris41  747:     }
1.56      www       748:     return 'ok';
                    749: }
                    750: # ----------------------------------------------------- Delete from Environment
                    751: 
                    752: sub delenv {
1.1104    raeburn   753:     my ($delthis,$regexp,$roles) = @_;
                    754:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    755:         my $refused = 1;
                    756:         if (ref($roles) eq 'ARRAY') {
                    757:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    758:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    759:                 $refused = 0;
                    760:             }
                    761:         }
                    762:         if ($refused) {
                    763:             &logthis("<font color=\"blue\">WARNING: ".
                    764:                      "Attempt to delete from environment ".$delthis);
                    765:             return 'error';
                    766:         }
1.56      www       767:     }
1.917     albertel  768:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    769:     if ($opened
1.915     albertel  770: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  771: 	&&
                    772: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    773: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  774: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   775: 	    if ($regexp) {
                    776:                 if ($key=~/^$delthis/) {
                    777:                     delete($env{$key});
                    778:                     delete($disk_env{$key});
                    779:                 } 
                    780:             } else {
                    781:                 if ($key=~/^\Q$delthis\E/) {
                    782: 		    delete($env{$key});
                    783: 		    delete($disk_env{$key});
                    784: 	        }
                    785:             }
1.448     albertel  786: 	}
1.783     albertel  787: 	untie(%disk_env);
1.5       www       788:     }
                    789:     return 'ok';
1.369     albertel  790: }
                    791: 
1.790     albertel  792: sub get_env_multiple {
                    793:     my ($name) = @_;
                    794:     my @values;
                    795:     if (defined($env{$name})) {
                    796:         # exists is it an array
                    797:         if (ref($env{$name})) {
                    798:             @values=@{ $env{$name} };
                    799:         } else {
                    800:             $values[0]=$env{$name};
                    801:         }
                    802:     }
                    803:     return(@values);
                    804: }
                    805: 
1.958     www       806: # ------------------------------------------------------------------- Locking
                    807: 
                    808: sub set_lock {
                    809:     my ($text)=@_;
                    810:     $locknum++;
                    811:     my $id=$$.'-'.$locknum;
                    812:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    813:              'session.lock.'.$id => $text});
                    814:     return $id;
                    815: }
                    816: 
                    817: sub get_locks {
                    818:     my $num=0;
                    819:     my %texts=();
                    820:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    821:        if ($lock=~/\w/) {
                    822:           $num++;
                    823:           $texts{$lock}=$env{'session.lock.'.$lock};
                    824:        }
                    825:    }
                    826:    return ($num,%texts);
                    827: }
                    828: 
                    829: sub remove_lock {
                    830:     my ($id)=@_;
                    831:     my $newlocks='';
                    832:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    833:        if (($lock=~/\w/) && ($lock ne $id)) {
                    834:           $newlocks.=','.$lock;
                    835:        }
                    836:     }
                    837:     &appenv({'session.locks' => $newlocks});
                    838:     &delenv('session.lock.'.$id);
                    839: }
                    840: 
                    841: sub remove_all_locks {
                    842:     my $activelocks=$env{'session.locks'};
                    843:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    844:        if ($lock=~/\w/) {
                    845:           &remove_lock($lock);
                    846:        }
                    847:     }
                    848: }
                    849: 
                    850: 
1.369     albertel  851: # ------------------------------------------ Find out current server userload
                    852: sub userload {
                    853:     my $numusers=0;
                    854:     {
                    855: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    856: 	my $filename;
                    857: 	my $curtime=time;
                    858: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  859: 	    next if ($filename eq '.' || $filename eq '..');
                    860: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  861: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  862: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  863: 	}
                    864: 	closedir(LONIDS);
                    865:     }
                    866:     my $userloadpercent=0;
                    867:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    868:     if ($maxuserload) {
1.371     albertel  869: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  870:     }
1.372     albertel  871:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  872:     return $userloadpercent;
1.283     www       873: }
                    874: 
1.1       albertel  875: # ------------------------------ Find server with least workload from spare.tab
1.11      www       876: 
1.1       albertel  877: sub spareserver {
1.1083    raeburn   878:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  879:     my $spare_server;
1.370     albertel  880:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  881:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    882:                                                      :  $userloadpercent;
1.1083    raeburn   883:     my ($uint_dom,$remotesessions);
                    884:     if (($udom ne '') && (&domain($udom) ne '')) {
                    885:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    886:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    887:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    888:         $remotesessions = $udomdefaults{'remotesessions'};
                    889:     }
1.1123    raeburn   890:     my $spareshash = &this_host_spares($udom);
                    891:     if (ref($spareshash) eq 'HASH') {
                    892:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    893:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279    raeburn   894:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    895:                                              $try_server));
1.1123    raeburn   896: 	        ($spare_server, $lowest_load) =
                    897: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    898:             }
1.1083    raeburn   899:         }
1.784     albertel  900: 
1.1123    raeburn   901:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    902: 
                    903:         if (!$found_server) {
                    904:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    905: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279    raeburn   906:                     next unless (&spare_can_host($udom,$uint_dom,
                    907:                                                  $remotesessions,$try_server));
1.1123    raeburn   908: 	            ($spare_server, $lowest_load) =
                    909: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    910:                 }
                    911: 	    }
                    912:         }
1.784     albertel  913:     }
                    914: 
                    915:     if (!$want_server_name) {
1.968     raeburn   916:         my $protocol = 'http';
                    917:         if ($protocol{$spare_server} eq 'https') {
                    918:             $protocol = $protocol{$spare_server};
                    919:         }
1.1001    raeburn   920:         if (defined($spare_server)) {
                    921:             my $hostname = &hostname($spare_server);
1.1083    raeburn   922:             if (defined($hostname)) {
1.1001    raeburn   923: 	        $spare_server = $protocol.'://'.$hostname;
                    924:             }
                    925:         }
1.784     albertel  926:     }
                    927:     return $spare_server;
                    928: }
                    929: 
                    930: sub compare_server_load {
1.1253    raeburn   931:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    932: 
                    933:     if ($required) {
                    934:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    935:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    936:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    937:         if (($major eq '' && $minor eq '') ||
                    938:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    939:             return ($spare_server,$lowest_load);
                    940:         }
                    941:     }
1.784     albertel  942: 
                    943:     my $loadans     = &reply('load',    $try_server);
                    944:     my $userloadans = &reply('userload',$try_server);
                    945: 
                    946:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   947: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  948:     }
                    949: 
                    950:     my $load;
                    951:     if ($loadans =~ /\d/) {
                    952: 	if ($userloadans =~ /\d/) {
                    953: 	    #both are numbers, pick the bigger one
                    954: 	    $load = ($loadans > $userloadans) ? $loadans 
                    955: 		                              : $userloadans;
1.411     albertel  956: 	} else {
1.784     albertel  957: 	    $load = $loadans;
1.411     albertel  958: 	}
1.784     albertel  959:     } else {
                    960: 	$load = $userloadans;
                    961:     }
                    962: 
                    963:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    964: 	$spare_server = $try_server;
                    965: 	$lowest_load  = $load;
1.370     albertel  966:     }
1.784     albertel  967:     return ($spare_server,$lowest_load);
1.202     matthew   968: }
1.914     albertel  969: 
                    970: # --------------------------- ask offload servers if user already has a session
                    971: sub find_existing_session {
                    972:     my ($udom,$uname) = @_;
1.1123    raeburn   973:     my $spareshash = &this_host_spares($udom);
                    974:     if (ref($spareshash) eq 'HASH') {
                    975:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    976:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    977:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    978:             }
                    979:         }
                    980:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    981:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    982:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    983:             }
                    984:         }
1.914     albertel  985:     }
                    986:     return;
                    987: }
                    988: 
                    989: # -------------------------------- ask if server already has a session for user
                    990: sub has_user_session {
                    991:     my ($lonid,$udom,$uname) = @_;
                    992:     my $result = &reply(join(':','userhassession',
                    993: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    994:     return 1 if ($result eq 'ok');
                    995: 
                    996:     return 0;
                    997: }
                    998: 
1.1076    raeburn   999: # --------- determine least loaded server in a user's domain which allows login
                   1000: 
                   1001: sub choose_server {
1.1259    raeburn  1002:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1003:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1004:     my %servers = &get_servers($udom);
1.1076    raeburn  1005:     my $lowest_load = 30000;
1.1259    raeburn  1006:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1007:     if ($skiploadbal) {
                   1008:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1009:         unless (defined($cached)) {
                   1010:             my $cachetime = 60*60*24;
                   1011:             my %domconfig =
                   1012:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1013:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1014:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1015:                                            $cachetime);
                   1016:             }
                   1017:         }
                   1018:     }
1.1076    raeburn  1019:     foreach my $lonhost (keys(%servers)) {
1.1259    raeburn  1020:         if ($skiploadbal) {
                   1021:             if (ref($balancers) eq 'HASH') {
                   1022:                 next if (exists($balancers->{$lonhost}));
                   1023:             }
                   1024:         }   
1.1115    raeburn  1025:         my $loginvia;
                   1026:         if ($checkloginvia) {
                   1027:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1028:             if ($loginvia) {
                   1029:                 my ($server,$path) = split(/:/,$loginvia);
                   1030:                 ($login_host, $lowest_load) =
1.1253    raeburn  1031:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1032:                 if ($login_host eq $server) {
                   1033:                     $portal_path = $path;
1.1151    raeburn  1034:                     $isredirect = 1;
1.1116    raeburn  1035:                 }
                   1036:             } else {
                   1037:                 ($login_host, $lowest_load) =
1.1253    raeburn  1038:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1039:                 if ($login_host eq $lonhost) {
                   1040:                     $portal_path = '';
1.1151    raeburn  1041:                     $isredirect = ''; 
1.1116    raeburn  1042:                 }
                   1043:             }
                   1044:         } else {
1.1076    raeburn  1045:             ($login_host, $lowest_load) =
1.1253    raeburn  1046:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1047:         }
                   1048:     }
                   1049:     if ($login_host ne '') {
1.1116    raeburn  1050:         $hostname = &hostname($login_host);
1.1076    raeburn  1051:     }
1.1151    raeburn  1052:     return ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn  1053: }
                   1054: 
1.202     matthew  1055: # --------------------------------------------- Try to change a user's password
                   1056: 
                   1057: sub changepass {
1.799     raeburn  1058:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1059:     $currentpass = &escape($currentpass);
                   1060:     $newpass     = &escape($newpass);
1.1030    raeburn  1061:     my $lonhost = $perlvar{'lonHostID'};
                   1062:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1063: 		       $server);
                   1064:     if (! $answer) {
                   1065: 	&logthis("No reply on password change request to $server ".
                   1066: 		 "by $uname in domain $udom.");
                   1067:     } elsif ($answer =~ "^ok") {
                   1068:         &logthis("$uname in $udom successfully changed their password ".
                   1069: 		 "on $server.");
                   1070:     } elsif ($answer =~ "^pwchange_failure") {
                   1071: 	&logthis("$uname in $udom was unable to change their password ".
                   1072: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1073: 		 "or pwchange");
                   1074:     } elsif ($answer =~ "^non_authorized") {
                   1075:         &logthis("$uname in $udom did not get their password correct when ".
                   1076: 		 "attempting to change it on $server.");
                   1077:     } elsif ($answer =~ "^auth_mode_error") {
                   1078:         &logthis("$uname in $udom attempted to change their password despite ".
                   1079: 		 "not being locally or internally authenticated on $server.");
                   1080:     } elsif ($answer =~ "^unknown_user") {
                   1081:         &logthis("$uname in $udom attempted to change their password ".
                   1082: 		 "on $server but were unable to because $server is not ".
                   1083: 		 "their home server.");
                   1084:     } elsif ($answer =~ "^refused") {
                   1085: 	&logthis("$server refused to change $uname in $udom password because ".
                   1086: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1087:     } elsif ($answer =~ "invalid_client") {
                   1088:         &logthis("$server refused to change $uname in $udom password because ".
                   1089:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1090:     }
                   1091:     return $answer;
1.1       albertel 1092: }
                   1093: 
1.169     harris41 1094: # ----------------------- Try to determine user's current authentication scheme
                   1095: 
                   1096: sub queryauthenticate {
                   1097:     my ($uname,$udom)=@_;
1.456     albertel 1098:     my $uhome=&homeserver($uname,$udom);
                   1099:     if (!$uhome) {
                   1100: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1101: 	return 'no_host';
                   1102:     }
                   1103:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1104:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1105: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1106:     }
1.456     albertel 1107:     return $answer;
1.169     harris41 1108: }
                   1109: 
1.1       albertel 1110: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1111: 
1.1       albertel 1112: sub authenticate {
1.1073    raeburn  1113:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1114:     $upass=&escape($upass);
                   1115:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1116:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1117:     my $newhome;
1.836     www      1118:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1119: # Maybe the machine was offline and only re-appeared again recently?
                   1120:         &reconlonc();
                   1121: # One more
1.952     raeburn  1122: 	$uhome=&homeserver($uname,$udom,1);
                   1123:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1124:             if (defined(&domain($udom,'primary'))) {
                   1125:                 $newhome=&domain($udom,'primary');
                   1126:             }
                   1127:             if ($newhome ne '') {
                   1128:                 $uhome = $newhome;
                   1129:             }
                   1130:         }
1.836     www      1131: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1132: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1133: 	    return 'no_host';
                   1134:         }
1.1       albertel 1135:     }
1.1073    raeburn  1136:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1137:     if ($answer eq 'authorized') {
1.952     raeburn  1138:         if ($newhome) {
                   1139:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1140:             return 'no_account_on_host'; 
                   1141:         } else {
                   1142:             &logthis("User $uname at $udom authorized by $uhome");
                   1143:             return $uhome;
                   1144:         }
1.471     albertel 1145:     }
                   1146:     if ($answer eq 'non_authorized') {
                   1147: 	&logthis("User $uname at $udom rejected by $uhome");
                   1148: 	return 'no_host'; 
1.9       www      1149:     }
1.471     albertel 1150:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1151:     return 'no_host';
                   1152: }
                   1153: 
1.1073    raeburn  1154: sub can_host_session {
1.1074    raeburn  1155:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1156:     my $canhost = 1;
1.1074    raeburn  1157:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1158:     if (ref($remotesessions) eq 'HASH') {
                   1159:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1160:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1161:                 $canhost = 0;
                   1162:             } else {
                   1163:                 $canhost = 1;
                   1164:             }
                   1165:         }
                   1166:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1167:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1168:                 $canhost = 1;
                   1169:             } else {
                   1170:                 $canhost = 0;
                   1171:             }
                   1172:         }
                   1173:         if ($canhost) {
                   1174:             if ($remotesessions->{'version'} ne '') {
                   1175:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1176:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1177:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1178:                         my $major = $1;
                   1179:                         my $minor = $2;
                   1180:                         if (($major < $reqmajor ) ||
                   1181:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1182:                             $canhost = 0;
                   1183:                         }
                   1184:                     } else {
                   1185:                         $canhost = 0;
                   1186:                     }
                   1187:                 }
                   1188:             }
                   1189:         }
                   1190:     }
                   1191:     if ($canhost) {
                   1192:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1193:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1194:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1195:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1196:                 if (($uint_dom ne '') && 
                   1197:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1198:                     $canhost = 0;
                   1199:                 } else {
                   1200:                     $canhost = 1;
                   1201:                 }
                   1202:             }
                   1203:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1204:                 if (($uint_dom ne '') && 
                   1205:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1206:                     $canhost = 1;
                   1207:                 } else {
                   1208:                     $canhost = 0;
                   1209:                 }
                   1210:             }
                   1211:         }
                   1212:     }
                   1213:     return $canhost;
                   1214: }
                   1215: 
1.1083    raeburn  1216: sub spare_can_host {
                   1217:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1218:     my $canhost=1;
1.1279    raeburn  1219:     my $try_server_hostname = &hostname($try_server);
                   1220:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1221:     my $serverhomedom = &host_domain($serverhomeID);
                   1222:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1223:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1224:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1225:             $canhost = 0;
                   1226:         }
                   1227:     }
                   1228:     if (($canhost) && ($uint_dom)) {
                   1229:         my @intdoms;
                   1230:         my $internet_names = &get_internet_names($try_server);
                   1231:         if (ref($internet_names) eq 'ARRAY') {
                   1232:             @intdoms = @{$internet_names};
                   1233:         }
                   1234:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1235:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1236:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1237:                                          $remotesessions,
                   1238:                                          $defdomdefaults{'hostedsessions'});
                   1239:         }
1.1083    raeburn  1240:     }
                   1241:     return $canhost;
                   1242: }
                   1243: 
1.1123    raeburn  1244: sub this_host_spares {
                   1245:     my ($dom) = @_;
1.1126    raeburn  1246:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1247:     my @hosts = &current_machine_ids();
                   1248:     foreach my $lonhost (@hosts) {
                   1249:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1250:             $dom_in_use = $dom;
                   1251:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1252:             last;
                   1253:         }
                   1254:     }
1.1126    raeburn  1255:     if ($dom_in_use ne '') {
                   1256:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1257:     }
                   1258:     if (ref($result) ne 'HASH') {
                   1259:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1260:         $dom_in_use = &host_domain($lonhost_in_use);
                   1261:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1262:         if (ref($result) ne 'HASH') {
                   1263:             $result = \%spareid;
                   1264:         }
                   1265:     }
                   1266:     return $result;
                   1267: }
                   1268: 
                   1269: sub spares_for_offload  {
                   1270:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1271:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1272:     if (defined($cached)) {
                   1273:         return $result;
                   1274:     } else {
1.1126    raeburn  1275:         my $cachetime = 60*60*24;
                   1276:         my %domconfig =
                   1277:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1278:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1279:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1280:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1281:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1282:                 }
                   1283:             }
                   1284:         }
                   1285:     }
1.1126    raeburn  1286:     return;
1.1123    raeburn  1287: }
                   1288: 
1.1129    raeburn  1289: sub get_lonbalancer_config {
                   1290:     my ($servers) = @_;
                   1291:     my ($currbalancer,$currtargets);
                   1292:     if (ref($servers) eq 'HASH') {
                   1293:         foreach my $server (keys(%{$servers})) {
                   1294:             my %what = (
                   1295:                          spareid => 1,
                   1296:                          perlvar => 1,
                   1297:                        );
                   1298:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1299:             if ($result eq 'ok') {
                   1300:                 if (ref($returnhash) eq 'HASH') {
                   1301:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1302:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1303:                             $currbalancer = $server;
                   1304:                             $currtargets = {};
                   1305:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1306:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1307:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1308:                                 }
                   1309:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1310:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1311:                                 }
                   1312:                             }
                   1313:                             last;
                   1314:                         }
                   1315:                     }
                   1316:                 }
                   1317:             }
                   1318:         }
                   1319:     }
                   1320:     return ($currbalancer,$currtargets);
                   1321: }
                   1322: 
                   1323: sub check_loadbalancing {
                   1324:     my ($uname,$udom) = @_;
1.1191    raeburn  1325:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1326:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1327:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1328:     my @hosts = &current_machine_ids();
1.1129    raeburn  1329:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1330:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1331:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1332:     my $serverhomedom = &host_domain($lonhost);
1.1307    raeburn  1333:     my $domneedscache;
1.1129    raeburn  1334:     my $cachetime = 60*60*24;
                   1335: 
                   1336:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1337:         $dom_in_use = $udom;
                   1338:         $homeintdom = 1;
                   1339:     } else {
                   1340:         $dom_in_use = $serverhomedom;
                   1341:     }
                   1342:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1343:     unless (defined($cached)) {
                   1344:         my %domconfig =
                   1345:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1346:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1347:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307    raeburn  1348:         } else {
                   1349:             $domneedscache = $dom_in_use;
1.1129    raeburn  1350:         }
                   1351:     }
                   1352:     if (ref($result) eq 'HASH') {
1.1191    raeburn  1353:         ($is_balancer,$currtargets,$currrules) = 
                   1354:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1355:         if ($is_balancer) {
                   1356:             if (ref($currrules) eq 'HASH') {
                   1357:                 if ($homeintdom) {
                   1358:                     if ($uname ne '') {
                   1359:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1360:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1361:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1362:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1363:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1364:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1365:                             }
                   1366:                         }
                   1367:                         if ($rule_in_effect eq '') {
                   1368:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1369:                             if ($userenv{'inststatus'} ne '') {
                   1370:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1371:                                 my ($othertitle,$usertypes,$types) =
                   1372:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1373:                                 if (ref($types) eq 'ARRAY') {
                   1374:                                     foreach my $type (@{$types}) {
                   1375:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1376:                                             if (exists($currrules->{$type})) {
                   1377:                                                 $rule_in_effect = $currrules->{$type};
                   1378:                                             }
                   1379:                                         }
                   1380:                                     }
                   1381:                                 }
                   1382:                             } else {
                   1383:                                 if (exists($currrules->{'default'})) {
                   1384:                                     $rule_in_effect = $currrules->{'default'};
                   1385:                                 }
                   1386:                             }
                   1387:                         }
                   1388:                     } else {
                   1389:                         if (exists($currrules->{'default'})) {
                   1390:                             $rule_in_effect = $currrules->{'default'};
                   1391:                         }
                   1392:                     }
                   1393:                 } else {
                   1394:                     if ($currrules->{'_LC_external'} ne '') {
                   1395:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1396:                     }
                   1397:                 }
                   1398:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1399:                                                        $uname,$udom);
                   1400:             }
                   1401:         }
                   1402:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1403:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1404:         unless (defined($cached)) {
                   1405:             my %domconfig =
                   1406:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1407:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307    raeburn  1408:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1409:             } else {
                   1410:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1411:             }
                   1412:         }
                   1413:         if (ref($result) eq 'HASH') {
1.1191    raeburn  1414:             ($is_balancer,$currtargets,$currrules) = 
                   1415:                 &check_balancer_result($result,@hosts);
                   1416:             if ($is_balancer) {
1.1129    raeburn  1417:                 if (ref($currrules) eq 'HASH') {
                   1418:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1419:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1420:                     }
                   1421:                 }
                   1422:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1423:                                                        $uname,$udom);
                   1424:             }
                   1425:         } else {
                   1426:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1427:                 $is_balancer = 1;
                   1428:                 $offloadto = &this_host_spares($dom_in_use);
                   1429:             }
1.1307    raeburn  1430:             unless (defined($cached)) {
                   1431:                 $domneedscache = $serverhomedom;
                   1432:             }
1.1129    raeburn  1433:         }
                   1434:     } else {
                   1435:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1436:             $is_balancer = 1;
                   1437:             $offloadto = &this_host_spares($dom_in_use);
                   1438:         }
1.1307    raeburn  1439:         unless (defined($cached)) {
                   1440:             $domneedscache = $serverhomedom;
                   1441:         }
                   1442:     }
                   1443:     if ($domneedscache) {
                   1444:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1445:     }
1.1176    raeburn  1446:     if ($is_balancer) {
                   1447:         my $lowest_load = 30000;
                   1448:         if (ref($offloadto) eq 'HASH') {
                   1449:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1450:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1451:                     ($otherserver,$lowest_load) =
                   1452:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1453:                 }
1.1129    raeburn  1454:             }
1.1176    raeburn  1455:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1456: 
1.1176    raeburn  1457:             if (!$found_server) {
                   1458:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1459:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1460:                         ($otherserver,$lowest_load) =
                   1461:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1462:                     }
                   1463:                 }
                   1464:             }
                   1465:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1466:             if (@{$offloadto} == 1) {
                   1467:                 $otherserver = $offloadto->[0];
                   1468:             } elsif (@{$offloadto} > 1) {
                   1469:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1470:                     ($otherserver,$lowest_load) =
                   1471:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1472:                 }
                   1473:             }
                   1474:         }
1.1176    raeburn  1475:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1476:             $is_balancer = 0;
                   1477:             if ($uname ne '' && $udom ne '') {
                   1478:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1479:                     
                   1480:                     &appenv({'user.loadbalexempt'     => $lonhost,  
                   1481:                              'user.loadbalcheck.time' => time});
                   1482:                 }
1.1129    raeburn  1483:             }
                   1484:         }
                   1485:     }
                   1486:     return ($is_balancer,$otherserver);
                   1487: }
                   1488: 
1.1191    raeburn  1489: sub check_balancer_result {
                   1490:     my ($result,@hosts) = @_;
                   1491:     my ($is_balancer,$currtargets,$currrules);
                   1492:     if (ref($result) eq 'HASH') {
                   1493:         if ($result->{'lonhost'} ne '') {
                   1494:             my $currbalancer = $result->{'lonhost'};
                   1495:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1496:                 $is_balancer = 1;
                   1497:                 $currtargets = $result->{'targets'};
                   1498:                 $currrules = $result->{'rules'};
                   1499:             }
                   1500:         } else {
                   1501:             foreach my $key (keys(%{$result})) {
                   1502:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1503:                     (ref($result->{$key}) eq 'HASH')) {
                   1504:                     $is_balancer = 1;
                   1505:                     $currrules = $result->{$key}{'rules'};
                   1506:                     $currtargets = $result->{$key}{'targets'};
                   1507:                     last;
                   1508:                 }
                   1509:             }
                   1510:         }
                   1511:     }
                   1512:     return ($is_balancer,$currtargets,$currrules);
                   1513: }
                   1514: 
1.1129    raeburn  1515: sub get_loadbalancer_targets {
                   1516:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1517:     my $offloadto;
1.1175    raeburn  1518:     if ($rule_in_effect eq 'none') {
                   1519:         return [$perlvar{'lonHostID'}];
                   1520:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1521:         $offloadto = $currtargets;
                   1522:     } else {
                   1523:         if ($rule_in_effect eq 'homeserver') {
                   1524:             my $homeserver = &homeserver($uname,$udom);
                   1525:             if ($homeserver ne 'no_host') {
                   1526:                 $offloadto = [$homeserver];
                   1527:             }
                   1528:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1529:             my %domconfig =
                   1530:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1531:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1532:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1533:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1534:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1535:                     }
                   1536:                 }
                   1537:             } else {
1.1178    raeburn  1538:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1539:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1540:                 if (&hostname($remotebalancer) ne '') {
                   1541:                     $offloadto = [$remotebalancer];
                   1542:                 }
                   1543:             }
                   1544:         } elsif (&hostname($rule_in_effect) ne '') {
                   1545:             $offloadto = [$rule_in_effect];
                   1546:         }
                   1547:     }
                   1548:     return $offloadto;
                   1549: }
                   1550: 
1.1127    raeburn  1551: sub internet_dom_servers {
                   1552:     my ($dom) = @_;
                   1553:     my (%uniqservers,%servers);
                   1554:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1555:     my @machinedoms = &machine_domains($primaryserver);
                   1556:     foreach my $mdom (@machinedoms) {
                   1557:         my %currservers = %servers;
                   1558:         my %server = &get_servers($mdom);
                   1559:         %servers = (%currservers,%server);
                   1560:     }
                   1561:     my %by_hostname;
                   1562:     foreach my $id (keys(%servers)) {
                   1563:         push(@{$by_hostname{$servers{$id}}},$id);
                   1564:     }
                   1565:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1566:         if (@{$by_hostname{$hostname}} > 1) {
                   1567:             my $match = 0;
                   1568:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1569:                 if (&host_domain($id) eq $dom) {
                   1570:                     $uniqservers{$id} = $hostname;
                   1571:                     $match = 1;
                   1572:                 }
                   1573:             }
                   1574:             unless ($match) {
                   1575:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1576:             }
                   1577:         } else {
                   1578:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1579:         }
                   1580:     }
                   1581:     return %uniqservers;
                   1582: }
                   1583: 
1.1       albertel 1584: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1585: 
1.599     albertel 1586: my %homecache;
1.1       albertel 1587: sub homeserver {
1.230     stredwic 1588:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1589:     my $index="$uname:$udom";
1.426     albertel 1590: 
1.599     albertel 1591:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1592: 
                   1593:     my %servers = &get_servers($udom,'library');
                   1594:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1595:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1596: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1597: 
                   1598: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1599: 	if ($answer eq 'found') {
                   1600: 	    delete($badServerCache{$tryserver}); 
                   1601: 	    return $homecache{$index}=$tryserver;
                   1602: 	} elsif ($answer eq 'no_host') {
                   1603: 	    $badServerCache{$tryserver}=1;
                   1604: 	}
1.1       albertel 1605:     }    
                   1606:     return 'no_host';
1.70      www      1607: }
                   1608: 
1.1300    raeburn  1609: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70      www      1610: 
                   1611: sub idget {
1.1300    raeburn  1612:     my ($udom,$idsref,$namespace)=@_;
1.70      www      1613:     my %returnhash=();
1.1300    raeburn  1614:     my @ids=(); 
                   1615:     if (ref($idsref) eq 'ARRAY') {
                   1616:         @ids = @{$idsref};
                   1617:     } else {
                   1618:         return %returnhash; 
                   1619:     }
                   1620:     if ($namespace eq '') {
                   1621:         $namespace = 'ids';
                   1622:     }
1.70      www      1623:     
1.841     albertel 1624:     my %servers = &get_servers($udom,'library');
                   1625:     foreach my $tryserver (keys(%servers)) {
1.1299    raeburn  1626: 	my $idlist=join('&', map { &escape($_); } @ids);
1.1300    raeburn  1627: 	if ($namespace eq 'ids') {
                   1628: 	    $idlist=~tr/A-Z/a-z/;
                   1629: 	}
                   1630: 	my $reply;
                   1631: 	if ($namespace eq 'ids') {
                   1632: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1633: 	} else {
                   1634: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
                   1635: 	}
1.841     albertel 1636: 	my @answer=();
                   1637: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1638: 	    @answer=split(/\&/,$reply);
                   1639: 	}                    ;
                   1640: 	my $i;
                   1641: 	for ($i=0;$i<=$#ids;$i++) {
                   1642: 	    if ($answer[$i]) {
1.1299    raeburn  1643: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300    raeburn  1644: 	    }
1.841     albertel 1645: 	}
1.1300    raeburn  1646:     }
1.70      www      1647:     return %returnhash;
                   1648: }
                   1649: 
                   1650: # ------------------------------------- Find the IDs behind a list of usernames
                   1651: 
                   1652: sub idrget {
                   1653:     my ($udom,@unames)=@_;
                   1654:     my %returnhash=();
1.800     albertel 1655:     foreach my $uname (@unames) {
                   1656:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1657:     }
1.70      www      1658:     return %returnhash;
                   1659: }
                   1660: 
1.1300    raeburn  1661: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70      www      1662: 
                   1663: sub idput {
1.1300    raeburn  1664:     my ($udom,$idsref,$uhom,$namespace)=@_;
1.70      www      1665:     my %servers=();
1.1300    raeburn  1666:     my %ids=();
                   1667:     my %byid = ();
                   1668:     if (ref($idsref) eq 'HASH') {
                   1669:         %ids=%{$idsref};
                   1670:     }
                   1671:     if ($namespace eq '') {
                   1672:         $namespace = 'ids'; 
                   1673:     }
1.800     albertel 1674:     foreach my $uname (keys(%ids)) {
                   1675: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300    raeburn  1676:         if ($uhom eq '') {
                   1677:             $uhom=&homeserver($uname,$udom);
                   1678:         }
1.70      www      1679:         if ($uhom ne 'no_host') {
1.800     albertel 1680:             my $esc_unam=&escape($uname);
1.1300    raeburn  1681:             if ($namespace eq 'ids') {
                   1682:                 my $id=&escape($ids{$uname});
                   1683:                 $id=~tr/A-Z/a-z/;
                   1684:                 my $esc_unam=&escape($uname);
                   1685:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70      www      1686:             } else {
1.1300    raeburn  1687:                 my @currids = split(/,/,$ids{$uname});
                   1688:                 foreach my $id (@currids) {
                   1689:                     $byid{$uhom}{$id} .= $uname.',';
                   1690:                 }
                   1691:             }
                   1692:         }
                   1693:     }
                   1694:     if ($namespace eq 'clickers') {
                   1695:         foreach my $server (keys(%byid)) {
                   1696:             if (ref($byid{$server}) eq 'HASH') {
                   1697:                 foreach my $id (keys(%{$byid{$server}})) {
                   1698:                     $byid{$server} =~ s/,$//;
                   1699:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
                   1700:                 }
1.70      www      1701:             }
                   1702:         }
1.191     harris41 1703:     }
1.800     albertel 1704:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1705:         $servers{$server} =~ s/\&$//;
                   1706:         if ($namespace eq 'ids') {     
                   1707:             &critical('idput:'.$udom.':'.$servers{$server},$server);
                   1708:         } else {
                   1709:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
                   1710:         }
1.191     harris41 1711:     }
1.344     www      1712: }
                   1713: 
1.1300    raeburn  1714: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231    raeburn  1715: 
                   1716: sub iddel {
1.1300    raeburn  1717:     my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231    raeburn  1718:     my %result=();
1.1300    raeburn  1719:     my %ids=();
                   1720:     my %byid = ();
                   1721:     if (ref($idshashref) eq 'HASH') {
                   1722:         %ids=%{$idshashref};
                   1723:     } else {
1.1231    raeburn  1724:         return %result;
                   1725:     }
1.1300    raeburn  1726:     if ($namespace eq '') {
                   1727:         $namespace = 'ids';
                   1728:     }
1.1231    raeburn  1729:     my %servers=();
1.1300    raeburn  1730:     while (my ($id,$unamestr) = each(%ids)) {
                   1731:         if ($namespace eq 'ids') {
                   1732:             my $uhom = $uhome;
                   1733:             if ($uhom eq '') { 
                   1734:                 $uhom=&homeserver($unamestr,$udom);
                   1735:             }
                   1736:             if ($uhom ne 'no_host') {
                   1737:                 $servers{$uhom}.='&'.&escape($id);
                   1738:             }
                   1739:          } else {
                   1740:             my @curritems = split(/,/,$ids{$id});
                   1741:             foreach my $uname (@curritems) {
                   1742:                 my $uhom = $uhome;
                   1743:                 if ($uhom eq '') {
                   1744:                     $uhom=&homeserver($uname,$udom);
                   1745:                 }
                   1746:                 if ($uhom ne 'no_host') { 
                   1747:                     $byid{$uhom}{$id} .= $uname.',';
                   1748:                 }
                   1749:             }
1.1231    raeburn  1750:         }
1.1300    raeburn  1751:     }
                   1752:     if ($namespace eq 'clickers') {
                   1753:         foreach my $server (keys(%byid)) {
                   1754:             if (ref($byid{$server}) eq 'HASH') {
                   1755:                 foreach my $id (keys(%{$byid{$server}})) {
                   1756:                     $byid{$server}{$id} =~ s/,$//;
                   1757:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
                   1758:                 }
1.1231    raeburn  1759:             }
                   1760:         }
                   1761:     }
                   1762:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1763:         $servers{$server} =~ s/\&$//;
                   1764:         if ($namespace eq 'ids') {
                   1765:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1766:         } elsif ($namespace eq 'clickers') {
                   1767:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
                   1768:         }
1.1231    raeburn  1769:     }
                   1770:     return %result;
                   1771: }
                   1772: 
1.1300    raeburn  1773: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
                   1774: 
                   1775: sub updateclickers {
                   1776:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
                   1777:     my %clickers;
                   1778:     if (ref($idshashref) eq 'HASH') {
                   1779:         %clickers=%{$idshashref};
                   1780:     } else {
                   1781:         return;
                   1782:     }
                   1783:     my $items='';
                   1784:     foreach my $item (keys(%clickers)) {
                   1785:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
                   1786:     }
                   1787:     $items=~s/\&$//;
                   1788:     my $request = "updateclickers:$udom:$action:$items";
                   1789:     if ($critical) {
                   1790:         return &critical($request,$uhome);
                   1791:     } else {
                   1792:         return &reply($request,$uhome);
                   1793:     }
                   1794: }
                   1795: 
1.1023    raeburn  1796: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1797: sub dump_dom {
1.1165    droeschl 1798:     my ($namespace, $udom, $regexp) = @_;
                   1799: 
                   1800:     $udom ||= $env{'user.domain'};
                   1801: 
                   1802:     return () unless $udom;
                   1803: 
                   1804:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1805: }
                   1806: 
1.1023    raeburn  1807: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1808: 
                   1809: sub get_dom {
1.860     raeburn  1810:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267    raeburn  1811:     return if ($udom eq 'public');
1.806     raeburn  1812:     my $items='';
                   1813:     foreach my $item (@$storearr) {
                   1814:         $items.=&escape($item).'&';
                   1815:     }
                   1816:     $items=~s/\&$//;
1.860     raeburn  1817:     if (!$udom) {
                   1818:         $udom=$env{'user.domain'};
1.1267    raeburn  1819:         return if ($udom eq 'public');
1.860     raeburn  1820:         if (defined(&domain($udom,'primary'))) {
                   1821:             $uhome=&domain($udom,'primary');
                   1822:         } else {
1.874     albertel 1823:             undef($uhome);
1.860     raeburn  1824:         }
                   1825:     } else {
                   1826:         if (!$uhome) {
                   1827:             if (defined(&domain($udom,'primary'))) {
                   1828:                 $uhome=&domain($udom,'primary');
                   1829:             }
                   1830:         }
                   1831:     }
                   1832:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1833:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1834:         my %returnhash;
1.875     albertel 1835:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1836:             return %returnhash;
                   1837:         }
1.806     raeburn  1838:         my @pairs=split(/\&/,$rep);
                   1839:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1840:             return @pairs;
                   1841:         }
                   1842:         my $i=0;
                   1843:         foreach my $item (@$storearr) {
                   1844:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1845:             $i++;
                   1846:         }
                   1847:         return %returnhash;
                   1848:     } else {
1.880     banghart 1849:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1850:     }
                   1851: }
                   1852: 
                   1853: # -------------------------------------------- put items in domain db files 
                   1854: 
                   1855: sub put_dom {
1.860     raeburn  1856:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1857:     if (!$udom) {
                   1858:         $udom=$env{'user.domain'};
                   1859:         if (defined(&domain($udom,'primary'))) {
                   1860:             $uhome=&domain($udom,'primary');
                   1861:         } else {
1.874     albertel 1862:             undef($uhome);
1.860     raeburn  1863:         }
                   1864:     } else {
                   1865:         if (!$uhome) {
                   1866:             if (defined(&domain($udom,'primary'))) {
                   1867:                 $uhome=&domain($udom,'primary');
                   1868:             }
                   1869:         }
                   1870:     } 
                   1871:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1872:         my $items='';
                   1873:         foreach my $item (keys(%$storehash)) {
                   1874:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1875:         }
                   1876:         $items=~s/\&$//;
                   1877:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1878:     } else {
1.860     raeburn  1879:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1880:     }
                   1881: }
                   1882: 
1.1023    raeburn  1883: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1884: sub newput_dom {
1.1023    raeburn  1885:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1886:     my $result;
                   1887:     if (!$udom) {
                   1888:         $udom=$env{'user.domain'};
                   1889:     }
1.1023    raeburn  1890:     if ($udom) {
                   1891:         my $uname = &get_domainconfiguser($udom);
                   1892:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1893:     }
                   1894:     return $result;
                   1895: }
                   1896: 
1.1023    raeburn  1897: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1898: sub del_dom {
1.1023    raeburn  1899:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1900:     if (ref($storearr) eq 'ARRAY') {
                   1901:         if (!$udom) {
                   1902:             $udom=$env{'user.domain'};
                   1903:         }
1.1023    raeburn  1904:         if ($udom) {
                   1905:             my $uname = &get_domainconfiguser($udom); 
                   1906:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1907:         }
                   1908:     }
                   1909: }
                   1910: 
1.1023    raeburn  1911: # ----------------------------------construct domainconfig user for a domain 
                   1912: sub get_domainconfiguser {
                   1913:     my ($udom) = @_;
                   1914:     return $udom.'-domainconfig';
                   1915: }
                   1916: 
1.837     raeburn  1917: sub retrieve_inst_usertypes {
                   1918:     my ($udom) = @_;
                   1919:     my (%returnhash,@order);
1.989     raeburn  1920:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1921:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1922:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  1923:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1924:     } else {
                   1925:         if (defined(&domain($udom,'primary'))) {
                   1926:             my $uhome=&domain($udom,'primary');
                   1927:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1928:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  1929:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1930:                 return (\%returnhash,\@order);
                   1931:             }
                   1932:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1933:             my @pairs=split(/\&/,$hashitems);
                   1934:             foreach my $item (@pairs) {
                   1935:                 my ($key,$value)=split(/=/,$item,2);
                   1936:                 $key = &unescape($key);
                   1937:                 next if ($key =~ /^error: 2 /);
                   1938:                 $returnhash{$key}=&thaw_unescape($value);
                   1939:             }
                   1940:             my @esc_order = split(/\&/,$orderitems);
                   1941:             foreach my $item (@esc_order) {
                   1942:                 push(@order,&unescape($item));
                   1943:             }
                   1944:         } else {
1.1256    raeburn  1945:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1946:         }
1.1256    raeburn  1947:         return (\%returnhash,\@order);
1.837     raeburn  1948:     }
                   1949: }
                   1950: 
1.868     raeburn  1951: sub is_domainimage {
                   1952:     my ($url) = @_;
1.1306    raeburn  1953:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  1954:         if (&domain($1) ne '') {
                   1955:             return '1';
                   1956:         }
                   1957:     }
                   1958:     return;
                   1959: }
                   1960: 
1.899     raeburn  1961: sub inst_directory_query {
                   1962:     my ($srch) = @_;
                   1963:     my $udom = $srch->{'srchdomain'};
                   1964:     my %results;
                   1965:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1966:     my $outcome;
1.899     raeburn  1967:     if ($homeserver ne '') {
1.904     albertel 1968: 	my $queryid=&reply("querysend:instdirsearch:".
                   1969: 			   &escape($srch->{'srchby'}).':'.
                   1970: 			   &escape($srch->{'srchterm'}).':'.
                   1971: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1972: 	my $host=&hostname($homeserver);
                   1973: 	if ($queryid !~/^\Q$host\E\_/) {
                   1974: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1975: 	    return;
                   1976: 	}
                   1977: 	my $response = &get_query_reply($queryid);
                   1978: 	my $maxtries = 5;
                   1979: 	my $tries = 1;
                   1980: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1981: 	    $response = &get_query_reply($queryid);
                   1982: 	    $tries ++;
                   1983: 	}
                   1984: 
                   1985:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1986:             if ($response eq 'unavailable') {
                   1987:                 $outcome = $response;
                   1988:             } else {
                   1989:                 $outcome = 'ok';
                   1990:                 my @matches = split(/\n/,$response);
                   1991:                 foreach my $match (@matches) {
                   1992:                     my ($key,$value) = split(/=/,$match);
                   1993:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1994:                 }
1.899     raeburn  1995:             }
                   1996:         }
                   1997:     }
1.909     raeburn  1998:     return ($outcome,%results);
1.899     raeburn  1999: }
                   2000: 
                   2001: sub usersearch {
                   2002:     my ($srch) = @_;
                   2003:     my $dom = $srch->{'srchdomain'};
                   2004:     my %results;
                   2005:     my %libserv = &all_library();
                   2006:     my $query = 'usersearch';
                   2007:     foreach my $tryserver (keys(%libserv)) {
                   2008:         if (&host_domain($tryserver) eq $dom) {
                   2009:             my $host=&hostname($tryserver);
                   2010:             my $queryid=
1.911     raeburn  2011:                 &reply("querysend:".&escape($query).':'.
                   2012:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2013:                        &escape($srch->{'srchtype'}).':'.
                   2014:                        &escape($srch->{'srchterm'}),$tryserver);
                   2015:             if ($queryid !~/^\Q$host\E\_/) {
                   2016:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2017:                 next;
1.899     raeburn  2018:             }
                   2019:             my $reply = &get_query_reply($queryid);
                   2020:             my $maxtries = 1;
                   2021:             my $tries = 1;
                   2022:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2023:                 $reply = &get_query_reply($queryid);
                   2024:                 $tries ++;
                   2025:             }
                   2026:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2027:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2028:             } else {
1.911     raeburn  2029:                 my @matches;
                   2030:                 if ($reply =~ /\n/) {
                   2031:                     @matches = split(/\n/,$reply);
                   2032:                 } else {
                   2033:                     @matches = split(/\&/,$reply);
                   2034:                 }
1.899     raeburn  2035:                 foreach my $match (@matches) {
                   2036:                     my ($uname,$udom,%userhash);
1.911     raeburn  2037:                     foreach my $entry (split(/:/,$match)) {
                   2038:                         my ($key,$value) =
                   2039:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2040:                         $userhash{$key} = $value;
                   2041:                         if ($key eq 'username') {
                   2042:                             $uname = $value;
                   2043:                         } elsif ($key eq 'domain') {
                   2044:                             $udom = $value;
1.911     raeburn  2045:                         }
1.899     raeburn  2046:                     }
                   2047:                     $results{$uname.':'.$udom} = \%userhash;
                   2048:                 }
                   2049:             }
                   2050:         }
                   2051:     }
                   2052:     return %results;
                   2053: }
                   2054: 
1.912     raeburn  2055: sub get_instuser {
                   2056:     my ($udom,$uname,$id) = @_;
                   2057:     my $homeserver = &domain($udom,'primary');
                   2058:     my ($outcome,%results);
                   2059:     if ($homeserver ne '') {
                   2060:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2061:                            &escape($id).':'.&escape($udom),$homeserver);
                   2062:         my $host=&hostname($homeserver);
                   2063:         if ($queryid !~/^\Q$host\E\_/) {
                   2064:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2065:             return;
                   2066:         }
                   2067:         my $response = &get_query_reply($queryid);
                   2068:         my $maxtries = 5;
                   2069:         my $tries = 1;
                   2070:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2071:             $response = &get_query_reply($queryid);
                   2072:             $tries ++;
                   2073:         }
                   2074:         if (!&error($response) && $response ne 'refused') {
                   2075:             if ($response eq 'unavailable') {
                   2076:                 $outcome = $response;
                   2077:             } else {
                   2078:                 $outcome = 'ok';
                   2079:                 my @matches = split(/\n/,$response);
                   2080:                 foreach my $match (@matches) {
                   2081:                     my ($key,$value) = split(/=/,$match);
                   2082:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2083:                 }
                   2084:             }
                   2085:         }
                   2086:     }
                   2087:     my %userinfo;
                   2088:     if (ref($results{$uname}) eq 'HASH') {
                   2089:         %userinfo = %{$results{$uname}};
                   2090:     } 
                   2091:     return ($outcome,%userinfo);
                   2092: }
                   2093: 
1.1290    raeburn  2094: sub get_multiple_instusers {
                   2095:     my ($udom,$users,$caller) = @_;
                   2096:     my ($outcome,$results);
                   2097:     if (ref($users) eq 'HASH') {
                   2098:         my $count = keys(%{$users}); 
                   2099:         my $requested = &freeze_escape($users);
                   2100:         my $homeserver = &domain($udom,'primary');
                   2101:         if ($homeserver ne '') {
                   2102:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2103:             my $host=&hostname($homeserver);
                   2104:             if ($queryid !~/^\Q$host\E\_/) {
                   2105:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2106:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2107:                 return ($outcome,$results);
                   2108:             }
                   2109:             my $response = &get_query_reply($queryid);
                   2110:             my $maxtries = 5;
                   2111:             if ($count > 100) {
                   2112:                 $maxtries = 1+int($count/20);
                   2113:             }
                   2114:             my $tries = 1;
                   2115:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2116:                 $response = &get_query_reply($queryid);
                   2117:                 $tries ++;
                   2118:             }
                   2119:             if ($response eq '') {
                   2120:                 $results = {};
                   2121:                 foreach my $key (keys(%{$users})) {
                   2122:                     my ($uname,$id);
                   2123:                     if ($caller eq 'id') {
                   2124:                         $id = $key;
                   2125:                     } else {
                   2126:                         $uname = $key;
                   2127:                     }
                   2128:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291    raeburn  2129:                     $outcome = $resp;
1.1290    raeburn  2130:                     if ($resp eq 'ok') {
                   2131:                         %{$results} = (%{$results}, %info);
                   2132:                     } else {
                   2133:                         last;
                   2134:                     }
                   2135:                 }
                   2136:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2137:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2138:                     $outcome = $response;
                   2139:                 } else {
1.1291    raeburn  2140:                     ($outcome,my $userdata) = split(/=/,$response,2);
1.1290    raeburn  2141:                     if ($outcome eq 'ok') {
                   2142:                         $results = &thaw_unescape($userdata); 
                   2143:                     }
                   2144:                 }
                   2145:             }
                   2146:         }
                   2147:     }
                   2148:     return ($outcome,$results);
                   2149: }
                   2150: 
1.912     raeburn  2151: sub inst_rulecheck {
1.923     raeburn  2152:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2153:     my %returnhash;
                   2154:     if ($udom ne '') {
                   2155:         if (ref($rules) eq 'ARRAY') {
                   2156:             @{$rules} = map {&escape($_);} (@{$rules});
                   2157:             my $rulestr = join(':',@{$rules});
                   2158:             my $homeserver=&domain($udom,'primary');
                   2159:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2160:                 my $response;
                   2161:                 if ($item eq 'username') {                
                   2162:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2163:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2164:                                               $homeserver));
1.923     raeburn  2165:                 } elsif ($item eq 'id') {
                   2166:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2167:                                               ':'.&escape($id).':'.$rulestr,
                   2168:                                               $homeserver));
1.945     raeburn  2169:                 } elsif ($item eq 'selfcreate') {
                   2170:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2171:                                                &escape($udom).':'.&escape($uname).
                   2172:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2173:                 }
1.912     raeburn  2174:                 if ($response ne 'refused') {
                   2175:                     my @pairs=split(/\&/,$response);
                   2176:                     foreach my $item (@pairs) {
                   2177:                         my ($key,$value)=split(/=/,$item,2);
                   2178:                         $key = &unescape($key);
                   2179:                         next if ($key =~ /^error: 2 /);
                   2180:                         $returnhash{$key}=&thaw_unescape($value);
                   2181:                     }
                   2182:                 }
                   2183:             }
                   2184:         }
                   2185:     }
                   2186:     return %returnhash;
                   2187: }
                   2188: 
                   2189: sub inst_userrules {
1.923     raeburn  2190:     my ($udom,$check) = @_;
1.912     raeburn  2191:     my (%ruleshash,@ruleorder);
                   2192:     if ($udom ne '') {
                   2193:         my $homeserver=&domain($udom,'primary');
                   2194:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2195:             my $response;
                   2196:             if ($check eq 'id') {
                   2197:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2198:                                  $homeserver);
1.943     raeburn  2199:             } elsif ($check eq 'email') {
                   2200:                 $response=&reply('instemailrules:'.&escape($udom),
                   2201:                                  $homeserver);
1.923     raeburn  2202:             } else {
                   2203:                 $response=&reply('instuserrules:'.&escape($udom),
                   2204:                                  $homeserver);
                   2205:             }
1.912     raeburn  2206:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2207:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2208:                 ($response ne 'no_such_host')) {
                   2209:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2210:                 my @pairs=split(/\&/,$hashitems);
                   2211:                 foreach my $item (@pairs) {
                   2212:                     my ($key,$value)=split(/=/,$item,2);
                   2213:                     $key = &unescape($key);
                   2214:                     next if ($key =~ /^error: 2 /);
                   2215:                     $ruleshash{$key}=&thaw_unescape($value);
                   2216:                 }
                   2217:                 my @esc_order = split(/\&/,$orderitems);
                   2218:                 foreach my $item (@esc_order) {
                   2219:                     push(@ruleorder,&unescape($item));
                   2220:                 }
                   2221:             }
                   2222:         }
                   2223:     }
                   2224:     return (\%ruleshash,\@ruleorder);
                   2225: }
                   2226: 
1.976     raeburn  2227: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2228: 
                   2229: sub get_domain_defaults {
1.1240    raeburn  2230:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2231:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2232:     my $cachetime = 60*60*24;
1.1240    raeburn  2233:     unless ($ignore_cache) {
                   2234:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2235:         if (defined($cached)) {
                   2236:             if (ref($result) eq 'HASH') {
                   2237:                 return %{$result};
                   2238:             }
1.943     raeburn  2239:         }
                   2240:     }
                   2241:     my %domdefaults;
                   2242:     my %domconfig =
1.989     raeburn  2243:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2244:                                   'requestcourses','inststatus',
1.1183    raeburn  2245:                                   'coursedefaults','usersessions',
1.1258    raeburn  2246:                                   'requestauthor','selfenrollment',
1.1320    raeburn  2247:                                   'coursecategories','ssl','autoenroll',
                   2248:                                   'trust'],$domain);
1.1305    raeburn  2249:     my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943     raeburn  2250:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2251:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2252:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2253:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2254:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2255:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2256:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  2257:     } else {
                   2258:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2259:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2260:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2261:     }
1.976     raeburn  2262:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2263:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2264:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2265:         } else {
                   2266:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2267:         }
1.1177    raeburn  2268:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2269:         foreach my $item (@usertools) {
                   2270:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2271:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2272:             }
                   2273:         }
1.1229    raeburn  2274:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2275:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2276:         }
1.976     raeburn  2277:     }
1.985     raeburn  2278:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305    raeburn  2279:         foreach my $item ('official','unofficial','community','textbook','placement') {
1.985     raeburn  2280:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2281:         }
                   2282:     }
1.1183    raeburn  2283:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2284:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2285:     }
1.989     raeburn  2286:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2287:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2288:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2289:         }
                   2290:     }
1.1047    raeburn  2291:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2292:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2293:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2294:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2295:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2296:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2297:         }
1.1254    raeburn  2298:         foreach my $type (@coursetypes) {
                   2299:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2300:                 unless ($type eq 'community') {
                   2301:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2302:                 }
                   2303:             }
                   2304:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2305:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2306:             }
1.1277    raeburn  2307:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2308:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2309:                     $domdefaults{$type.'postsubtimeout'} = 
                   2310:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2311:                 }
                   2312:             }
1.1230    raeburn  2313:         }
1.1286    raeburn  2314:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2315:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2316:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2317:                 if (@clonecodes) {
                   2318:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2319:                 }
                   2320:             }
                   2321:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2322:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2323:         }
1.1047    raeburn  2324:     }
1.1073    raeburn  2325:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2326:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2327:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2328:         }
                   2329:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2330:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2331:         }
1.1279    raeburn  2332:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2333:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2334:         }
1.1073    raeburn  2335:     }
1.1254    raeburn  2336:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2337:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2338:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2339:                             'approval','limit');
                   2340:             foreach my $type (@coursetypes) {
                   2341:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2342:                     my @mgrdc = ();
                   2343:                     foreach my $item (@settings) {
                   2344:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2345:                             push(@mgrdc,$item);
                   2346:                         }
                   2347:                     }
                   2348:                     if (@mgrdc) {
                   2349:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2350:                     }
                   2351:                 }
                   2352:             }
                   2353:         }
                   2354:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2355:             foreach my $type (@coursetypes) {
                   2356:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2357:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2358:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2359:                     }
                   2360:                 }
                   2361:             }
                   2362:         }
                   2363:     }
1.1258    raeburn  2364:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2365:         $domdefaults{'catauth'} = 'std';
                   2366:         $domdefaults{'catunauth'} = 'std';
                   2367:         if ($domconfig{'coursecategories'}{'auth'}) { 
                   2368:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2369:         }
                   2370:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2371:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2372:         }
                   2373:     }
1.1315    raeburn  2374:     if (ref($domconfig{'ssl'}) eq 'HASH') {
                   2375:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
                   2376:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
                   2377:         }
                   2378:         if (ref($domconfig{'ssl'}{'connect'}) eq 'HASH') {
                   2379:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connect'};
                   2380:         }
                   2381:     }
1.1320    raeburn  2382:     if (ref($domconfig{'trust'}) eq 'HASH') {
                   2383:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
                   2384:         foreach my $prefix (@prefixes) {
                   2385:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
                   2386:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
                   2387:             }
                   2388:         }
                   2389:     }
1.1314    raeburn  2390:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2391:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2392:     }
1.1219    raeburn  2393:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2394:     return %domdefaults;
                   2395: }
                   2396: 
1.1311    raeburn  2397: sub course_portal_url {
                   2398:     my ($cnum,$cdom) = @_;
                   2399:     my $chome = &homeserver($cnum,$cdom);
                   2400:     my $hostname = &hostname($chome);
                   2401:     my $protocol = $protocol{$chome};
                   2402:     $protocol = 'http' if ($protocol ne 'https');
                   2403:     my %domdefaults = &get_domain_defaults($cdom);
                   2404:     my $firsturl;
                   2405:     if ($domdefaults{'portal_def'}) {
                   2406:         $firsturl = $domdefaults{'portal_def'};
                   2407:     } else {
                   2408:         $firsturl = $protocol.'://'.$hostname;
                   2409:     }
                   2410:     return $firsturl;
                   2411: }
                   2412: 
1.344     www      2413: # --------------------------------------------------- Assign a key to a student
                   2414: 
                   2415: sub assign_access_key {
1.364     www      2416: #
                   2417: # a valid key looks like uname:udom#comments
                   2418: # comments are being appended
                   2419: #
1.498     www      2420:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2421:     $kdom=
1.620     albertel 2422:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2423:     $knum=
1.620     albertel 2424:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2425:     $cdom=
1.620     albertel 2426:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2427:     $cnum=
1.620     albertel 2428:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2429:     $udom=$env{'user.name'} unless (defined($udom));
                   2430:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2431:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2432:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2433:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2434:                                                   # assigned to this person
                   2435:                                                   # - this should not happen,
1.345     www      2436:                                                   # unless something went wrong
                   2437:                                                   # the first time around
                   2438: # ready to assign
1.364     www      2439:         $logentry=$1.'; '.$logentry;
1.496     www      2440:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2441:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2442: # key now belongs to user
1.346     www      2443: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2444:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2445:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2446:                 return 'ok';
                   2447:             } else {
                   2448:                 return 
                   2449:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2450: 	    }
                   2451:         } else {
                   2452:             return 'error: Could not assign key, try again later.';
                   2453:         }
1.364     www      2454:     } elsif (!$existing{$ckey}) {
1.345     www      2455: # the key does not exist
                   2456: 	return 'error: The key does not exist';
                   2457:     } else {
                   2458: # the key is somebody else's
                   2459: 	return 'error: The key is already in use';
                   2460:     }
1.344     www      2461: }
                   2462: 
1.364     www      2463: # ------------------------------------------ put an additional comment on a key
                   2464: 
                   2465: sub comment_access_key {
                   2466: #
                   2467: # a valid key looks like uname:udom#comments
                   2468: # comments are being appended
                   2469: #
                   2470:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2471:     $cdom=
1.620     albertel 2472:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2473:     $cnum=
1.620     albertel 2474:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2475:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2476:     if ($existing{$ckey}) {
                   2477:         $existing{$ckey}.='; '.$logentry;
                   2478: # ready to assign
1.367     www      2479:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2480:                                                  $cdom,$cnum) eq 'ok') {
                   2481: 	    return 'ok';
                   2482:         } else {
                   2483: 	    return 'error: Count not store comment.';
                   2484:         }
                   2485:     } else {
                   2486: # the key does not exist
                   2487: 	return 'error: The key does not exist';
                   2488:     }
                   2489: }
                   2490: 
1.344     www      2491: # ------------------------------------------------------ Generate a set of keys
                   2492: 
                   2493: sub generate_access_keys {
1.364     www      2494:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2495:     $cdom=
1.620     albertel 2496:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2497:     $cnum=
1.620     albertel 2498:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2499:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2500:     unless (($cdom) && ($cnum)) { return 0; }
                   2501:     if ($number>10000) { return 0; }
                   2502:     sleep(2); # make sure don't get same seed twice
                   2503:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2504:     my $total=0;
                   2505:     for (my $i=1;$i<=$number;$i++) {
                   2506:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2507:                   sprintf("%lx",int(100000*rand)).'-'.
                   2508:                   sprintf("%lx",int(100000*rand));
                   2509:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2510:        $newkey=~s/0/h/g; # and also 0 and O
                   2511:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2512:        if ($existing{$newkey}) {
                   2513:            $i--;
                   2514:        } else {
1.364     www      2515: 	  if (&put('accesskeys',
                   2516:               { $newkey => '# generated '.localtime().
1.620     albertel 2517:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2518:                            '; '.$logentry },
                   2519: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2520:               $total++;
                   2521: 	  }
                   2522:        }
                   2523:     }
1.620     albertel 2524:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2525:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2526:     return $total;
                   2527: }
                   2528: 
                   2529: # ------------------------------------------------------- Validate an accesskey
                   2530: 
                   2531: sub validate_access_key {
                   2532:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2533:     $cdom=
1.620     albertel 2534:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2535:     $cnum=
1.620     albertel 2536:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2537:     $udom=$env{'user.domain'} unless (defined($udom));
                   2538:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2539:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2540:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2541: }
                   2542: 
                   2543: # ------------------------------------- Find the section of student in a course
1.652     albertel 2544: sub devalidate_getsection_cache {
                   2545:     my ($udom,$unam,$courseid)=@_;
                   2546:     my $hashid="$udom:$unam:$courseid";
                   2547:     &devalidate_cache_new('getsection',$hashid);
                   2548: }
1.298     matthew  2549: 
1.815     albertel 2550: sub courseid_to_courseurl {
                   2551:     my ($courseid) = @_;
                   2552:     #already url style courseid
                   2553:     return $courseid if ($courseid =~ m{^/});
                   2554: 
                   2555:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2556: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2557: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2558: 	return "/$cdom/$cnum";
                   2559:     }
                   2560: 
                   2561:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2562:     if (exists($courseinfo{'num'})) {
                   2563: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2564:     }
                   2565: 
                   2566:     return undef;
                   2567: }
                   2568: 
1.298     matthew  2569: sub getsection {
                   2570:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2571:     my $cachetime=1800;
1.551     albertel 2572: 
                   2573:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2574:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2575:     if (defined($cached)) { return $result; }
                   2576: 
1.298     matthew  2577:     my %Pending; 
                   2578:     my %Expired;
                   2579:     #
                   2580:     # Each role can either have not started yet (pending), be active, 
                   2581:     #    or have expired.
                   2582:     #
                   2583:     # If there is an active role, we are done.
                   2584:     #
                   2585:     # If there is more than one role which has not started yet, 
                   2586:     #     choose the one which will start sooner
                   2587:     # If there is one role which has not started yet, return it.
                   2588:     #
                   2589:     # If there is more than one expired role, choose the one which ended last.
                   2590:     # If there is a role which has expired, return it.
                   2591:     #
1.815     albertel 2592:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2593:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2594:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2595:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2596:         my $section=$1;
                   2597:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2598:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2599:         my $now=time;
1.548     albertel 2600:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2601:             $Expired{$end}=$section;
                   2602:             next;
                   2603:         }
1.548     albertel 2604:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2605:             $Pending{$start}=$section;
                   2606:             next;
                   2607:         }
1.599     albertel 2608:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2609:     }
                   2610:     #
                   2611:     # Presumedly there will be few matching roles from the above
                   2612:     # loop and the sorting time will be negligible.
                   2613:     if (scalar(keys(%Pending))) {
                   2614:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2615:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2616:     } 
                   2617:     if (scalar(keys(%Expired))) {
                   2618:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2619:         my $time = pop(@sorted);
1.599     albertel 2620:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2621:     }
1.599     albertel 2622:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2623: }
1.70      www      2624: 
1.599     albertel 2625: sub save_cache {
                   2626:     &purge_remembered();
1.722     albertel 2627:     #&Apache::loncommon::validate_page();
1.620     albertel 2628:     undef(%env);
1.780     albertel 2629:     undef($env_loaded);
1.599     albertel 2630: }
1.452     albertel 2631: 
1.599     albertel 2632: my $to_remember=-1;
                   2633: my %remembered;
                   2634: my %accessed;
                   2635: my $kicks=0;
                   2636: my $hits=0;
1.849     albertel 2637: sub make_key {
                   2638:     my ($name,$id) = @_;
1.872     albertel 2639:     if (length($id) > 65 
                   2640: 	&& length(&escape($id)) > 200) {
                   2641: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2642:     }
1.849     albertel 2643:     return &escape($name.':'.$id);
                   2644: }
                   2645: 
1.599     albertel 2646: sub devalidate_cache_new {
                   2647:     my ($name,$id,$debug) = @_;
                   2648:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319    damieng  2649:     my $remembered_id=$name.':'.$id;
1.849     albertel 2650:     $id=&make_key($name,$id);
1.599     albertel 2651:     $memcache->delete($id);
1.1319    damieng  2652:     delete($remembered{$remembered_id});
                   2653:     delete($accessed{$remembered_id});
1.599     albertel 2654: }
                   2655: 
                   2656: sub is_cached_new {
                   2657:     my ($name,$id,$debug) = @_;
1.1319    damieng  2658:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
                   2659:     if (exists($remembered{$remembered_id})) {
                   2660: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2661: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2662: 	$hits++;
1.1319    damieng  2663: 	return ($remembered{$remembered_id},1);
1.599     albertel 2664:     }
1.1319    damieng  2665:     $id=&make_key($name,$id);
1.599     albertel 2666:     my $value = $memcache->get($id);
                   2667:     if (!(defined($value))) {
                   2668: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2669: 	return (undef,undef);
1.416     albertel 2670:     }
1.599     albertel 2671:     if ($value eq '__undef__') {
                   2672: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2673: 	$value=undef;
                   2674:     }
1.1319    damieng  2675:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2676:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2677:     return ($value,1);
                   2678: }
                   2679: 
                   2680: sub do_cache_new {
                   2681:     my ($name,$id,$value,$time,$debug) = @_;
1.1319    damieng  2682:     my $remembered_id=$name.':'.$id;
1.849     albertel 2683:     $id=&make_key($name,$id);
1.599     albertel 2684:     my $setvalue=$value;
                   2685:     if (!defined($setvalue)) {
                   2686: 	$setvalue='__undef__';
                   2687:     }
1.623     albertel 2688:     if (!defined($time) ) {
                   2689: 	$time=600;
                   2690:     }
1.599     albertel 2691:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2692:     my $result = $memcache->set($id,$setvalue,$time);
                   2693:     if (! $result) {
1.872     albertel 2694: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2695: 	$memcache->disconnect_all();
1.872     albertel 2696:     }
1.600     albertel 2697:     # need to make a copy of $value
1.1319    damieng  2698:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2699:     return $value;
                   2700: }
                   2701: 
                   2702: sub make_room {
1.1319    damieng  2703:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2704: 
1.1319    damieng  2705:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2706:                                     : $value;
1.599     albertel 2707:     if ($to_remember<0) { return; }
1.1319    damieng  2708:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2709:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2710:     my $to_kick;
                   2711:     my $max_time=0;
                   2712:     foreach my $other (keys(%accessed)) {
                   2713: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2714: 	    $to_kick=$other;
                   2715: 	    $max_time=&tv_interval($accessed{$other});
                   2716: 	}
                   2717:     }
                   2718:     delete($remembered{$to_kick});
                   2719:     delete($accessed{$to_kick});
                   2720:     $kicks++;
                   2721:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2722:     return;
                   2723: }
                   2724: 
1.599     albertel 2725: sub purge_remembered {
1.604     albertel 2726:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2727:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2728:     undef(%remembered);
                   2729:     undef(%accessed);
1.428     albertel 2730: }
1.70      www      2731: # ------------------------------------- Read an entry from a user's environment
                   2732: 
                   2733: sub userenvironment {
                   2734:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2735:     my $items;
                   2736:     foreach my $item (@what) {
                   2737:         $items.=&escape($item).'&';
                   2738:     }
                   2739:     $items=~s/\&$//;
1.70      www      2740:     my %returnhash=();
1.1009    raeburn  2741:     my $uhome = &homeserver($unam,$udom);
                   2742:     unless ($uhome eq 'no_host') {
                   2743:         my @answer=split(/\&/, 
                   2744:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2745:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2746:             return %returnhash;
                   2747:         }
1.1009    raeburn  2748:         my $i;
                   2749:         for ($i=0;$i<=$#what;$i++) {
                   2750: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2751:         }
1.70      www      2752:     }
                   2753:     return %returnhash;
1.1       albertel 2754: }
                   2755: 
1.617     albertel 2756: # ---------------------------------------------------------- Get a studentphoto
                   2757: sub studentphoto {
                   2758:     my ($udom,$unam,$ext) = @_;
                   2759:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2760:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2761:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2762:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2763:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2764:             } else {
                   2765:                 my ($result,$perm_reqd)=
1.707     albertel 2766: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2767:                 if ($result eq 'ok') {
                   2768:                     if (!($perm_reqd eq 'yes')) {
                   2769:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2770:                     }
                   2771:                 }
                   2772:             }
                   2773:         }
                   2774:     } else {
                   2775:         my ($result,$perm_reqd) = 
1.707     albertel 2776: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2777:         if ($result eq 'ok') {
                   2778:             if (!($perm_reqd eq 'yes')) {
                   2779:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2780:             }
                   2781:         }
                   2782:     }
                   2783:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2784: }
                   2785: 
                   2786: sub retrievestudentphoto {
                   2787:     my ($udom,$unam,$ext,$type) = @_;
                   2788:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2789:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2790:     if ($ret eq 'ok') {
                   2791:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2792:         if ($type eq 'thumbnail') {
                   2793:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2794:         }
                   2795:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2796:         return $tokenurl;
                   2797:     } else {
                   2798:         if ($type eq 'thumbnail') {
                   2799:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2800:         } else { 
                   2801:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2802:         }
1.617     albertel 2803:     }
                   2804: }
                   2805: 
1.263     www      2806: # -------------------------------------------------------------------- New chat
                   2807: 
                   2808: sub chatsend {
1.724     raeburn  2809:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2810:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2811:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2812:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2813:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2814: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2815: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2816: }
                   2817: 
                   2818: # ------------------------------------------ Find current version of a resource
                   2819: 
                   2820: sub getversion {
                   2821:     my $fname=&clutter(shift);
1.1189    raeburn  2822:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2823:     return &currentversion(&filelocation('',$fname));
                   2824: }
                   2825: 
                   2826: sub currentversion {
                   2827:     my $fname=shift;
                   2828:     my $author=$fname;
                   2829:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2830:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2831:     my $home=&homeserver($uname,$udom);
1.292     www      2832:     if ($home eq 'no_host') { 
                   2833:         return -1; 
                   2834:     }
1.1112    www      2835:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2836:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2837: 	return -1;
                   2838:     }
1.1112    www      2839:     return $answer;
1.263     www      2840: }
                   2841: 
1.1111    www      2842: #
                   2843: # Return special version number of resource if set by override, empty otherwise
                   2844: #
                   2845: sub usedversion {
                   2846:     my $fname=shift;
                   2847:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2848:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2849:     if ($urlversion) { return $urlversion; }
                   2850:     return '';
                   2851: }
                   2852: 
1.1       albertel 2853: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2854: 
1.1       albertel 2855: sub subscribe {
                   2856:     my $fname=shift;
1.761     raeburn  2857:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2858:     $fname=~s/[\n\r]//g;
1.1       albertel 2859:     my $author=$fname;
                   2860:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2861:     my ($udom,$uname)=split(/\//,$author);
                   2862:     my $home=homeserver($uname,$udom);
1.335     albertel 2863:     if ($home eq 'no_host') {
                   2864:         return 'not_found';
1.1       albertel 2865:     }
                   2866:     my $answer=reply("sub:$fname",$home);
1.64      www      2867:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2868: 	$answer.=' by '.$home;
                   2869:     }
1.1       albertel 2870:     return $answer;
                   2871: }
                   2872:     
1.8       www      2873: # -------------------------------------------------------------- Replicate file
                   2874: 
                   2875: sub repcopy {
                   2876:     my $filename=shift;
1.23      www      2877:     $filename=~s/\/+/\//g;
1.1142    raeburn  2878:     my $londocroot = $perlvar{'lonDocRoot'};
                   2879:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2880:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2881:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2882: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2883: 	return &repcopy_userfile($filename);
                   2884:     }
1.532     albertel 2885:     $filename=~s/[\n\r]//g;
1.8       www      2886:     my $transname="$filename.in.transfer";
1.828     www      2887: # FIXME: this should flock
1.607     raeburn  2888:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2889:     my $remoteurl=subscribe($filename);
1.64      www      2890:     if ($remoteurl =~ /^con_lost by/) {
                   2891: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2892:            return 'unavailable';
1.8       www      2893:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2894: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2895: 	   return 'not_found';
1.64      www      2896:     } elsif ($remoteurl =~ /^rejected by/) {
                   2897: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2898:            return 'forbidden';
1.20      www      2899:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2900:            return 'ok';
1.8       www      2901:     } else {
1.290     www      2902:         my $author=$filename;
                   2903:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2904:         my ($udom,$uname)=split(/\//,$author);
                   2905:         my $home=homeserver($uname,$udom);
                   2906:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2907:            my @parts=split(/\//,$filename);
                   2908:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2909:            if ($path ne "$londocroot/res") {
1.8       www      2910:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2911: 	       return 'bad_request';
1.8       www      2912:            }
                   2913:            my $count;
                   2914:            for ($count=5;$count<$#parts;$count++) {
                   2915:                $path.="/$parts[$count]";
                   2916:                if ((-e $path)!=1) {
                   2917: 		   mkdir($path,0777);
                   2918:                }
                   2919:            }
                   2920:            my $ua=new LWP::UserAgent;
                   2921:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2922:            my $response=$ua->request($request,$transname);
                   2923:            if ($response->is_error()) {
                   2924: 	       unlink($transname);
                   2925:                my $message=$response->status_line;
1.672     albertel 2926:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2927:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2928:                return 'unavailable';
1.8       www      2929:            } else {
1.16      www      2930: 	       if ($remoteurl!~/\.meta$/) {
                   2931:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2932:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2933:                   if ($mresponse->is_error()) {
                   2934: 		      unlink($filename.'.meta');
                   2935:                       &logthis(
1.672     albertel 2936:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2937:                   }
                   2938: 	       }
1.8       www      2939:                rename($transname,$filename);
1.607     raeburn  2940:                return 'ok';
1.8       www      2941:            }
1.290     www      2942:        }
1.8       www      2943:     }
1.330     www      2944: }
                   2945: 
                   2946: # ------------------------------------------------ Get server side include body
                   2947: sub ssi_body {
1.381     albertel 2948:     my ($filelink,%form)=@_;
1.606     matthew  2949:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2950:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2951:     }
1.953     www      2952:     my $output='';
                   2953:     my $response;
1.980     raeburn  2954:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2955:        ($output,$response)=&externalssi($filelink);
1.953     www      2956:     } else {
1.1004    droeschl 2957:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2958:        $filelink .= 'inhibitmenu=yes';
1.953     www      2959:        ($output,$response)=&ssi($filelink,%form);
                   2960:     }
1.778     albertel 2961:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2962:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2963:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2964:     if (wantarray) {
                   2965:         return ($output, $response);
                   2966:     } else {
                   2967:         return $output;
                   2968:     }
1.8       www      2969: }
                   2970: 
1.15      www      2971: # --------------------------------------------------------- Server Side Include
                   2972: 
1.782     albertel 2973: sub absolute_url {
                   2974:     my ($host_name) = @_;
                   2975:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2976:     if ($host_name eq '') {
                   2977: 	$host_name = $ENV{'SERVER_NAME'};
                   2978:     }
                   2979:     return $protocol.$host_name;
                   2980: }
                   2981: 
1.942     foxr     2982: #
                   2983: #   Server side include.
                   2984: # Parameters:
                   2985: #  fn     Possibly encrypted resource name/id.
                   2986: #  form   Hash that describes how the rendering should be done
                   2987: #         and other things.
1.944     foxr     2988: # Returns:
1.950     raeburn  2989: #   Scalar context: The content of the response.
                   2990: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2991: #     
1.15      www      2992: sub ssi {
                   2993: 
1.944     foxr     2994:     my ($fn,%form)=@_;
1.15      www      2995:     my $ua=new LWP::UserAgent;
1.23      www      2996:     my $request;
1.711     albertel 2997: 
                   2998:     $form{'no_update_last_known'}=1;
1.895     albertel 2999:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3000:     if (%form) {
1.782     albertel 3001:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272    droeschl 3002:       $request->content(join('&',map { 
                   3003:             my $name = escape($_);
                   3004:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   3005:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   3006:             : &escape($form{$_}) );    
                   3007:         } keys(%form)));
1.23      www      3008:     } else {
1.782     albertel 3009:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3010:     }
                   3011: 
1.15      www      3012:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173    foxr     3013:     my $response= $ua->request($request);
1.1182    foxr     3014:     my $content = $response->content;
                   3015: 
                   3016: 
1.944     foxr     3017:     if (wantarray) {
1.1173    foxr     3018: 	return ($content, $response);
1.944     foxr     3019:     } else {
1.1173    foxr     3020: 	return $content;
1.942     foxr     3021:     }
1.324     www      3022: }
                   3023: 
                   3024: sub externalssi {
                   3025:     my ($url)=@_;
                   3026:     my $ua=new LWP::UserAgent;
                   3027:     my $request=new HTTP::Request('GET',$url);
                   3028:     my $response=$ua->request($request);
1.954     raeburn  3029:     if (wantarray) {
                   3030:         return ($response->content, $response);
                   3031:     } else {
                   3032:         return $response->content;
                   3033:     }
1.15      www      3034: }
1.254     www      3035: 
1.492     albertel 3036: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3037: 
                   3038: sub allowuploaded {
                   3039:     my ($srcurl,$url)=@_;
                   3040:     $url=&clutter(&declutter($url));
                   3041:     my $dir=$url;
                   3042:     $dir=~s/\/[^\/]+$//;
                   3043:     my %httpref=();
                   3044:     my $httpurl=&hreflocation('',$url);
                   3045:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3046:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3047: }
1.477     raeburn  3048: 
1.1193    raeburn  3049: #
                   3050: # Determine if the current user should be able to edit a particular resource,
                   3051: # when viewing in course context.
                   3052: # (a) When viewing resource used to determine if "Edit" item is included in 
                   3053: #     Functions.
                   3054: # (b) When displaying folder contents in course editor, used to determine if
                   3055: #     "Edit" link will be displayed alongside resource.
                   3056: #
1.1196    raeburn  3057: #  input: six args -- filename (decluttered), course number, course domain,
                   3058: #                   url, symb (if registered) and group (if this is a group
                   3059: #                   item -- e.g., bulletin board, group page etc.).
                   3060: #  output: array of five scalars -- 
1.1193    raeburn  3061: #          $cfile -- url for file editing if editable on current server
                   3062: #          $home -- homeserver of resource (i.e., for author if published,
                   3063: #                                           or course if uploaded.).
                   3064: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  3065: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   3066: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  3067: #
                   3068: 
                   3069: sub can_edit_resource {
1.1194    raeburn  3070:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3071:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3072: #
                   3073: # For aboutme pages user can only edit his/her own.
                   3074: #
1.1199    raeburn  3075:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  3076:         my ($sdom,$sname) = ($1,$2);
                   3077:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3078:             $home = $env{'user.home'};
                   3079:             $cfile = $resurl;
                   3080:             if ($env{'form.forceedit'}) {
                   3081:                 $forceview = 1;
                   3082:             } else {
                   3083:                 $forceedit = 1;
                   3084:             }
                   3085:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3086:         } else {
                   3087:             return;
                   3088:         }
                   3089:     }
                   3090: 
                   3091:     if ($env{'request.course.id'}) {
                   3092:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3093:         if ($group ne '') {
                   3094: # if this is a group homepage or group bulletin board, check group privs
                   3095:             my $allowed = 0;
1.1197    raeburn  3096:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3097:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  3098:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  3099:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3100:                     $allowed = 1;
                   3101:                 }
1.1197    raeburn  3102:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3103:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3104:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  3105:                     $allowed = 1;
                   3106:                 }
                   3107:             }
                   3108:             if ($allowed) {
                   3109:                 $home=&homeserver($cnum,$cdom);
                   3110:                 if ($env{'form.forceedit'}) {
                   3111:                     $forceview = 1;
                   3112:                 } else {
                   3113:                     $forceedit = 1;
                   3114:                 }
                   3115:                 $cfile = $resurl;
                   3116:             } else {
                   3117:                 return;
                   3118:             }
                   3119:         } else {
1.1208    raeburn  3120:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3121:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3122:                     return;
                   3123:                 }
                   3124:             } elsif (!$crsedit) {
1.1194    raeburn  3125: #
                   3126: # No edit allowed where CC has switched to student role.
                   3127: #
                   3128:                 return;
                   3129:             }
                   3130:         }
                   3131:     }
                   3132: 
1.1193    raeburn  3133:     if ($file ne '') {
                   3134:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  3135:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3136:                 $uploaded = 1;
                   3137:                 $incourse = 1;
1.1193    raeburn  3138:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3139:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  3140:                     if ($env{'form.forceedit'}) {
                   3141:                         $forceview = 1;
                   3142:                     } else {
                   3143:                         $forceedit = 1;
                   3144:                     }
1.1194    raeburn  3145:                 }
                   3146:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3147:                 $incourse = 1;
                   3148:                 if ($env{'form.forceedit'}) {
                   3149:                     $forceview = 1;
                   3150:                 } else {
                   3151:                     $forceedit = 1;
                   3152:                 }
                   3153:                 $cfile = $resurl;
                   3154:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   3155:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3156:                     $incourse = 1;
                   3157:                     if ($env{'form.forceedit'}) {
                   3158:                         $forceview = 1;
                   3159:                     } else {
                   3160:                         $forceedit = 1;
                   3161:                     }
                   3162:                     $cfile = $resurl;
1.1199    raeburn  3163:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  3164:                     $incourse = 1;
                   3165:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  3166:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  3167:                     $incourse = 1;
1.1199    raeburn  3168:                     if ($env{'form.forceedit'}) {
                   3169:                         $forceview = 1;
                   3170:                     } else {
                   3171:                         $forceedit = 1;
                   3172:                     }
                   3173:                     $cfile = $resurl;
1.1298    raeburn  3174:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) {
                   3175:                     $incourse = 1;
                   3176:                     if ($env{'form.forceedit'}) {
                   3177:                         $forceview = 1;
                   3178:                     } else {
                   3179:                         $forceedit = 1;
                   3180:                     }
                   3181:                     $cfile = $resurl;
1.1208    raeburn  3182:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3183:                     $incourse = 1;
                   3184:                     if ($env{'form.forceedit'}) {
                   3185:                         $forceview = 1;
                   3186:                     } else {
                   3187:                         $forceedit = 1;
                   3188:                     }
                   3189:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  3190:                 }
                   3191:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3192:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3193:                 if (&is_on_map($template)) { 
                   3194:                     $incourse = 1;
                   3195:                     $forceview = 1;
                   3196:                     $cfile = $template;
1.1193    raeburn  3197:                 }
1.1199    raeburn  3198:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3199:                     $incourse = 1;
                   3200:                     if ($env{'form.forceedit'}) {
                   3201:                         $forceview = 1;
                   3202:                     } else {
                   3203:                         $forceedit = 1;
                   3204:                     }
                   3205:                     $cfile = $resurl;
1.1298    raeburn  3206:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3207:                 $incourse = 1;
                   3208:                 if ($env{'form.forceedit'}) {
                   3209:                     $forceview = 1;
                   3210:                 } else {
                   3211:                     $forceedit = 1;
                   3212:                 }
                   3213:                 $cfile = $resurl;
1.1199    raeburn  3214:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3215:                 $incourse = 1;
                   3216:                 $forceview = 1;
                   3217:                 if ($symb) {
                   3218:                     my ($map,$id,$res)=&decode_symb($symb);
                   3219:                     $env{'request.symb'} = $symb;
                   3220:                     $cfile = &clutter($res);
                   3221:                 } else {
                   3222:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  3223:                     my $escfile = &unescape($cfile);
                   3224:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/exttools?$}) {
                   3225:                         $cfile = '/adm/wrapper'.$escfile;
                   3226:                     } else {
                   3227:                         $escfile =~ s{^http://}{};
                   3228:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3229:                     }
1.1199    raeburn  3230:                 }
1.1234    raeburn  3231:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3232:                 if ($env{'form.forceedit'}) {
                   3233:                     $forceview = 1;
                   3234:                 } else {
                   3235:                     $forceedit = 1;
                   3236:                 }
                   3237:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  3238:             }
                   3239:         }
1.1194    raeburn  3240:         if ($uploaded || $incourse) {
                   3241:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  3242:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  3243:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3244:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3245:             # Check that the user has permission to edit this resource
                   3246:             my $setpriv = 1;
                   3247:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3248:             if (defined($cfudom)) {
                   3249:                 $home=&homeserver($cfuname,$cfudom);
                   3250:                 $cfile=$file;
                   3251:             }
                   3252:         }
1.1194    raeburn  3253:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   3254:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  3255:             my @ids=&current_machine_ids();
                   3256:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3257:                 $switchserver=1;
                   3258:             }
                   3259:         }
                   3260:     }
1.1194    raeburn  3261:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  3262: }
                   3263: 
                   3264: sub is_course_upload {
                   3265:     my ($file,$cnum,$cdom) = @_;
                   3266:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3267:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  3268:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3269:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  3270:         return 1;
                   3271:     }
                   3272:     return;
                   3273: }
                   3274: 
1.1194    raeburn  3275: sub in_course {
1.1195    raeburn  3276:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3277:     if ($hideprivileged) {
                   3278:         my $skipuser;
1.1219    raeburn  3279:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3280:         my @possdoms = ($cdom);  
                   3281:         if ($coursehash{'checkforpriv'}) { 
                   3282:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   3283:         }
                   3284:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  3285:             $skipuser = 1;
                   3286:             if ($coursehash{'nothideprivileged'}) {
                   3287:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3288:                     my $user;
                   3289:                     if ($item =~ /:/) {
                   3290:                         $user = $item;
                   3291:                     } else {
                   3292:                         $user = join(':',split(/[\@]/,$item));
                   3293:                     }
                   3294:                     if ($user eq $uname.':'.$udom) {
                   3295:                         undef($skipuser);
                   3296:                         last;
                   3297:                     }
                   3298:                 }
                   3299:             }
                   3300:             if ($skipuser) {
                   3301:                 return 0;
                   3302:             }
                   3303:         }
                   3304:     }
1.1194    raeburn  3305:     $type ||= 'any';
                   3306:     if (!defined($cdom) || !defined($cnum)) {
                   3307:         my $cid  = $env{'request.course.id'};
                   3308:         $cdom = $env{'course.'.$cid.'.domain'};
                   3309:         $cnum = $env{'course.'.$cid.'.num'};
                   3310:     }
                   3311:     my $typesref;
1.1195    raeburn  3312:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3313:         $typesref = ['active','previous','future'];
                   3314:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3315:         $typesref = [$type];
                   3316:     }
                   3317:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3318:                               $typesref,undef,[$cdom]);
                   3319:     my ($tmp) = keys(%roles);
                   3320:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3321:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3322:     if (@course_roles > 0) {
                   3323:         return 1;
                   3324:     }
                   3325:     return 0;
                   3326: }
                   3327: 
1.478     albertel 3328: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3329: # input: action, courseID, current domain, intended
1.637     raeburn  3330: #        path to file, source of file, instruction to parse file for objects,
                   3331: #        ref to hash for embedded objects,
                   3332: #        ref to hash for codebase of java objects.
1.1095    raeburn  3333: #        reference to scalar to accommodate mime type determined
                   3334: #          from File::MMagic if $parser = parse.
1.637     raeburn  3335: #
1.485     raeburn  3336: # output: url to file (if action was uploaddoc), 
                   3337: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3338: #
1.478     albertel 3339: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3340: # course.
1.477     raeburn  3341: #
1.478     albertel 3342: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3343: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3344: #          course's home server.
1.477     raeburn  3345: #
1.478     albertel 3346: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3347: #          be copied from $source (current location) to 
                   3348: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3349: #         and will then be copied to
                   3350: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3351: #         course's home server.
1.485     raeburn  3352: #
1.481     raeburn  3353: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3354: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3355: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3356: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3357: #         in course's home server.
1.637     raeburn  3358: #
1.477     raeburn  3359: 
                   3360: sub process_coursefile {
1.1095    raeburn  3361:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3362:         $mimetype)=@_;
1.477     raeburn  3363:     my $fetchresult;
1.638     albertel 3364:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3365:     if ($action eq 'propagate') {
1.638     albertel 3366:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3367: 			     $home);
1.481     raeburn  3368:     } else {
1.477     raeburn  3369:         my $fpath = '';
                   3370:         my $fname = $file;
1.478     albertel 3371:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3372:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3373:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3374:         if ($action eq 'copy') {
                   3375:             if ($source eq '') {
                   3376:                 $fetchresult = 'no source file';
                   3377:                 return $fetchresult;
                   3378:             } else {
                   3379:                 my $destination = $filepath.'/'.$fname;
                   3380:                 rename($source,$destination);
                   3381:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3382:                                  $home);
1.481     raeburn  3383:             }
                   3384:         } elsif ($action eq 'uploaddoc') {
                   3385:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 3386:             print $fh $env{'form.'.$source};
1.481     raeburn  3387:             close($fh);
1.637     raeburn  3388:             if ($parser eq 'parse') {
1.1024    raeburn  3389:                 my $mm = new File::MMagic;
1.1095    raeburn  3390:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3391:                 if ($type eq 'text/html') {
1.1024    raeburn  3392:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3393:                     unless ($parse_result eq 'ok') {
                   3394:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3395:                     }
1.637     raeburn  3396:                 }
1.1095    raeburn  3397:                 if (ref($mimetype)) {
                   3398:                     $$mimetype = $type;
                   3399:                 } 
1.637     raeburn  3400:             }
1.477     raeburn  3401:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3402:                                  $home);
1.481     raeburn  3403:             if ($fetchresult eq 'ok') {
                   3404:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3405:             } else {
                   3406:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3407:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3408:                 return '/adm/notfound.html';
                   3409:             }
1.477     raeburn  3410:         }
                   3411:     }
1.485     raeburn  3412:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3413:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3414:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3415:     }
                   3416:     return $fetchresult;
                   3417: }
                   3418: 
1.637     raeburn  3419: sub build_filepath {
                   3420:     my ($fpath) = @_;
                   3421:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3422:     unless ($fpath eq '') {
                   3423:         my @parts=split('/',$fpath);
                   3424:         foreach my $part (@parts) {
                   3425:             $filepath.= '/'.$part;
                   3426:             if ((-e $filepath)!=1) {
                   3427:                 mkdir($filepath,0777);
                   3428:             }
                   3429:         }
                   3430:     }
                   3431:     return $filepath;
                   3432: }
                   3433: 
                   3434: sub store_edited_file {
1.638     albertel 3435:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3436:     my $file = $primary_url;
                   3437:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3438:     my $fpath = '';
                   3439:     my $fname = $file;
                   3440:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3441:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3442:     my $filepath = &build_filepath($fpath);
                   3443:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3444:     print $fh $content;
                   3445:     close($fh);
1.638     albertel 3446:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3447:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3448: 			  $home);
1.637     raeburn  3449:     if ($$fetchresult eq 'ok') {
                   3450:         return '/uploaded/'.$fpath.'/'.$fname;
                   3451:     } else {
1.638     albertel 3452:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3453: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3454:         return '/adm/notfound.html';
                   3455:     }
                   3456: }
                   3457: 
1.531     albertel 3458: sub clean_filename {
1.831     albertel 3459:     my ($fname,$args)=@_;
1.315     www      3460: # Replace Windows backslashes by forward slashes
1.257     www      3461:     $fname=~s/\\/\//g;
1.831     albertel 3462:     if (!$args->{'keep_path'}) {
                   3463:         # Get rid of everything but the actual filename
                   3464: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3465:     }
1.315     www      3466: # Replace spaces by underscores
                   3467:     $fname=~s/\s+/\_/g;
                   3468: # Replace all other weird characters by nothing
1.831     albertel 3469:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3470: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3471: # numbers
                   3472:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3473:     return $fname;
                   3474: }
1.1051    raeburn  3475: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3476: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3477: # image with the same aspect ratio as the original, but with dimensions which do 
                   3478: # not exceed $resizewidth and $resizeheight.
                   3479:  
1.984     neumanie 3480: sub resizeImage {
1.1051    raeburn  3481:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3482:     my $ima = Image::Magick->new;
                   3483:     my $resized;
                   3484:     if (-e $img_path) {
                   3485:         $ima->Read($img_path);
                   3486:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3487:             my $width = $ima->Get('width');
                   3488:             my $height = $ima->Get('height');
                   3489:             if ($width > $resizewidth) {
                   3490: 	        my $factor = $width/$resizewidth;
                   3491:                 my $newheight = $height/$factor;
                   3492:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3493:                 $resized = 1;
                   3494:             }
                   3495:         }
                   3496:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3497:             my $width = $ima->Get('width');
                   3498:             my $height = $ima->Get('height');
                   3499:             if ($height > $resizeheight) {
                   3500:                 my $factor = $height/$resizeheight;
                   3501:                 my $newwidth = $width/$factor;
                   3502:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3503:                 $resized = 1;
                   3504:             }
                   3505:         }
                   3506:         if ($resized) {
                   3507:             $ima->Write($img_path);
                   3508:         }
                   3509:     }
                   3510:     return;
1.977     amueller 3511: }
                   3512: 
1.608     albertel 3513: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3514: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3515: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3516: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3517: #                                    canceloverwrite, or ''. 
                   3518: #                   if 'coursedoc': upload to the current course
                   3519: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3520: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3521: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3522: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3523: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3524: #        $allfiles - reference to hash for embedded objects
                   3525: #        $codebase - reference to hash for codebase of java objects
                   3526: #        $desuname - username for permanent storage of uploaded file
                   3527: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3528: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3529: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3530: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3531: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3532: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3533: #                    from File::MMagic.
1.858     raeburn  3534: # 
1.686     albertel 3535: # output: url of file in userspace, or error: <message> 
                   3536: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3537: 
1.531     albertel 3538: sub userfileupload {
1.1090    raeburn  3539:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3540:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3541:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3542:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3543:     $fname=&clean_filename($fname);
1.1090    raeburn  3544:     # See if there is anything left
1.257     www      3545:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3546:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3547:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3548:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3549:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3550:         my $now = time;
1.1090    raeburn  3551:         my $filepath;
1.1095    raeburn  3552:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3553:              $filepath = 'tmp/helprequests/'.$now;
                   3554:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3555:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3556:                          '_'.$env{'user.domain'}.'/pending';
                   3557:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3558:             my ($docuname,$docudom);
                   3559:             if ($destudom) {
                   3560:                 $docudom = $destudom;
                   3561:             } else {
                   3562:                 $docudom = $env{'user.domain'};
                   3563:             }
                   3564:             if ($destuname) {
                   3565:                 $docuname = $destuname;
                   3566:             } else {
                   3567:                 $docuname = $env{'user.name'};
                   3568:             }
                   3569:             if (exists($env{'form.group'})) {
                   3570:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3571:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3572:             }
                   3573:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3574:             if ($context eq 'canceloverwrite') {
                   3575:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3576:                 if (-e  $tempfile) {
                   3577:                     my @info = stat($tempfile);
                   3578:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3579:                         unlink($tempfile);
                   3580:                     }
                   3581:                 }
                   3582:                 return;
1.523     raeburn  3583:             }
                   3584:         }
1.1090    raeburn  3585:         # Create the directory if not present
1.741     raeburn  3586:         my @parts=split(/\//,$filepath);
                   3587:         my $fullpath = $perlvar{'lonDaemons'};
                   3588:         for (my $i=0;$i<@parts;$i++) {
                   3589:             $fullpath .= '/'.$parts[$i];
                   3590:             if ((-e $fullpath)!=1) {
                   3591:                 mkdir($fullpath,0777);
                   3592:             }
                   3593:         }
                   3594:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3595:         print $fh $env{'form.'.$formname};
                   3596:         close($fh);
1.1090    raeburn  3597:         if ($context eq 'existingfile') {
                   3598:             my @info = stat($fullpath.'/'.$fname);
                   3599:             return ($fullpath.'/'.$fname,$info[9]);
                   3600:         } else {
                   3601:             return $fullpath.'/'.$fname;
                   3602:         }
1.523     raeburn  3603:     }
1.995     raeburn  3604:     if ($subdir eq 'scantron') {
                   3605:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3606:     } else {
1.995     raeburn  3607:         $fname="$subdir/$fname";
                   3608:     }
1.1090    raeburn  3609:     if ($context eq 'coursedoc') {
1.638     albertel 3610: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3611: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3612:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3613:             return &finishuserfileupload($docuname,$docudom,
                   3614: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3615: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3616:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3617:         } else {
1.1218    raeburn  3618:             if ($env{'form.folder'}) {
                   3619:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3620:             }
1.638     albertel 3621:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3622: 				       $fname,$formname,$parser,
1.1095    raeburn  3623: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3624:         }
1.719     banghart 3625:     } elsif (defined($destuname)) {
                   3626:         my $docuname=$destuname;
                   3627:         my $docudom=$destudom;
1.860     raeburn  3628: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3629: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3630:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3631:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3632:     } else {
1.638     albertel 3633:         my $docuname=$env{'user.name'};
                   3634:         my $docudom=$env{'user.domain'};
1.1220    raeburn  3635:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3636:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3637:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3638:         }
1.860     raeburn  3639: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3640: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3641:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3642:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3643:     }
1.271     www      3644: }
                   3645: 
                   3646: sub finishuserfileupload {
1.860     raeburn  3647:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3648:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3649:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3650:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3651:   
1.860     raeburn  3652:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3653:     $file=$fname;
                   3654:     if ($fname=~m|/|) {
                   3655:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3656: 	$path.=$fnamepath.'/';
                   3657:     }
1.259     www      3658:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3659:     my $count;
                   3660:     for ($count=4;$count<=$#parts;$count++) {
                   3661:         $filepath.="/$parts[$count]";
                   3662:         if ((-e $filepath)!=1) {
                   3663: 	    mkdir($filepath,0777);
                   3664:         }
                   3665:     }
1.984     neumanie 3666: 
1.258     www      3667: # Save the file
                   3668:     {
1.701     albertel 3669: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3670: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3671: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3672: 	    return '/adm/notfound.html';
                   3673: 	}
1.1090    raeburn  3674:         if ($context eq 'overwrite') {
1.1117    foxr     3675:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3676:             my $target = $filepath.'/'.$file;
                   3677:             if (-e $source) {
                   3678:                 my @info = stat($source);
                   3679:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3680:                     unless (&File::Copy::move($source,$target)) {
                   3681:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3682:                         return "Moving from $source failed";
                   3683:                     }
                   3684:                 } else {
                   3685:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3686:                 }
                   3687:             } else {
                   3688:                 return "Temporary file: $source missing";
                   3689:             }
                   3690:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3691: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3692: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3693: 	    return '/adm/notfound.html';
                   3694: 	}
1.570     albertel 3695: 	close(FH);
1.1051    raeburn  3696:         if ($resizewidth && $resizeheight) {
                   3697:             my $mm = new File::MMagic;
                   3698:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3699:             if ($mime_type =~ m{^image/}) {
                   3700: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3701:             }  
1.977     amueller 3702: 	}
1.258     www      3703:     }
1.1152    raeburn  3704:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3705:         if (ref($mimetype)) {
                   3706:             if ($$mimetype eq '') {
                   3707:                 my $mm = new File::MMagic;
                   3708:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3709:                 $$mimetype = $type;
                   3710:             }
                   3711:         }
                   3712:     }
1.637     raeburn  3713:     if ($parser eq 'parse') {
1.1152    raeburn  3714:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3715:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3716:                                                        $allfiles,$codebase);
                   3717:             unless ($parse_result eq 'ok') {
                   3718:                 &logthis('Failed to parse '.$filepath.$file.
                   3719: 	   	         ' for embedded media: '.$parse_result); 
                   3720:             }
1.637     raeburn  3721:         }
                   3722:     }
1.860     raeburn  3723:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3724:         my $input = $filepath.'/'.$file;
                   3725:         my $output = $filepath.'/'.'tn-'.$file;
                   3726:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3727:         system("convert -sample $thumbsize $input $output");
                   3728:         if (-e $filepath.'/'.'tn-'.$file) {
                   3729:             $fetchthumb  = 1; 
                   3730:         }
                   3731:     }
1.858     raeburn  3732:  
1.259     www      3733: # Notify homeserver to grep it
                   3734: #
1.984     neumanie 3735:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3736:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3737:     if ($fetchresult eq 'ok') {
1.860     raeburn  3738:         if ($fetchthumb) {
                   3739:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3740:             if ($thumbresult ne 'ok') {
                   3741:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3742:                          $docuhome.': '.$thumbresult);
                   3743:             }
                   3744:         }
1.259     www      3745: #
1.258     www      3746: # Return the URL to it
1.494     albertel 3747:         return '/uploaded/'.$path.$file;
1.263     www      3748:     } else {
1.494     albertel 3749:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3750: 		 ': '.$fetchresult);
1.263     www      3751:         return '/adm/notfound.html';
1.858     raeburn  3752:     }
1.493     albertel 3753: }
                   3754: 
1.637     raeburn  3755: sub extract_embedded_items {
1.961     raeburn  3756:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3757:     my @state = ();
1.1164    raeburn  3758:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3759:     my %javafiles = (
                   3760:                       codebase => '',
                   3761:                       code => '',
                   3762:                       archive => ''
                   3763:                     );
                   3764:     my %mediafiles = (
                   3765:                       src => '',
                   3766:                       movie => '',
                   3767:                      );
1.648     raeburn  3768:     my $p;
                   3769:     if ($content) {
                   3770:         $p = HTML::LCParser->new($content);
                   3771:     } else {
1.961     raeburn  3772:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3773:     }
1.641     albertel 3774:     while (my $t=$p->get_token()) {
1.640     albertel 3775: 	if ($t->[0] eq 'S') {
                   3776: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3777: 	    push(@state, $tagname);
1.648     raeburn  3778:             if (lc($tagname) eq 'allow') {
                   3779:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3780:             }
1.640     albertel 3781: 	    if (lc($tagname) eq 'img') {
                   3782: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3783: 	    }
1.886     albertel 3784: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  3785:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  3786:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3787:                 }
1.886     albertel 3788: 	    }
1.645     raeburn  3789:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3790:                 my $src;
1.645     raeburn  3791:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3792:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3793:                 } else {
1.1164    raeburn  3794:                     if ($attr->{'src'} ne '') {
                   3795:                         $src = $attr->{'src'};
                   3796:                         &add_filetype($allfiles,$src,'src');
                   3797:                     }
                   3798:                 }
                   3799:                 my $text = $p->get_trimmed_text();
                   3800:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3801:                     my @swfargs = split(/,/,$1);
                   3802:                     foreach my $item (@swfargs) {
                   3803:                         $item =~ s/["']//g;
                   3804:                         $item =~ s/^\s+//;
                   3805:                         $item =~ s/\s+$//;
                   3806:                     }
                   3807:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3808:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3809:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3810:                         } else {
                   3811:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3812:                         }
                   3813:                     }
1.645     raeburn  3814:                 }
                   3815:             }
                   3816:             if (lc($tagname) eq 'link') {
                   3817:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3818:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3819:                 }
                   3820:             }
1.640     albertel 3821: 	    if (lc($tagname) eq 'object' ||
                   3822: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3823: 		foreach my $item (keys(%javafiles)) {
                   3824: 		    $javafiles{$item} = '';
                   3825: 		}
1.1164    raeburn  3826:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3827:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3828:                 }
1.640     albertel 3829: 	    }
                   3830: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3831: 		my $name = lc($attr->{'name'});
                   3832: 		foreach my $item (keys(%javafiles)) {
                   3833: 		    if ($name eq $item) {
                   3834: 			$javafiles{$item} = $attr->{'value'};
                   3835: 			last;
                   3836: 		    }
                   3837: 		}
1.1164    raeburn  3838:                 my $pathfrom;
1.640     albertel 3839: 		foreach my $item (keys(%mediafiles)) {
                   3840: 		    if ($name eq $item) {
1.1164    raeburn  3841:                         $pathfrom = $attr->{'value'};
                   3842:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3843: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3844: 			last;
                   3845: 		    }
                   3846: 		}
1.1164    raeburn  3847:                 if ($name eq 'flashvars') {
                   3848:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3849:                 }
                   3850:                 if ($pathfrom ne '') {
                   3851:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3852:                                          $pathfrom);
                   3853:                 }
1.640     albertel 3854: 	    }
                   3855: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3856: 		foreach my $item (keys(%javafiles)) {
                   3857: 		    if ($attr->{$item}) {
                   3858: 			$javafiles{$item} = $attr->{$item};
                   3859: 			last;
                   3860: 		    }
                   3861: 		}
                   3862: 		foreach my $item (keys(%mediafiles)) {
                   3863: 		    if ($attr->{$item}) {
                   3864: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3865: 			last;
                   3866: 		    }
                   3867: 		}
1.1164    raeburn  3868:                 if (lc($tagname) eq 'embed') {
                   3869:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3870:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3871:                                              $attr->{'src'});
                   3872:                     }
                   3873:                 }
1.640     albertel 3874: 	    }
1.1243    raeburn  3875:             if (lc($tagname) eq 'iframe') {
                   3876:                 my $src = $attr->{'src'} ;
                   3877:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   3878:                     &add_filetype($allfiles,$src,'src');
                   3879:                 } elsif ($src =~ m{^/}) {
                   3880:                     if ($env{'request.course.id'}) {
                   3881:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3882:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3883:                         my $url = &hreflocation('',$fullpath);
                   3884:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   3885:                             my $relpath = $1;
                   3886:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   3887:                                 &add_filetype($allfiles,$1,'src');
                   3888:                             }
                   3889:                         }
                   3890:                     }
                   3891:                 }
                   3892:             }
1.1164    raeburn  3893:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  3894:                 pop(@state);
1.1164    raeburn  3895:             }
1.640     albertel 3896: 	} elsif ($t->[0] eq 'E') {
                   3897: 	    my ($tagname) = ($t->[1]);
                   3898: 	    if ($javafiles{'codebase'} ne '') {
                   3899: 		$javafiles{'codebase'} .= '/';
                   3900: 	    }  
                   3901: 	    if (lc($tagname) eq 'applet' ||
                   3902: 		lc($tagname) eq 'object' ||
                   3903: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3904: 		) {
                   3905: 		foreach my $item (keys(%javafiles)) {
                   3906: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3907: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3908: 			&add_filetype($allfiles,$file,$item);
                   3909: 		    }
                   3910: 		}
                   3911: 	    } 
                   3912: 	    pop @state;
                   3913: 	}
                   3914:     }
1.1164    raeburn  3915:     foreach my $id (sort(keys(%flashvars))) {
                   3916:         if ($shockwave{$id} ne '') {
                   3917:             my @pairs = split(/\&/,$flashvars{$id});
                   3918:             foreach my $pair (@pairs) {
                   3919:                 my ($key,$value) = split(/\=/,$pair);
                   3920:                 if ($key eq 'thumb') {
                   3921:                     &add_filetype($allfiles,$value,$key);
                   3922:                 } elsif ($key eq 'content') {
                   3923:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3924:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3925:                     if ($ext ne '') {
                   3926:                         &add_filetype($allfiles,$path.$value,$ext);
                   3927:                     }
                   3928:                 }
                   3929:             }
                   3930:         }
                   3931:     }
1.637     raeburn  3932:     return 'ok';
                   3933: }
                   3934: 
1.639     albertel 3935: sub add_filetype {
                   3936:     my ($allfiles,$file,$type)=@_;
                   3937:     if (exists($allfiles->{$file})) {
                   3938: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3939: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3940: 	}
                   3941:     } else {
                   3942: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3943:     }
                   3944: }
                   3945: 
1.1164    raeburn  3946: sub embedded_dependency {
                   3947:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3948:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3949:         if (($identifier ne '') &&
                   3950:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3951:             ($pathfrom ne '')) {
                   3952:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3953:             foreach my $dep (@{$related->{$identifier}}) {
                   3954:                 &add_filetype($allfiles,$path.$dep,'object');
                   3955:             }
                   3956:         }
                   3957:     }
                   3958:     return;
                   3959: }
                   3960: 
1.493     albertel 3961: sub removeuploadedurl {
1.984     neumanie 3962:     my ($url)=@_;	
                   3963:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3964:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3965: }
                   3966: 
                   3967: sub removeuserfile {
                   3968:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3969:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3970:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3971:     if ($result eq 'ok') {	
1.798     raeburn  3972:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3973:             my $metafile = $fname.'.meta';
                   3974:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3975: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3976:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3977:             my $sqlresult = 
1.823     albertel 3978:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3979:                                         'portfolio_metadata',$group,
                   3980:                                         'delete');
1.798     raeburn  3981:         }
                   3982:     }
                   3983:     return $result;
1.257     www      3984: }
1.15      www      3985: 
1.530     albertel 3986: sub mkdiruserfile {
                   3987:     my ($docuname,$docudom,$dir)=@_;
                   3988:     my $home=&homeserver($docuname,$docudom);
                   3989:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3990: }
                   3991: 
1.531     albertel 3992: sub renameuserfile {
                   3993:     my ($docuname,$docudom,$old,$new)=@_;
                   3994:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3995:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3996:                         &escape("$old").':'.&escape("$new"),$home);
                   3997:     if ($result eq 'ok') {
                   3998:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3999:             my $oldmeta = $old.'.meta';
                   4000:             my $newmeta = $new.'.meta';
                   4001:             my $metaresult = 
                   4002:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4003: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4004:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4005:             my $sqlresult = 
1.823     albertel 4006:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4007:                                         'portfolio_metadata',$group,
                   4008:                                         'delete');
1.798     raeburn  4009:         }
                   4010:     }
                   4011:     return $result;
1.531     albertel 4012: }
                   4013: 
1.14      www      4014: # ------------------------------------------------------------------------- Log
                   4015: 
                   4016: sub log {
                   4017:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4018:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4019: }
                   4020: 
                   4021: # ------------------------------------------------------------------ Course Log
1.352     www      4022: #
                   4023: # This routine flushes several buffers of non-mission-critical nature
                   4024: #
1.157     www      4025: 
                   4026: sub flushcourselogs {
1.352     www      4027:     &logthis('Flushing log buffers');
                   4028: #
                   4029: # course logs
                   4030: # This is a log of all transactions in a course, which can be used
                   4031: # for data mining purposes
                   4032: #
                   4033: # It also collects the courseid database, which lists last transaction
                   4034: # times and course titles for all courseids
                   4035: #
                   4036:     my %courseidbuffer=();
1.921     raeburn  4037:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4038:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4039: 		          &escape($courselogs{$crsid}),
                   4040: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4041: 	    delete $courselogs{$crsid};
                   4042:         } else {
                   4043:             &logthis('Failed to flush log buffer for '.$crsid);
                   4044:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4045:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4046:                         " exceeded maximum size, deleting.</font>");
                   4047:                delete $courselogs{$crsid};
                   4048:             }
1.352     www      4049:         }
1.920     raeburn  4050:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4051:             'description' => $coursedescrbuf{$crsid},
                   4052:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4053:             'type'        => $coursetypebuf{$crsid},
                   4054:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4055:         };
1.191     harris41 4056:     }
1.352     www      4057: #
                   4058: # Write course id database (reverse lookup) to homeserver of courses 
                   4059: # Is used in pickcourse
                   4060: #
1.840     albertel 4061:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4062:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4063:                                     $courseidbuffer{$crs_home},
                   4064:                                     $crs_home,'timeonly');
1.352     www      4065:     }
                   4066: #
                   4067: # File accesses
                   4068: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4069: #
1.449     matthew  4070:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4071:         if ($entry =~ /___count$/) {
                   4072:             my ($dom,$name);
1.807     albertel 4073:             ($dom,$name,undef)=
1.811     albertel 4074: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4075:             if (! defined($dom) || $dom eq '' || 
                   4076:                 ! defined($name) || $name eq '') {
1.620     albertel 4077:                 my $cid = $env{'request.course.id'};
                   4078:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4079:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4080:             }
1.450     matthew  4081:             my $value = $accesshash{$entry};
                   4082:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4083:             my %temphash=($url => $value);
1.449     matthew  4084:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4085:             if ($result eq 'ok') {
                   4086:                 delete $accesshash{$entry};
                   4087:             }
                   4088:         } else {
1.811     albertel 4089:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4090:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4091:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4092:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4093:                 delete $accesshash{$entry};
                   4094:             }
1.185     www      4095:         }
1.191     harris41 4096:     }
1.352     www      4097: #
                   4098: # Roles
                   4099: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4100: #
1.800     albertel 4101:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4102:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4103: 	    split(/\:/,$entry);
                   4104:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4105:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4106:                 $rudom,$runame) eq 'ok') {
                   4107: 	    delete $userrolehash{$entry};
                   4108:         }
                   4109:     }
1.662     raeburn  4110: #
                   4111: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   4112: #
                   4113:     my %domrolebuffer = ();
1.1000    raeburn  4114:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4115:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4116:         if ($domrolebuffer{$rudom}) {
                   4117:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4118:                       '='.&escape($domainrolehash{$entry});
                   4119:         } else {
                   4120:             $domrolebuffer{$rudom}.=&escape($entry).
                   4121:                       '='.&escape($domainrolehash{$entry});
                   4122:         }
                   4123:         delete $domainrolehash{$entry};
                   4124:     }
                   4125:     foreach my $dom (keys(%domrolebuffer)) {
1.1324  ! raeburn  4126: 	my %servers;
        !          4127: 	if (defined(&domain($dom,'primary'))) {
        !          4128: 	    my $primary=&domain($dom,'primary');
        !          4129: 	    my $hostname=&hostname($primary);
        !          4130: 	    $servers{$primary} = $hostname;
        !          4131: 	} else { 
        !          4132: 	    %servers = &get_servers($dom,'library');
        !          4133: 	}
1.841     albertel 4134: 	foreach my $tryserver (keys(%servers)) {
1.1324  ! raeburn  4135: 	    if (&reply('domroleput:'.$dom.':'.
        !          4136: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
        !          4137: 		last;
        !          4138: 	    } else {  
1.841     albertel 4139: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4140: 	    }
1.662     raeburn  4141:         }
                   4142:     }
1.186     www      4143:     $dumpcount++;
1.157     www      4144: }
                   4145: 
                   4146: sub courselog {
                   4147:     my $what=shift;
1.158     www      4148:     $what=time.':'.$what;
1.620     albertel 4149:     unless ($env{'request.course.id'}) { return ''; }
                   4150:     $coursedombuf{$env{'request.course.id'}}=
                   4151:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4152:     $coursenumbuf{$env{'request.course.id'}}=
                   4153:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4154:     $coursehombuf{$env{'request.course.id'}}=
                   4155:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4156:     $coursedescrbuf{$env{'request.course.id'}}=
                   4157:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4158:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4159:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4160:     $courseownerbuf{$env{'request.course.id'}}=
                   4161:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4162:     $coursetypebuf{$env{'request.course.id'}}=
                   4163:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4164:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4165: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4166:     } else {
1.620     albertel 4167: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4168:     }
1.620     albertel 4169:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4170: 	&flushcourselogs();
                   4171:     }
1.158     www      4172: }
                   4173: 
                   4174: sub courseacclog {
                   4175:     my $fnsymb=shift;
1.620     albertel 4176:     unless ($env{'request.course.id'}) { return ''; }
                   4177:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4178:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4179:         $what.=':POST';
1.583     matthew  4180:         # FIXME: Probably ought to escape things....
1.800     albertel 4181: 	foreach my $key (keys(%env)) {
                   4182:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4183:                 my $formitem = $1;
                   4184:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4185:                     $what.=':'.$formitem.'='.$env{$key};
                   4186:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4187:                     $what.=':'.$formitem.'='.$env{$key};
                   4188:                 }
1.158     www      4189:             }
1.191     harris41 4190:         }
1.583     matthew  4191:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4192:         # FIXME: We should not be depending on a form parameter that someone
                   4193:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4194:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4195:             $what.= ':POST';
                   4196:             # FIXME: Probably ought to escape things....
                   4197:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4198:                                  'crsdiscuss') {
1.620     albertel 4199:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4200:             }
                   4201:         }
1.158     www      4202:     }
                   4203:     &courselog($what);
1.149     www      4204: }
                   4205: 
1.185     www      4206: sub countacc {
                   4207:     my $url=&declutter(shift);
1.458     matthew  4208:     return if (! defined($url) || $url eq '');
1.620     albertel 4209:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4210: #
                   4211: # Mark that this url was used in this course
                   4212: #
1.620     albertel 4213:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4214: #
                   4215: # Increase the access count for this resource in this child process
                   4216: #
1.281     www      4217:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4218:     $accesshash{$key}++;
1.185     www      4219: }
1.349     www      4220: 
1.361     www      4221: sub linklog {
                   4222:     my ($from,$to)=@_;
                   4223:     $from=&declutter($from);
                   4224:     $to=&declutter($to);
                   4225:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4226:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4227: }
1.1160    www      4228: 
                   4229: sub statslog {
                   4230:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4231:     if ($users<2) { return; }
                   4232:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4233:             'course'       => $env{'request.course.id'},
                   4234:             'sections'     => '"all"',
                   4235:             'num_students' => $users,
                   4236:             'part'         => $part,
                   4237:             'symb'         => $symb,
                   4238:             'mean_tries'   => $av_attempts,
                   4239:             'deg_of_diff'  => $degdiff});
                   4240:     foreach my $key (keys(%dynstore)) {
                   4241:         $accesshash{$key}=$dynstore{$key};
                   4242:     }
                   4243: }
1.361     www      4244:   
1.349     www      4245: sub userrolelog {
                   4246:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4247:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4248:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4249:        $userrolehash
                   4250:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4251:                     =$tend.':'.$tstart;
1.662     raeburn  4252:     }
1.1169    droeschl 4253:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4254:        $userrolehash
                   4255:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4256:                     =$tend.':'.$tstart;
                   4257:     }
1.1169    droeschl 4258:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  4259:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4260:        $domainrolehash
                   4261:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4262:                     = $tend.':'.$tstart;
                   4263:     }
1.351     www      4264: }
                   4265: 
1.957     raeburn  4266: sub courserolelog {
                   4267:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  4268:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4269:         my $cdom = $1;
                   4270:         my $cnum = $2;
                   4271:         my $sec = $3;
                   4272:         my $namespace = 'rolelog';
                   4273:         my %storehash = (
                   4274:                            role    => $trole,
                   4275:                            start   => $tstart,
                   4276:                            end     => $tend,
                   4277:                            selfenroll => $selfenroll,
                   4278:                            context    => $context,
                   4279:                         );
                   4280:         if ($trole eq 'gr') {
                   4281:             $namespace = 'groupslog';
                   4282:             $storehash{'group'} = $sec;
                   4283:         } else {
                   4284:             $storehash{'section'} = $sec;
                   4285:         }
1.1188    raeburn  4286:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4287:                    $domain,$cnum,$cdom);
1.1184    raeburn  4288:         if (($trole ne 'st') || ($sec ne '')) {
                   4289:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4290:         }
                   4291:     }
                   4292:     return;
                   4293: }
                   4294: 
1.1184    raeburn  4295: sub domainrolelog {
                   4296:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4297:     if ($area =~ m{^/($match_domain)/$}) {
                   4298:         my $cdom = $1;
                   4299:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4300:         my $namespace = 'rolelog';
                   4301:         my %storehash = (
                   4302:                            role    => $trole,
                   4303:                            start   => $tstart,
                   4304:                            end     => $tend,
                   4305:                            context => $context,
                   4306:                         );
1.1188    raeburn  4307:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4308:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  4309:     }
                   4310:     return;
                   4311: 
                   4312: }
                   4313: 
                   4314: sub coauthorrolelog {
                   4315:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4316:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4317:         my $audom = $1;
                   4318:         my $auname = $2;
                   4319:         my $namespace = 'rolelog';
                   4320:         my %storehash = (
                   4321:                            role    => $trole,
                   4322:                            start   => $tstart,
                   4323:                            end     => $tend,
                   4324:                            context => $context,
                   4325:                         );
1.1188    raeburn  4326:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4327:                    $domain,$auname,$audom);
1.1184    raeburn  4328:     }
                   4329:     return;
                   4330: }
                   4331: 
1.351     www      4332: sub get_course_adv_roles {
1.948     raeburn  4333:     my ($cid,$codes) = @_;
1.620     albertel 4334:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4335:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4336:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4337:     my %nothide=();
1.800     albertel 4338:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4339:         if ($user !~ /:/) {
                   4340: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4341:         } else {
                   4342:             $nothide{$user}=1;
                   4343:         }
1.470     www      4344:     }
1.1219    raeburn  4345:     my @possdoms = ($coursehash{'domain'});
                   4346:     if ($coursehash{'checkforpriv'}) {
                   4347:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4348:     }
1.351     www      4349:     my %returnhash=();
                   4350:     my %dumphash=
                   4351:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4352:     my $now=time;
1.997     raeburn  4353:     my %privileged;
1.1000    raeburn  4354:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4355: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4356:         if (($tstart) && ($tstart<0)) { next; }
                   4357:         if (($tend) && ($tend<$now)) { next; }
                   4358:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4359:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4360: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  4361:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4362:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4363: 	if ($role eq 'cr') { next; }
1.948     raeburn  4364:         if ($codes) {
                   4365:             if ($section) { $role .= ':'.$section; }
                   4366:             if ($returnhash{$role}) {
                   4367:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4368:             } else {
                   4369:                 $returnhash{$role}=$username.':'.$domain;
                   4370:             }
1.351     www      4371:         } else {
1.988     raeburn  4372:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4373:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4374:             if ($returnhash{$key}) {
                   4375: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4376:             } else {
                   4377:                 $returnhash{$key}=$username.':'.$domain;
                   4378:             }
1.351     www      4379:         }
1.948     raeburn  4380:     }
1.400     www      4381:     return %returnhash;
                   4382: }
                   4383: 
                   4384: sub get_my_roles {
1.937     raeburn  4385:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4386:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4387:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4388:     my (%dumphash,%nothide);
1.1086    raeburn  4389:     if ($context eq 'userroles') {
1.1166    raeburn  4390:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4391:     } else {
1.1219    raeburn  4392:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4393:         if ($hidepriv) {
                   4394:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4395:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4396:                 if ($user !~ /:/) {
                   4397:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4398:                 } else {
                   4399:                     $nothide{$user} = 1;
                   4400:                 }
                   4401:             }
                   4402:         }
1.858     raeburn  4403:     }
1.400     www      4404:     my %returnhash=();
                   4405:     my $now=time;
1.999     raeburn  4406:     my %privileged;
1.800     albertel 4407:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4408:         my ($role,$tend,$tstart);
                   4409:         if ($context eq 'userroles') {
1.1149    raeburn  4410:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4411: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4412:         } else {
                   4413:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4414:         }
1.400     www      4415:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4416:         my $status = 'active';
1.939     raeburn  4417:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4418:             $status = 'previous';
                   4419:         } 
                   4420:         if (($tstart) && ($now<$tstart)) {
                   4421:             $status = 'future';
                   4422:         }
                   4423:         if (ref($types) eq 'ARRAY') {
                   4424:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4425:                 next;
                   4426:             } 
                   4427:         } else {
                   4428:             if ($status ne 'active') {
                   4429:                 next;
                   4430:             }
                   4431:         }
1.867     raeburn  4432:         my ($rolecode,$username,$domain,$section,$area);
                   4433:         if ($context eq 'userroles') {
1.1186    raeburn  4434:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4435:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4436:         } else {
                   4437:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4438:         }
1.832     raeburn  4439:         if (ref($roledoms) eq 'ARRAY') {
                   4440:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4441:                 next;
                   4442:             }
                   4443:         }
                   4444:         if (ref($roles) eq 'ARRAY') {
                   4445:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4446:                 if ($role =~ /^cr\//) {
                   4447:                     if (!grep(/^cr$/,@{$roles})) {
                   4448:                         next;
                   4449:                     }
1.1104    raeburn  4450:                 } elsif ($role =~ /^gr\//) {
                   4451:                     if (!grep(/^gr$/,@{$roles})) {
                   4452:                         next;
                   4453:                     }
1.922     raeburn  4454:                 } else {
                   4455:                     next;
                   4456:                 }
1.832     raeburn  4457:             }
1.867     raeburn  4458:         }
1.937     raeburn  4459:         if ($hidepriv) {
1.1219    raeburn  4460:             my @privroles = ('dc','su');
1.999     raeburn  4461:             if ($context eq 'userroles') {
1.1219    raeburn  4462:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4463:             } else {
1.1219    raeburn  4464:                 my $possdoms = [$domain];
                   4465:                 if (ref($roledoms) eq 'ARRAY') {
                   4466:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  4467:                 }
1.1219    raeburn  4468:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4469:                     if (!$nothide{$username.':'.$domain}) {
                   4470:                         next;
                   4471:                     }
                   4472:                 }
1.937     raeburn  4473:             }
                   4474:         }
1.933     raeburn  4475:         if ($withsec) {
                   4476:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4477:                 $tstart.':'.$tend;
                   4478:         } else {
                   4479:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4480:         }
1.832     raeburn  4481:     }
1.373     www      4482:     return %returnhash;
1.399     www      4483: }
                   4484: 
                   4485: # ----------------------------------------------------- Frontpage Announcements
                   4486: #
                   4487: #
                   4488: 
                   4489: sub postannounce {
                   4490:     my ($server,$text)=@_;
1.844     albertel 4491:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4492:     unless ($text=~/\w/) { $text=''; }
                   4493:     return &reply('setannounce:'.&escape($text),$server);
                   4494: }
                   4495: 
                   4496: sub getannounce {
1.448     albertel 4497: 
                   4498:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4499: 	my $announcement='';
1.800     albertel 4500: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4501: 	close($fh);
1.399     www      4502: 	if ($announcement=~/\w/) { 
                   4503: 	    return 
                   4504:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4505:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4506: 	} else {
                   4507: 	    return '';
                   4508: 	}
                   4509:     } else {
                   4510: 	return '';
                   4511:     }
1.351     www      4512: }
1.353     www      4513: 
                   4514: # ---------------------------------------------------------- Course ID routines
                   4515: # Deal with domain's nohist_courseid.db files
                   4516: #
                   4517: 
                   4518: sub courseidput {
1.921     raeburn  4519:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4520:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4521:     my $outcome;
                   4522:     if ($caller eq 'timeonly') {
                   4523:         my $cids = '';
                   4524:         foreach my $item (keys(%$storehash)) {
                   4525:             $cids.=&escape($item).'&';
                   4526:         }
                   4527:         $cids=~s/\&$//;
                   4528:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4529:                           $coursehome);       
                   4530:     } else {
                   4531:         my $items = '';
                   4532:         foreach my $item (keys(%$storehash)) {
                   4533:             $items.= &escape($item).'='.
                   4534:                      &freeze_escape($$storehash{$item}).'&';
                   4535:         }
                   4536:         $items=~s/\&$//;
                   4537:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4538:                           $coursehome);
1.918     raeburn  4539:     }
                   4540:     if ($outcome eq 'unknown_cmd') {
                   4541:         my $what;
                   4542:         foreach my $cid (keys(%$storehash)) {
                   4543:             $what .= &escape($cid).'=';
1.921     raeburn  4544:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4545:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4546:             }
                   4547:             $what =~ s/\:$/&/;
                   4548:         }
                   4549:         $what =~ s/\&$//;  
                   4550:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4551:     } else {
                   4552:         return $outcome;
                   4553:     }
1.353     www      4554: }
                   4555: 
                   4556: sub courseiddump {
1.921     raeburn  4557:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4558:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4559:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  4560:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  4561:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  4562:     my $as_hash = 1;
                   4563:     my %returnhash;
                   4564:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4565:     my %libserv = &all_library();
                   4566:     foreach my $tryserver (keys(%libserv)) {
                   4567:         if ( (  $hostidflag == 1 
                   4568: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4569: 	     || (!defined($hostidflag)) ) {
                   4570: 
1.918     raeburn  4571: 	    if (($domfilter eq '') ||
                   4572: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 4573:                 my $rep;
                   4574:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   4575:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   4576:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   4577:                                 &escape($descfilter), &escape($instcodefilter), 
                   4578:                                 &escape($ownerfilter), &escape($coursefilter),
                   4579:                                 &escape($typefilter), &escape($regexp_ok), 
                   4580:                                 $as_hash, &escape($selfenrollonly), 
                   4581:                                 &escape($catfilter), $showhidden, $caller, 
                   4582:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   4583:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  4584:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   4585:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 4586:                 } else {
                   4587:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4588:                              $sincefilter.':'.&escape($descfilter).':'.
                   4589:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4590:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4591:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4592:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4593:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4594:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4595:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  4596:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   4597:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 4598:                 }
                   4599:                      
1.918     raeburn  4600:                 my @pairs=split(/\&/,$rep);
                   4601:                 foreach my $item (@pairs) {
                   4602:                     my ($key,$value)=split(/\=/,$item,2);
                   4603:                     $key = &unescape($key);
                   4604:                     next if ($key =~ /^error: 2 /);
                   4605:                     my $result = &thaw_unescape($value);
                   4606:                     if (ref($result) eq 'HASH') {
                   4607:                         $returnhash{$key}=$result;
                   4608:                     } else {
1.921     raeburn  4609:                         my @responses = split(/:/,$value);
                   4610:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4611:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4612:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4613:                         }
1.1008    raeburn  4614:                     }
1.353     www      4615:                 }
                   4616:             }
                   4617:         }
                   4618:     }
                   4619:     return %returnhash;
                   4620: }
                   4621: 
1.1055    raeburn  4622: sub courselastaccess {
                   4623:     my ($cdom,$cnum,$hostidref) = @_;
                   4624:     my %returnhash;
                   4625:     if ($cdom && $cnum) {
                   4626:         my $chome = &homeserver($cnum,$cdom);
                   4627:         if ($chome ne 'no_host') {
                   4628:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4629:             &extract_lastaccess(\%returnhash,$rep);
                   4630:         }
                   4631:     } else {
                   4632:         if (!$cdom) { $cdom=''; }
                   4633:         my %libserv = &all_library();
                   4634:         foreach my $tryserver (keys(%libserv)) {
                   4635:             if (ref($hostidref) eq 'ARRAY') {
                   4636:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4637:             } 
                   4638:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4639:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4640:                 &extract_lastaccess(\%returnhash,$rep);
                   4641:             }
                   4642:         }
                   4643:     }
                   4644:     return %returnhash;
                   4645: }
                   4646: 
                   4647: sub extract_lastaccess {
                   4648:     my ($returnhash,$rep) = @_;
                   4649:     if (ref($returnhash) eq 'HASH') {
                   4650:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4651:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4652:                  $rep eq '') {
                   4653:             my @pairs=split(/\&/,$rep);
                   4654:             foreach my $item (@pairs) {
                   4655:                 my ($key,$value)=split(/\=/,$item,2);
                   4656:                 $key = &unescape($key);
                   4657:                 next if ($key =~ /^error: 2 /);
                   4658:                 $returnhash->{$key} = &thaw_unescape($value);
                   4659:             }
                   4660:         }
                   4661:     }
                   4662:     return;
                   4663: }
                   4664: 
1.658     raeburn  4665: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4666: 
                   4667: sub dcmailput {
1.685     raeburn  4668:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4669:     my $status = &Apache::lonnet::critical(
1.740     www      4670:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4671:        &escape($message),$server);
1.662     raeburn  4672:     return $status;
                   4673: }
                   4674: 
1.658     raeburn  4675: sub dcmaildump {
                   4676:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4677:     my %returnhash=();
1.846     albertel 4678: 
                   4679:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4680:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4681:                                                          &escape($enddate).':';
                   4682: 	my @esc_senders=map { &escape($_)} @$senders;
                   4683: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4684: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4685:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4686:             if (($key) && ($value)) {
                   4687:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4688:             }
                   4689:         }
                   4690:     }
                   4691:     return %returnhash;
                   4692: }
1.662     raeburn  4693: # ---------------------------------------------------------- Domain roles
                   4694: 
                   4695: sub get_domain_roles {
                   4696:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4697:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4698:         $startdate = '.';
                   4699:     }
1.1018    raeburn  4700:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4701:         $enddate = '.';
                   4702:     }
1.922     raeburn  4703:     my $rolelist;
                   4704:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  4705:         $rolelist = join('&',@{$roles});
1.922     raeburn  4706:     }
1.662     raeburn  4707:     my %personnel = ();
1.841     albertel 4708: 
                   4709:     my %servers = &get_servers($dom,'library');
                   4710:     foreach my $tryserver (keys(%servers)) {
                   4711: 	%{$personnel{$tryserver}}=();
                   4712: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4713: 					    &escape($startdate).':'.
                   4714: 					    &escape($enddate).':'.
                   4715: 					    &escape($rolelist), $tryserver))) {
                   4716: 	    my ($key,$value) = split(/\=/,$line,2);
                   4717: 	    if (($key) && ($value)) {
                   4718: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4719: 	    }
                   4720: 	}
1.662     raeburn  4721:     }
                   4722:     return %personnel;
                   4723: }
1.658     raeburn  4724: 
1.1057    www      4725: # ----------------------------------------------------------- Interval timing 
1.149     www      4726: 
1.1153    www      4727: {
                   4728: # Caches needed for speedup of navmaps
                   4729: # We don't want to cache this for very long at all (5 seconds at most)
                   4730: # 
                   4731: # The user for whom we cache
                   4732: my $cachedkey='';
                   4733: # The cached times for this user
                   4734: my %cachedtimes=();
                   4735: # When this was last done
1.1282    raeburn  4736: my $cachedtime='';
1.1153    www      4737: 
                   4738: sub load_all_first_access {
1.1308    raeburn  4739:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      4740:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  4741:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   4742:         (!$ignorecache)) {
1.1154    raeburn  4743:         return;
                   4744:     }
                   4745:     $cachedtime=time;
                   4746:     $cachedkey=$uname.':'.$udom;
                   4747:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4748: }
                   4749: 
1.504     albertel 4750: sub get_first_access {
1.1308    raeburn  4751:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 4752:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4753:     if ($argsymb) { $symb=$argsymb; }
                   4754:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4755:     if ($argmap) { $map = $argmap; }
1.926     albertel 4756:     if ($type eq 'course') {
                   4757: 	$res='course';
                   4758:     } elsif ($type eq 'map') {
1.588     albertel 4759: 	$res=&symbread($map);
                   4760:     } else {
                   4761: 	$res=$symb;
                   4762:     }
1.1308    raeburn  4763:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      4764:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4765: }
                   4766: 
                   4767: sub set_first_access {
1.1162    raeburn  4768:     my ($type,$interval)=@_;
1.790     albertel 4769:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4770:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4771:     if ($type eq 'course') {
                   4772: 	$res='course';
                   4773:     } elsif ($type eq 'map') {
1.588     albertel 4774: 	$res=&symbread($map);
                   4775:     } else {
                   4776: 	$res=$symb;
                   4777:     }
1.1153    www      4778:     $cachedkey='';
1.1162    raeburn  4779:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4780:     if (!$firstaccess) {
1.1162    raeburn  4781:         my $start = time;
                   4782: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4783:                           $udom,$uname);
                   4784:         if ($putres eq 'ok') {
                   4785:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4786:                  $udom,$uname); 
                   4787:             &appenv(
                   4788:                      {
                   4789:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4790:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4791:                      }
                   4792:                   );
                   4793:         }
                   4794:         return $putres;
1.505     albertel 4795:     }
                   4796:     return 'already_set';
1.504     albertel 4797: }
1.1153    www      4798: }
1.1282    raeburn  4799: 
1.110     www      4800: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4801: 
                   4802: sub expirespread {
                   4803:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4804:     my $cid=$env{'request.course.id'}; 
1.110     www      4805:     if ($cid) {
                   4806:        my $now=time;
                   4807:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4808:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4809:                             $env{'course.'.$cid.'.num'}.
1.110     www      4810: 	        	    ':nohist_expirationdates:'.
                   4811:                             &escape($key).'='.$now,
1.620     albertel 4812:                             $env{'course.'.$cid.'.home'})
1.110     www      4813:     }
                   4814:     return 'ok';
1.14      www      4815: }
                   4816: 
1.109     www      4817: # ----------------------------------------------------- Devalidate Spreadsheets
                   4818: 
                   4819: sub devalidate {
1.325     www      4820:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4821:     my $cid=$env{'request.course.id'}; 
1.109     www      4822:     if ($cid) {
1.391     matthew  4823:         # delete the stored spreadsheets for
                   4824:         # - the student level sheet of this user in course's homespace
                   4825:         # - the assessment level sheet for this resource 
                   4826:         #   for this user in user's homespace
1.553     albertel 4827: 	# - current conditional state info
1.325     www      4828: 	my $key=$uname.':'.$udom.':';
1.109     www      4829:         my $status=
1.299     matthew  4830: 	    &del('nohist_calculatedsheets',
1.391     matthew  4831: 		 [$key.'studentcalc:'],
1.620     albertel 4832: 		 $env{'course.'.$cid.'.domain'},
                   4833: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4834: 		.' '.
                   4835: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4836: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4837:         unless ($status eq 'ok ok') {
                   4838:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4839:                     $uname.' at '.$udom.' for '.
1.109     www      4840: 		    $symb.': '.$status);
1.133     albertel 4841:         }
1.553     albertel 4842: 	&delenv('user.state.'.$cid);
1.109     www      4843:     }
                   4844: }
                   4845: 
1.265     albertel 4846: sub get_scalar {
                   4847:     my ($string,$end) = @_;
                   4848:     my $value;
                   4849:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4850: 	$value = $1;
                   4851:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4852: 	$value = $1;
                   4853:     }
                   4854:     return &unescape($value);
                   4855: }
                   4856: 
                   4857: sub array2str {
                   4858:   my (@array) = @_;
                   4859:   my $result=&arrayref2str(\@array);
                   4860:   $result=~s/^__ARRAY_REF__//;
                   4861:   $result=~s/__END_ARRAY_REF__$//;
                   4862:   return $result;
                   4863: }
                   4864: 
1.204     albertel 4865: sub arrayref2str {
                   4866:   my ($arrayref) = @_;
1.265     albertel 4867:   my $result='__ARRAY_REF__';
1.204     albertel 4868:   foreach my $elem (@$arrayref) {
1.265     albertel 4869:     if(ref($elem) eq 'ARRAY') {
                   4870:       $result.=&arrayref2str($elem).'&';
                   4871:     } elsif(ref($elem) eq 'HASH') {
                   4872:       $result.=&hashref2str($elem).'&';
                   4873:     } elsif(ref($elem)) {
                   4874:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4875:     } else {
                   4876:       $result.=&escape($elem).'&';
                   4877:     }
                   4878:   }
                   4879:   $result=~s/\&$//;
1.265     albertel 4880:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4881:   return $result;
                   4882: }
                   4883: 
1.168     albertel 4884: sub hash2str {
1.204     albertel 4885:   my (%hash) = @_;
                   4886:   my $result=&hashref2str(\%hash);
1.265     albertel 4887:   $result=~s/^__HASH_REF__//;
                   4888:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4889:   return $result;
                   4890: }
                   4891: 
                   4892: sub hashref2str {
                   4893:   my ($hashref)=@_;
1.265     albertel 4894:   my $result='__HASH_REF__';
1.800     albertel 4895:   foreach my $key (sort(keys(%$hashref))) {
                   4896:     if (ref($key) eq 'ARRAY') {
                   4897:       $result.=&arrayref2str($key).'=';
                   4898:     } elsif (ref($key) eq 'HASH') {
                   4899:       $result.=&hashref2str($key).'=';
                   4900:     } elsif (ref($key)) {
1.265     albertel 4901:       $result.='=';
1.800     albertel 4902:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4903:     } else {
1.1132    raeburn  4904: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4905:     }
                   4906: 
1.800     albertel 4907:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4908:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4909:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4910:       $result.=&hashref2str($hashref->{$key}).'&';
                   4911:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4912:        $result.='&';
1.800     albertel 4913:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4914:     } else {
1.800     albertel 4915:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4916:     }
                   4917:   }
1.168     albertel 4918:   $result=~s/\&$//;
1.265     albertel 4919:   $result .= '__END_HASH_REF__';
1.168     albertel 4920:   return $result;
                   4921: }
                   4922: 
                   4923: sub str2hash {
1.265     albertel 4924:     my ($string)=@_;
                   4925:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4926:     return %$hash;
                   4927: }
                   4928: 
                   4929: sub str2hashref {
1.168     albertel 4930:   my ($string) = @_;
1.265     albertel 4931: 
                   4932:   my %hash;
                   4933: 
                   4934:   if($string !~ /^__HASH_REF__/) {
                   4935:       if (! ($string eq '' || !defined($string))) {
                   4936: 	  $hash{'error'}='Not hash reference';
                   4937:       }
                   4938:       return (\%hash, $string);
                   4939:   }
                   4940: 
                   4941:   $string =~ s/^__HASH_REF__//;
                   4942: 
                   4943:   while($string !~ /^__END_HASH_REF__/) {
                   4944:       #key
                   4945:       my $key='';
                   4946:       if($string =~ /^__HASH_REF__/) {
                   4947:           ($key, $string)=&str2hashref($string);
                   4948:           if(defined($key->{'error'})) {
                   4949:               $hash{'error'}='Bad data';
                   4950:               return (\%hash, $string);
                   4951:           }
                   4952:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4953:           ($key, $string)=&str2arrayref($string);
                   4954:           if($key->[0] eq 'Array reference error') {
                   4955:               $hash{'error'}='Bad data';
                   4956:               return (\%hash, $string);
                   4957:           }
                   4958:       } else {
                   4959:           $string =~ s/^(.*?)=//;
1.267     albertel 4960: 	  $key=&unescape($1);
1.265     albertel 4961:       }
                   4962:       $string =~ s/^=//;
                   4963: 
                   4964:       #value
                   4965:       my $value='';
                   4966:       if($string =~ /^__HASH_REF__/) {
                   4967:           ($value, $string)=&str2hashref($string);
                   4968:           if(defined($value->{'error'})) {
                   4969:               $hash{'error'}='Bad data';
                   4970:               return (\%hash, $string);
                   4971:           }
                   4972:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4973:           ($value, $string)=&str2arrayref($string);
                   4974:           if($value->[0] eq 'Array reference error') {
                   4975:               $hash{'error'}='Bad data';
                   4976:               return (\%hash, $string);
                   4977:           }
                   4978:       } else {
                   4979: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4980:       }
                   4981:       $string =~ s/^&//;
                   4982: 
                   4983:       $hash{$key}=$value;
1.204     albertel 4984:   }
1.265     albertel 4985: 
                   4986:   $string =~ s/^__END_HASH_REF__//;
                   4987: 
                   4988:   return (\%hash, $string);
1.204     albertel 4989: }
                   4990: 
                   4991: sub str2array {
1.265     albertel 4992:     my ($string)=@_;
                   4993:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4994:     return @$array;
                   4995: }
                   4996: 
                   4997: sub str2arrayref {
1.204     albertel 4998:   my ($string) = @_;
1.265     albertel 4999:   my @array;
                   5000: 
                   5001:   if($string !~ /^__ARRAY_REF__/) {
                   5002:       if (! ($string eq '' || !defined($string))) {
                   5003: 	  $array[0]='Array reference error';
                   5004:       }
                   5005:       return (\@array, $string);
                   5006:   }
                   5007: 
                   5008:   $string =~ s/^__ARRAY_REF__//;
                   5009: 
                   5010:   while($string !~ /^__END_ARRAY_REF__/) {
                   5011:       my $value='';
                   5012:       if($string =~ /^__HASH_REF__/) {
                   5013:           ($value, $string)=&str2hashref($string);
                   5014:           if(defined($value->{'error'})) {
                   5015:               $array[0] ='Array reference error';
                   5016:               return (\@array, $string);
                   5017:           }
                   5018:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5019:           ($value, $string)=&str2arrayref($string);
                   5020:           if($value->[0] eq 'Array reference error') {
                   5021:               $array[0] ='Array reference error';
                   5022:               return (\@array, $string);
                   5023:           }
                   5024:       } else {
                   5025: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5026:       }
                   5027:       $string =~ s/^&//;
                   5028: 
                   5029:       push(@array, $value);
1.191     harris41 5030:   }
1.265     albertel 5031: 
                   5032:   $string =~ s/^__END_ARRAY_REF__//;
                   5033: 
                   5034:   return (\@array, $string);
1.168     albertel 5035: }
                   5036: 
1.167     albertel 5037: # -------------------------------------------------------------------Temp Store
                   5038: 
1.168     albertel 5039: sub tmpreset {
                   5040:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5041:   if (!$symb) {
                   5042:     $symb=&symbread();
1.620     albertel 5043:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5044:   }
                   5045:   $symb=escape($symb);
                   5046: 
1.620     albertel 5047:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5048:   $namespace=~s/\//\_/g;
                   5049:   $namespace=~s/\W//g;
                   5050: 
1.620     albertel 5051:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5052:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5053:   if ($domain eq 'public' && $stuname eq 'public') {
                   5054:       $stuname=$ENV{'REMOTE_ADDR'};
                   5055:   }
1.1117    foxr     5056:   my $path=LONCAPA::tempdir();
1.168     albertel 5057:   my %hash;
                   5058:   if (tie(%hash,'GDBM_File',
                   5059: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5060: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5061:     foreach my $key (keys(%hash)) {
1.180     albertel 5062:       if ($key=~ /:$symb/) {
1.168     albertel 5063: 	delete($hash{$key});
                   5064:       }
                   5065:     }
                   5066:   }
                   5067: }
                   5068: 
1.167     albertel 5069: sub tmpstore {
1.168     albertel 5070:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5071: 
                   5072:   if (!$symb) {
                   5073:     $symb=&symbread();
1.620     albertel 5074:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5075:   }
                   5076:   $symb=escape($symb);
                   5077: 
                   5078:   if (!$namespace) {
                   5079:     # I don't think we would ever want to store this for a course.
                   5080:     # it seems this will only be used if we don't have a course.
1.620     albertel 5081:     #$namespace=$env{'request.course.id'};
1.168     albertel 5082:     #if (!$namespace) {
1.620     albertel 5083:       $namespace=$env{'request.state'};
1.168     albertel 5084:     #}
                   5085:   }
                   5086:   $namespace=~s/\//\_/g;
                   5087:   $namespace=~s/\W//g;
1.620     albertel 5088:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5089:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5090:   if ($domain eq 'public' && $stuname eq 'public') {
                   5091:       $stuname=$ENV{'REMOTE_ADDR'};
                   5092:   }
1.168     albertel 5093:   my $now=time;
                   5094:   my %hash;
1.1117    foxr     5095:   my $path=LONCAPA::tempdir();
1.168     albertel 5096:   if (tie(%hash,'GDBM_File',
                   5097: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5098: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5099:     $hash{"version:$symb"}++;
                   5100:     my $version=$hash{"version:$symb"};
                   5101:     my $allkeys=''; 
                   5102:     foreach my $key (keys(%$storehash)) {
                   5103:       $allkeys.=$key.':';
1.591     albertel 5104:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5105:     }
                   5106:     $hash{"$version:$symb:timestamp"}=$now;
                   5107:     $allkeys.='timestamp';
                   5108:     $hash{"$version:keys:$symb"}=$allkeys;
                   5109:     if (untie(%hash)) {
                   5110:       return 'ok';
                   5111:     } else {
                   5112:       return "error:$!";
                   5113:     }
                   5114:   } else {
                   5115:     return "error:$!";
                   5116:   }
                   5117: }
1.167     albertel 5118: 
1.168     albertel 5119: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5120: 
1.168     albertel 5121: sub tmprestore {
                   5122:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5123: 
1.168     albertel 5124:   if (!$symb) {
                   5125:     $symb=&symbread();
1.620     albertel 5126:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5127:   }
                   5128:   $symb=escape($symb);
                   5129: 
1.620     albertel 5130:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5131: 
1.620     albertel 5132:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5133:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5134:   if ($domain eq 'public' && $stuname eq 'public') {
                   5135:       $stuname=$ENV{'REMOTE_ADDR'};
                   5136:   }
1.168     albertel 5137:   my %returnhash;
                   5138:   $namespace=~s/\//\_/g;
                   5139:   $namespace=~s/\W//g;
                   5140:   my %hash;
1.1117    foxr     5141:   my $path=LONCAPA::tempdir();
1.168     albertel 5142:   if (tie(%hash,'GDBM_File',
                   5143: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5144: 	  &GDBM_READER(),0640)) {
1.168     albertel 5145:     my $version=$hash{"version:$symb"};
                   5146:     $returnhash{'version'}=$version;
                   5147:     my $scope;
                   5148:     for ($scope=1;$scope<=$version;$scope++) {
                   5149:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5150:       my @keys=split(/:/,$vkeys);
                   5151:       my $key;
                   5152:       $returnhash{"$scope:keys"}=$vkeys;
                   5153:       foreach $key (@keys) {
1.591     albertel 5154: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5155: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5156:       }
                   5157:     }
1.168     albertel 5158:     if (!(untie(%hash))) {
                   5159:       return "error:$!";
                   5160:     }
                   5161:   } else {
                   5162:     return "error:$!";
                   5163:   }
                   5164:   return %returnhash;
1.167     albertel 5165: }
                   5166: 
1.9       www      5167: # ----------------------------------------------------------------------- Store
                   5168: 
                   5169: sub store {
1.1269    raeburn  5170:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5171:     my $home='';
                   5172: 
1.168     albertel 5173:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5174: 
1.213     www      5175:     $symb=&symbclean($symb);
1.122     albertel 5176:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5177: 
1.620     albertel 5178:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5179:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5180: 
                   5181:     &devalidate($symb,$stuname,$domain);
1.109     www      5182: 
                   5183:     $symb=escape($symb);
1.187     www      5184:     if (!$namespace) { 
1.620     albertel 5185:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5186:           return ''; 
                   5187:        } 
                   5188:     }
1.620     albertel 5189:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5190: 
                   5191:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5192:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5193: 
1.12      www      5194:     my $namevalue='';
1.800     albertel 5195:     foreach my $key (keys(%$storehash)) {
                   5196:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5197:     }
1.12      www      5198:     $namevalue=~s/\&$//;
1.187     www      5199:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  5200:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5201: }
                   5202: 
1.47      www      5203: # -------------------------------------------------------------- Critical Store
                   5204: 
                   5205: sub cstore {
1.1269    raeburn  5206:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5207:     my $home='';
                   5208: 
1.168     albertel 5209:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5210: 
1.213     www      5211:     $symb=&symbclean($symb);
1.122     albertel 5212:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5213: 
1.620     albertel 5214:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5215:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5216: 
                   5217:     &devalidate($symb,$stuname,$domain);
1.109     www      5218: 
                   5219:     $symb=escape($symb);
1.187     www      5220:     if (!$namespace) { 
1.620     albertel 5221:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5222:           return ''; 
                   5223:        } 
                   5224:     }
1.620     albertel 5225:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5226: 
                   5227:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5228:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5229: 
1.47      www      5230:     my $namevalue='';
1.800     albertel 5231:     foreach my $key (keys(%$storehash)) {
                   5232:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5233:     }
1.47      www      5234:     $namevalue=~s/\&$//;
1.187     www      5235:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5236:     return critical
1.1269    raeburn  5237:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5238: }
                   5239: 
1.9       www      5240: # --------------------------------------------------------------------- Restore
                   5241: 
                   5242: sub restore {
1.124     www      5243:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5244:     my $home='';
                   5245: 
1.168     albertel 5246:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5247: 
1.122     albertel 5248:     if (!$symb) {
1.1224    raeburn  5249:         return if ($namespace eq 'courserequests');
                   5250:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5251:     } else {
1.1224    raeburn  5252:         unless ($namespace eq 'courserequests') {
                   5253:             $symb=&escape(&symbclean($symb));
                   5254:         }
1.122     albertel 5255:     }
1.188     www      5256:     if (!$namespace) { 
1.620     albertel 5257:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5258:           return ''; 
                   5259:        } 
                   5260:     }
1.620     albertel 5261:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5262:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5263:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5264:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5265: 
1.12      www      5266:     my %returnhash=();
1.800     albertel 5267:     foreach my $line (split(/\&/,$answer)) {
                   5268: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5269:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5270:     }
1.75      www      5271:     my $version;
                   5272:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5273:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5274:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5275:        }
1.75      www      5276:     }
1.13      www      5277:     return %returnhash;
1.34      www      5278: }
                   5279: 
                   5280: # ---------------------------------------------------------- Course Description
1.1118    foxr     5281: #
                   5282: #  
1.34      www      5283: 
                   5284: sub coursedescription {
1.731     albertel 5285:     my ($courseid,$args)=@_;
1.34      www      5286:     $courseid=~s/^\///;
1.49      www      5287:     $courseid=~s/\_/\//g;
1.34      www      5288:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5289:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5290:     my $normalid=$cdomain.'_'.$cnum;
                   5291:     # need to always cache even if we get errors otherwise we keep 
                   5292:     # trying and trying and trying to get the course description.
                   5293:     my %envhash=();
                   5294:     my %returnhash=();
1.731     albertel 5295:     
                   5296:     my $expiretime=600;
                   5297:     if ($env{'request.course.id'} eq $normalid) {
                   5298: 	$expiretime=120;
                   5299:     }
                   5300: 
                   5301:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5302:     if (!$args->{'freshen_cache'}
                   5303: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5304: 	foreach my $key (keys(%env)) {
                   5305: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5306: 	    my ($setting) = $1;
                   5307: 	    $returnhash{$setting} = $env{$key};
                   5308: 	}
                   5309: 	return %returnhash;
                   5310:     }
                   5311: 
1.1118    foxr     5312:     # get the data again
                   5313: 
1.731     albertel 5314:     if (!$args->{'one_time'}) {
                   5315: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5316:     }
1.811     albertel 5317: 
1.34      www      5318:     if ($chome ne 'no_host') {
1.302     albertel 5319:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5320:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5321: 	   my $username = $env{'user.name'}; # Defult username
                   5322: 	   if(defined $args->{'user'}) {
                   5323: 	       $username = $args->{'user'};
                   5324: 	   }
1.129     albertel 5325:            $returnhash{'home'}= $chome;
                   5326: 	   $returnhash{'domain'} = $cdomain;
                   5327: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5328:            if (!defined($returnhash{'type'})) {
                   5329:                $returnhash{'type'} = 'Course';
                   5330:            }
1.130     albertel 5331:            while (my ($name,$value) = each %returnhash) {
1.53      www      5332:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5333:            }
1.270     www      5334:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5335:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5336: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5337:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5338:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5339:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5340:        }
                   5341:     }
1.731     albertel 5342:     if (!$args->{'one_time'}) {
1.949     raeburn  5343: 	&appenv(\%envhash);
1.731     albertel 5344:     }
1.302     albertel 5345:     return %returnhash;
1.461     www      5346: }
                   5347: 
1.1080    raeburn  5348: sub update_released_required {
                   5349:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5350:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5351:         $cid = $env{'request.course.id'};
                   5352:         $cdom = $env{'course.'.$cid.'.domain'};
                   5353:         $cnum = $env{'course.'.$cid.'.num'};
                   5354:         $chome = $env{'course.'.$cid.'.home'};
                   5355:     }
                   5356:     if ($needsrelease) {
                   5357:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5358:         my $needsupdate;
                   5359:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5360:             $needsupdate = 1;
                   5361:         } else {
                   5362:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5363:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5364:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5365:                 $needsupdate = 1;
                   5366:             }
                   5367:         }
                   5368:         if ($needsupdate) {
                   5369:             my %needshash = (
                   5370:                              'internal.releaserequired' => $needsrelease,
                   5371:                             );
                   5372:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5373:             if ($putresult eq 'ok') {
                   5374:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5375:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5376:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5377:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5378:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5379:                 }
                   5380:             }
                   5381:         }
                   5382:     }
                   5383:     return;
                   5384: }
                   5385: 
1.461     www      5386: # -------------------------------------------------See if a user is privileged
                   5387: 
                   5388: sub privileged {
1.1219    raeburn  5389:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5390:     my $now = time;
1.1219    raeburn  5391:     my $roles;
                   5392:     if (ref($possroles) eq 'ARRAY') {
                   5393:         $roles = $possroles; 
                   5394:     } else {
                   5395:         $roles = ['dc','su'];
                   5396:     }
                   5397:     if (ref($possdomains) eq 'ARRAY') {
                   5398:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5399:         foreach my $dom (@{$possdomains}) {
                   5400:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5401:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5402:                 foreach my $role (@{$roles}) {
                   5403:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5404:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5405:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5406:                             return 1 unless (($end && $end < $now) ||
                   5407:                                              ($start && $start > $now));
                   5408:                         }
                   5409:                     }
                   5410:                 }
                   5411:             }
                   5412:         }
                   5413:     } else {
                   5414:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5415:         my $now = time;
1.1170    droeschl 5416: 
1.1275    musolffc 5417:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5418:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  5419:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 5420:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  5421:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5422:             }
1.1219    raeburn  5423:         }
                   5424:     }
                   5425:     return 0;
                   5426: }
1.1170    droeschl 5427: 
1.1219    raeburn  5428: sub privileged_by_domain {
                   5429:     my ($domains,$roles) = @_;
                   5430:     my %privileged = ();
                   5431:     my $cachetime = 60*60*24;
                   5432:     my $now = time;
                   5433:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5434:         return %privileged;
                   5435:     }
                   5436:     foreach my $dom (@{$domains}) {
                   5437:         next if (ref($privileged{$dom}) eq 'HASH');
                   5438:         my $needroles;
                   5439:         foreach my $role (@{$roles}) {
                   5440:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5441:             if (defined($cached)) {
                   5442:                 if (ref($result) eq 'HASH') {
                   5443:                     $privileged{$dom}{$role} = $result;
                   5444:                 }
                   5445:             } else {
                   5446:                 $needroles = 1;
                   5447:             }
                   5448:         }
                   5449:         if ($needroles) {
                   5450:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5451:             $privileged{$dom} = {};
                   5452:             foreach my $server (keys(%dompersonnel)) {
                   5453:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5454:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5455:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5456:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5457:                         next if ($end && $end < $now);
                   5458:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   5459:                             $dompersonnel{$server}{$item};
                   5460:                     }
                   5461:                 }
                   5462:             }
                   5463:             if (ref($privileged{$dom}) eq 'HASH') {
                   5464:                 foreach my $role (@{$roles}) {
                   5465:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5466:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5467:                     } else {
                   5468:                         my %hash = ();
                   5469:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5470:                     }
                   5471:                 }
                   5472:             }
                   5473:         }
                   5474:     }
                   5475:     return %privileged;
1.9       www      5476: }
1.1       albertel 5477: 
1.103     harris41 5478: # -------------------------------------------------------- Get user privileges
1.11      www      5479: 
                   5480: sub rolesinit {
1.1169    droeschl 5481:     my ($domain, $username) = @_;
                   5482:     my %userroles = ('user.login.time' => time);
                   5483:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5484: 
                   5485:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5486:     # also, blocking can be triggered by an activating timer
                   5487:     # it's saved in the user's %env.
                   5488:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5489:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5490:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5491:         %timerintchk, %timerintenv);
                   5492: 
1.1162    raeburn  5493:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5494:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5495:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5496:     }
1.1169    droeschl 5497: 
1.1162    raeburn  5498:     foreach my $key (keys(%timerinterval)) {
                   5499:         my ($cid,$rest) = split(/\0/,$key);
                   5500:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5501:     }
1.1169    droeschl 5502: 
1.11      www      5503:     my %allroles=();
1.1162    raeburn  5504:     my %allgroups=();
1.11      www      5505: 
1.1274    raeburn  5506:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5507:         my $role = $rolesdump{$area};
                   5508:         $area =~ s/\_\w\w$//;
                   5509: 
                   5510:         my ($trole, $tend, $tstart, $group_privs);
                   5511: 
                   5512:         if ($role =~ /^cr/) {
                   5513:         # Custom role, defined by a user 
                   5514:         # e.g., user.role.cr/msu/smith/mynewrole
                   5515:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5516:                 $trole = $1;
                   5517:                 ($tend, $tstart) = split('_', $2);
                   5518:             } else {
                   5519:                 $trole = $role;
                   5520:             }
                   5521:         } elsif ($role =~ m|^gr/|) {
                   5522:         # Role of member in a group, defined within a course/community
                   5523:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5524:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5525:             next if $tstart eq '-1';
                   5526:             ($trole, $group_privs) = split(/\//, $trole);
                   5527:             $group_privs = &unescape($group_privs);
                   5528:         } else {
                   5529:         # Just a normal role, defined in roles.tab
                   5530:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5531:         }
                   5532: 
                   5533:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5534:                  $username);
                   5535:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5536: 
                   5537:         # role expired or not available yet?
                   5538:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5539:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5540: 
                   5541:         next if $area eq '' or $trole eq '';
                   5542: 
                   5543:         my $spec = "$trole.$area";
                   5544:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5545: 
                   5546:         if ($trole =~ /^cr\//) {
                   5547:         # Custom role, defined by a user
                   5548:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5549:         } elsif ($trole eq 'gr') {
                   5550:         # Role of a member in a group, defined within a course/community
                   5551:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5552:             next;
                   5553:         } else {
                   5554:         # Normal role, defined in roles.tab
                   5555:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5556:         }
                   5557: 
                   5558:         my $cid = $tdomain.'_'.$trest;
                   5559:         unless ($firstaccchk{$cid}) {
                   5560:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5561:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5562:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5563:                         $coursetimerstarts{$cid}{$item}; 
                   5564:                 }
                   5565:             }
                   5566:             $firstaccchk{$cid} = 1;
                   5567:         }
                   5568:         unless ($timerintchk{$cid}) {
                   5569:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5570:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5571:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5572:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5573:                 }
1.12      www      5574:             }
1.1169    droeschl 5575:             $timerintchk{$cid} = 1;
1.191     harris41 5576:         }
1.11      www      5577:     }
1.1169    droeschl 5578: 
                   5579:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5580:         \%allroles, \%allgroups);
                   5581:     $env{'user.adv'} = $userroles{'user.adv'};
                   5582: 
1.1162    raeburn  5583:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5584: }
                   5585: 
1.567     raeburn  5586: sub set_arearole {
1.1215    raeburn  5587:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5588:     unless ($nolog) {
1.567     raeburn  5589: # log the associated role with the area
1.1215    raeburn  5590:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5591:     }
1.743     albertel 5592:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5593: }
                   5594: 
                   5595: sub custom_roleprivs {
                   5596:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5597:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  5598:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5599:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5600:         my ($rdummy,$roledef)=
                   5601:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5602:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5603:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5604:             if (defined($syspriv)) {
1.1043    raeburn  5605:                 if ($trest =~ /^$match_community$/) {
                   5606:                     $syspriv =~ s/bre\&S//; 
                   5607:                 }
1.567     raeburn  5608:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5609:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5610:             }
                   5611:             if ($tdomain ne '') {
                   5612:                 if (defined($dompriv)) {
                   5613:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5614:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5615:                 }
                   5616:                 if (($trest ne '') && (defined($coursepriv))) {
                   5617:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5618:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5619:                 }
                   5620:             }
                   5621:         }
                   5622:     }
                   5623: }
                   5624: 
1.678     raeburn  5625: sub group_roleprivs {
                   5626:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5627:     my $access = 1;
                   5628:     my $now = time;
                   5629:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5630:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5631:     if ($access) {
1.811     albertel 5632:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5633:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5634:     }
                   5635: }
1.567     raeburn  5636: 
                   5637: sub standard_roleprivs {
                   5638:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5639:     if (defined($pr{$trole.':s'})) {
                   5640:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5641:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5642:     }
                   5643:     if ($tdomain ne '') {
                   5644:         if (defined($pr{$trole.':d'})) {
                   5645:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5646:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5647:         }
                   5648:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5649:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5650:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5651:         }
                   5652:     }
                   5653: }
                   5654: 
                   5655: sub set_userprivs {
1.1064    raeburn  5656:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5657:     my $author=0;
                   5658:     my $adv=0;
1.678     raeburn  5659:     my %grouproles = ();
                   5660:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5661:         my @groupkeys; 
1.1000    raeburn  5662:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5663:             push(@groupkeys,$role);
                   5664:         }
                   5665:         if (ref($groups_roles) eq 'HASH') {
                   5666:             foreach my $key (keys(%{$groups_roles})) {
                   5667:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5668:                     push(@groupkeys,$key);
                   5669:                 }
                   5670:             }
                   5671:         }
                   5672:         if (@groupkeys > 0) {
                   5673:             foreach my $role (@groupkeys) {
                   5674:                 my ($trole,$area,$sec,$extendedarea);
                   5675:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5676:                     $trole = $1;
                   5677:                     $area = $2;
                   5678:                     $sec = $3;
                   5679:                     $extendedarea = $area.$sec;
                   5680:                     if (exists($$allgroups{$area})) {
                   5681:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5682:                             my $spec = $trole.'.'.$extendedarea;
                   5683:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5684:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5685:                         }
1.678     raeburn  5686:                     }
                   5687:                 }
                   5688:             }
                   5689:         }
                   5690:     }
1.800     albertel 5691:     foreach my $group (keys(%grouproles)) {
                   5692:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5693:     }
1.800     albertel 5694:     foreach my $role (keys(%{$allroles})) {
                   5695:         my %thesepriv;
1.941     raeburn  5696:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5697:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5698:             if ($item ne '') {
                   5699:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5700:                 if ($restrictions eq '') {
                   5701:                     $thesepriv{$privilege}='F';
                   5702:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5703:                     $thesepriv{$privilege}.=$restrictions;
                   5704:                 }
                   5705:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5706:             }
                   5707:         }
                   5708:         my $thesestr='';
1.1104    raeburn  5709:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5710: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5711: 	}
                   5712:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5713:     }
                   5714:     return ($author,$adv);
                   5715: }
                   5716: 
1.994     raeburn  5717: sub role_status {
1.1104    raeburn  5718:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5719:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  5720:         my ($one,$two) = split(m{\./},$rolekey,2);
                   5721:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  5722:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  5723:             $$where = '/'.$two;
1.994     raeburn  5724:             $$trolecode=$$role.'.'.$$where;
                   5725:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5726:             $$tstatus='is';
1.1104    raeburn  5727:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5728:                 $$tstatus='future';
1.1034    raeburn  5729:                 if ($$tstart<$now) {
                   5730:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5731:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5732:                             my (%allroles,%allgroups,$group_privs,
                   5733:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5734:                             my %userroles = (
                   5735:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5736:                             );
1.1064    raeburn  5737:                             @rolecodes = ('cm'); 
1.1002    raeburn  5738:                             my $spec=$$role.'.'.$$where;
                   5739:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5740:                             if ($$role =~ /^cr\//) {
                   5741:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5742:                                 push(@rolecodes,'cr');
1.1002    raeburn  5743:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5744:                                 push(@rolecodes,$$role);
1.1002    raeburn  5745:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5746:                                                     $env{'user.name'});
1.1064    raeburn  5747:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5748:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5749:                                 $group_privs = &unescape($group_privs);
                   5750:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5751:                                 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  5752:                                 &get_groups_roles($tdomain,$trest,
                   5753:                                                   \%course_roles,\@rolecodes,
                   5754:                                                   \%groups_roles);
1.1002    raeburn  5755:                             } else {
1.1064    raeburn  5756:                                 push(@rolecodes,$$role);
1.1002    raeburn  5757:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5758:                             }
1.1064    raeburn  5759:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5760:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5761:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5762:                         }
                   5763:                     }
1.1034    raeburn  5764:                     $$tstatus = 'is';
1.1002    raeburn  5765:                 }
1.994     raeburn  5766:             }
                   5767:             if ($$tend) {
1.1104    raeburn  5768:                 if ($$tend<$update) {
1.994     raeburn  5769:                     $$tstatus='expired';
                   5770:                 } elsif ($$tend<$now) {
                   5771:                     $$tstatus='will_not';
                   5772:                 }
                   5773:             }
                   5774:         }
                   5775:     }
                   5776: }
                   5777: 
1.1104    raeburn  5778: sub get_groups_roles {
                   5779:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5780:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5781:                   (ref($rolecodes) eq 'ARRAY') && 
                   5782:                   (ref($groups_roles) eq 'HASH')); 
                   5783:     if (keys(%{$cdom_courseroles}) > 0) {
                   5784:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5785:         if ($cdom ne '' && $cnum ne '') {
                   5786:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5787:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5788:                     my $crsrole = $1;
                   5789:                     my $crssec = $2;
                   5790:                     if ($crsrole =~ /^cr/) {
                   5791:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5792:                             push(@{$rolecodes},'cr');
                   5793:                         }
                   5794:                     } else {
                   5795:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5796:                             push(@{$rolecodes},$crsrole);
                   5797:                         }
                   5798:                     }
                   5799:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5800:                     if ($crssec ne '') {
                   5801:                         $rolekey .= "/$crssec";
                   5802:                     }
                   5803:                     $rolekey .= './';
                   5804:                     $groups_roles->{$rolekey} = $rolecodes;
                   5805:                 }
                   5806:             }
                   5807:         }
                   5808:     }
                   5809:     return;
                   5810: }
                   5811: 
                   5812: sub delete_env_groupprivs {
                   5813:     my ($where,$courseroles,$possroles) = @_;
                   5814:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5815:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5816:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5817:         %{$courseroles->{$udom}} =
                   5818:             &get_my_roles('','','userroles',['active'],
                   5819:                           $possroles,[$udom],1);
                   5820:     }
                   5821:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5822:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5823:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5824:             my $area = '/'.$cdom.'/'.$cnum;
                   5825:             my $privkey = "user.priv.$crsrole.$area";
                   5826:             if ($crssec ne '') {
                   5827:                 $privkey .= '/'.$crssec;
                   5828:             }
                   5829:             $privkey .= ".$area/$group";
                   5830:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5831:         }
                   5832:     }
                   5833:     return;
                   5834: }
                   5835: 
1.994     raeburn  5836: sub check_adhoc_privs {
1.1104    raeburn  5837:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5838:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185    raeburn  5839:     my $setprivs;
1.994     raeburn  5840:     if ($env{$cckey}) {
                   5841:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5842:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5843:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5844:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5845:             $setprivs = 1;
1.994     raeburn  5846:         }
                   5847:     } else {
1.1088    raeburn  5848:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5849:         $setprivs = 1;
1.994     raeburn  5850:     }
1.1185    raeburn  5851:     return $setprivs;
1.994     raeburn  5852: }
                   5853: 
                   5854: sub set_adhoc_privileges {
                   5855: # role can be cc or ca
1.1088    raeburn  5856:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5857:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5858:     my $spec = $role.'.'.$area;
                   5859:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  5860:                                   $env{'user.name'},1);
1.994     raeburn  5861:     my %ccrole = ();
                   5862:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5863:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5864:     &appenv(\%userroles,[$role,'cm']);
                   5865:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5866:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5867:         &appenv( {'request.role'        => $spec,
                   5868:                   'request.role.domain' => $dcdom,
                   5869:                   'request.course.sec'  => ''
                   5870:                  }
                   5871:                );
                   5872:         my $tadv=0;
                   5873:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5874:         &appenv({'request.role.adv'    => $tadv});
                   5875:     }
1.994     raeburn  5876: }
                   5877: 
1.12      www      5878: # --------------------------------------------------------------- get interface
                   5879: 
                   5880: sub get {
1.131     albertel 5881:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5882:    my $items='';
1.800     albertel 5883:    foreach my $item (@$storearr) {
                   5884:        $items.=&escape($item).'&';
1.191     harris41 5885:    }
1.12      www      5886:    $items=~s/\&$//;
1.620     albertel 5887:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5888:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5889:    my $uhome=&homeserver($uname,$udomain);
                   5890: 
1.133     albertel 5891:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5892:    my @pairs=split(/\&/,$rep);
1.273     albertel 5893:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5894:      return @pairs;
                   5895:    }
1.15      www      5896:    my %returnhash=();
1.42      www      5897:    my $i=0;
1.800     albertel 5898:    foreach my $item (@$storearr) {
                   5899:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5900:       $i++;
1.191     harris41 5901:    }
1.15      www      5902:    return %returnhash;
1.27      www      5903: }
                   5904: 
                   5905: # --------------------------------------------------------------- del interface
                   5906: 
                   5907: sub del {
1.133     albertel 5908:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5909:    my $items='';
1.800     albertel 5910:    foreach my $item (@$storearr) {
                   5911:        $items.=&escape($item).'&';
1.191     harris41 5912:    }
1.984     neumanie 5913: 
1.27      www      5914:    $items=~s/\&$//;
1.620     albertel 5915:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5916:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5917:    my $uhome=&homeserver($uname,$udomain);
                   5918:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5919: }
                   5920: 
                   5921: # -------------------------------------------------------------- dump interface
                   5922: 
1.1180    droeschl 5923: sub unserialize {
                   5924:     my ($rep, $escapedkeys) = @_;
                   5925: 
                   5926:     return {} if $rep =~ /^error/;
                   5927: 
                   5928:     my %returnhash=();
1.1252    raeburn  5929: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 5930: 	    my ($key, $value) = split(/=/, $item, 2);
                   5931: 	    $key = unescape($key) unless $escapedkeys;
                   5932: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  5933: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 5934: 	}
                   5935:     #return %returnhash;
                   5936:     return \%returnhash;
                   5937: }        
                   5938: 
                   5939: # see Lond::dump_with_regexp
                   5940: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5941: sub dump {
1.1180    droeschl 5942:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5943:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5944:     if (!$uname) { $uname=$env{'user.name'}; }
                   5945:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5946: 
1.1266    raeburn  5947:     if ($regexp) {
                   5948:         $regexp=&escape($regexp);
                   5949:     } else {
                   5950:         $regexp='.';
                   5951:     }
1.1180    droeschl 5952:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   5953:         # user is hosted on this machine
1.1266    raeburn  5954:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  5955:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 5956:         return %{unserialize($reply, $escapedkeys)};
                   5957:     }
1.1166    raeburn  5958:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5959:     my @pairs=split(/\&/,$rep);
                   5960:     my %returnhash=();
1.1098    foxr     5961:     if (!($rep =~ /^error/ )) {
                   5962: 	foreach my $item (@pairs) {
                   5963: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 5964:         $key = unescape($key) unless $escapedkeys;
                   5965:         #$key = &unescape($key);
1.1098    foxr     5966: 	    next if ($key =~ /^error: 2 /);
                   5967: 	    $returnhash{$key}=&thaw_unescape($value);
                   5968: 	}
1.755     albertel 5969:     }
                   5970:     return %returnhash;
1.407     www      5971: }
                   5972: 
1.1098    foxr     5973: 
1.717     albertel 5974: # --------------------------------------------------------- dumpstore interface
                   5975: 
                   5976: sub dumpstore {
                   5977:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 5978:    # same as dump but keys must be escaped. They may contain colon separated
                   5979:    # lists of values that may themself contain colons (e.g. symbs).
                   5980:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5981: }
                   5982: 
1.407     www      5983: # -------------------------------------------------------------- keys interface
                   5984: 
                   5985: sub getkeys {
                   5986:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5987:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5988:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5989:    my $uhome=&homeserver($uname,$udomain);
                   5990:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5991:    my @keyarray=();
1.800     albertel 5992:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5993:       next if ($key =~ /^error: 2 /);
1.800     albertel 5994:       push(@keyarray,&unescape($key));
1.407     www      5995:    }
                   5996:    return @keyarray;
1.318     matthew  5997: }
                   5998: 
1.319     matthew  5999: # --------------------------------------------------------------- currentdump
                   6000: sub currentdump {
1.328     matthew  6001:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6002:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6003:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6004:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6005:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 6006:    my $rep;
                   6007: 
                   6008:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6009:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   6010:                    $courseid)));
                   6011:    } else {
                   6012:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6013:    }
                   6014: 
1.318     matthew  6015:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6016:    #
1.318     matthew  6017:    my %returnhash=();
1.319     matthew  6018:    #
                   6019:    if ($rep eq "unknown_cmd") { 
                   6020:        # an old lond will not know currentdump
                   6021:        # Do a dump and make it look like a currentdump
1.822     albertel 6022:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6023:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6024:        my %hash = @tmp;
                   6025:        @tmp=();
1.424     matthew  6026:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6027:    } else {
                   6028:        my @pairs=split(/\&/,$rep);
1.800     albertel 6029:        foreach my $pair (@pairs) {
                   6030:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6031:            my ($symb,$param) = split(/:/,$key);
                   6032:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6033:                                                         &thaw_unescape($value);
1.319     matthew  6034:        }
1.191     harris41 6035:    }
1.12      www      6036:    return %returnhash;
1.424     matthew  6037: }
                   6038: 
                   6039: sub convert_dump_to_currentdump{
                   6040:     my %hash = %{shift()};
                   6041:     my %returnhash;
                   6042:     # Code ripped from lond, essentially.  The only difference
                   6043:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6044:     # we might run in to problems with parameter names =~ /^v\./
                   6045:     while (my ($key,$value) = each(%hash)) {
                   6046:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6047: 	$symb  = &unescape($symb);
                   6048: 	$param = &unescape($param);
1.424     matthew  6049:         next if ($v eq 'version' || $symb eq 'keys');
                   6050:         next if (exists($returnhash{$symb}) &&
                   6051:                  exists($returnhash{$symb}->{$param}) &&
                   6052:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6053:         $returnhash{$symb}->{$param}=$value;
                   6054:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6055:     }
                   6056:     #
                   6057:     # Remove all of the keys in the hashes which keep track of
                   6058:     # the version of the parameter.
                   6059:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6060:         # use a foreach because we are going to delete from the hash.
                   6061:         foreach my $key (keys(%$param_hash)) {
                   6062:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6063:         }
                   6064:     }
                   6065:     return \%returnhash;
1.12      www      6066: }
                   6067: 
1.627     albertel 6068: # ------------------------------------------------------ critical inc interface
                   6069: 
                   6070: sub cinc {
                   6071:     return &inc(@_,'critical');
                   6072: }
                   6073: 
1.449     matthew  6074: # --------------------------------------------------------------- inc interface
                   6075: 
                   6076: sub inc {
1.627     albertel 6077:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6078:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6079:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6080:     my $uhome=&homeserver($uname,$udomain);
                   6081:     my $items='';
                   6082:     if (! ref($store)) {
                   6083:         # got a single value, so use that instead
                   6084:         $items = &escape($store).'=&';
                   6085:     } elsif (ref($store) eq 'SCALAR') {
                   6086:         $items = &escape($$store).'=&';        
                   6087:     } elsif (ref($store) eq 'ARRAY') {
                   6088:         $items = join('=&',map {&escape($_);} @{$store});
                   6089:     } elsif (ref($store) eq 'HASH') {
                   6090:         while (my($key,$value) = each(%{$store})) {
                   6091:             $items.= &escape($key).'='.&escape($value).'&';
                   6092:         }
                   6093:     }
                   6094:     $items=~s/\&$//;
1.627     albertel 6095:     if ($critical) {
                   6096: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6097:     } else {
                   6098: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6099:     }
1.449     matthew  6100: }
                   6101: 
1.12      www      6102: # --------------------------------------------------------------- put interface
                   6103: 
                   6104: sub put {
1.134     albertel 6105:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6106:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6107:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6108:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6109:    my $items='';
1.800     albertel 6110:    foreach my $item (keys(%$storehash)) {
                   6111:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6112:    }
1.12      www      6113:    $items=~s/\&$//;
1.134     albertel 6114:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6115: }
                   6116: 
1.631     albertel 6117: # ------------------------------------------------------------ newput interface
                   6118: 
                   6119: sub newput {
                   6120:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6121:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6122:    if (!$uname) { $uname=$env{'user.name'}; }
                   6123:    my $uhome=&homeserver($uname,$udomain);
                   6124:    my $items='';
                   6125:    foreach my $key (keys(%$storehash)) {
                   6126:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6127:    }
                   6128:    $items=~s/\&$//;
                   6129:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6130: }
                   6131: 
                   6132: # ---------------------------------------------------------  putstore interface
                   6133: 
1.524     raeburn  6134: sub putstore {
1.1269    raeburn  6135:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6136:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6137:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6138:    my $uhome=&homeserver($uname,$udomain);
                   6139:    my $items='';
1.715     albertel 6140:    foreach my $key (keys(%$storehash)) {
                   6141:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6142:    }
1.715     albertel 6143:    $items=~s/\&$//;
1.716     albertel 6144:    my $esc_symb=&escape($symb);
                   6145:    my $esc_v=&escape($version);
1.715     albertel 6146:    my $reply =
1.716     albertel 6147:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6148: 	      $uhome);
1.1269    raeburn  6149:    if (($tolog) && ($reply eq 'ok')) {
                   6150:        my $namevalue='';
                   6151:        foreach my $key (keys(%{$storehash})) {
                   6152:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6153:        }
                   6154:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6155:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6156:                      '&version='.$esc_v.
                   6157:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6158:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6159:    }
1.715     albertel 6160:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6161:        # gfall back to way things use to be done
1.715     albertel 6162:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6163: 			    $uname);
1.524     raeburn  6164:    }
1.715     albertel 6165:    return $reply;
                   6166: }
                   6167: 
                   6168: sub old_putstore {
1.716     albertel 6169:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6170:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6171:     if (!$uname) { $uname=$env{'user.name'}; }
                   6172:     my $uhome=&homeserver($uname,$udomain);
                   6173:     my %newstorehash;
1.800     albertel 6174:     foreach my $item (keys(%$storehash)) {
                   6175: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6176: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6177:     }
                   6178:     my $items='';
                   6179:     my %allitems = ();
1.800     albertel 6180:     foreach my $item (keys(%newstorehash)) {
                   6181: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6182: 	    my $key = $1.':keys:'.$2;
                   6183: 	    $allitems{$key} .= $3.':';
                   6184: 	}
1.800     albertel 6185: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6186:     }
1.800     albertel 6187:     foreach my $item (keys(%allitems)) {
                   6188: 	$allitems{$item} =~ s/\:$//;
                   6189: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6190:     }
                   6191:     $items=~s/\&$//;
                   6192:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6193: }
                   6194: 
1.47      www      6195: # ------------------------------------------------------ critical put interface
                   6196: 
                   6197: sub cput {
1.134     albertel 6198:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6199:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6200:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6201:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6202:    my $items='';
1.800     albertel 6203:    foreach my $item (keys(%$storehash)) {
                   6204:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6205:    }
1.47      www      6206:    $items=~s/\&$//;
1.134     albertel 6207:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6208: }
                   6209: 
                   6210: # -------------------------------------------------------------- eget interface
                   6211: 
                   6212: sub eget {
1.133     albertel 6213:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6214:    my $items='';
1.800     albertel 6215:    foreach my $item (@$storearr) {
                   6216:        $items.=&escape($item).'&';
1.191     harris41 6217:    }
1.12      www      6218:    $items=~s/\&$//;
1.620     albertel 6219:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6220:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6221:    my $uhome=&homeserver($uname,$udomain);
                   6222:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6223:    my @pairs=split(/\&/,$rep);
                   6224:    my %returnhash=();
1.42      www      6225:    my $i=0;
1.800     albertel 6226:    foreach my $item (@$storearr) {
                   6227:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6228:       $i++;
1.191     harris41 6229:    }
1.12      www      6230:    return %returnhash;
                   6231: }
                   6232: 
1.667     albertel 6233: # ------------------------------------------------------------ tmpput interface
                   6234: sub tmpput {
1.802     raeburn  6235:     my ($storehash,$server,$context)=@_;
1.667     albertel 6236:     my $items='';
1.800     albertel 6237:     foreach my $item (keys(%$storehash)) {
                   6238: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6239:     }
                   6240:     $items=~s/\&$//;
1.802     raeburn  6241:     if (defined($context)) {
                   6242:         $items .= ':'.&escape($context);
                   6243:     }
1.667     albertel 6244:     return &reply("tmpput:$items",$server);
                   6245: }
                   6246: 
                   6247: # ------------------------------------------------------------ tmpget interface
                   6248: sub tmpget {
1.688     albertel 6249:     my ($token,$server)=@_;
                   6250:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6251:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6252:     my %returnhash;
                   6253:     foreach my $item (split(/\&/,$rep)) {
                   6254: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  6255:         next if ($key =~ /^error: 2 /);
1.667     albertel 6256: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6257:     }
                   6258:     return %returnhash;
                   6259: }
                   6260: 
1.1113    raeburn  6261: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6262: sub tmpdel {
                   6263:     my ($token,$server)=@_;
                   6264:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6265:     return &reply("tmpdel:$token",$server);
                   6266: }
                   6267: 
1.1198    raeburn  6268: # ------------------------------------------------------------ get_timebased_id 
                   6269: 
                   6270: sub get_timebased_id {
                   6271:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6272:         $maxtries) = @_;
                   6273:     my ($newid,$error,$dellock);
                   6274:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   6275:         return ('','ok','invalid call to get suffix');
                   6276:     }
                   6277: 
                   6278: # set defaults for any optional args for which values were not supplied
                   6279:     if ($who eq '') {
                   6280:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6281:     }
                   6282:     if (!$locktries) {
                   6283:         $locktries = 3;
                   6284:     }
                   6285:     if (!$maxtries) {
                   6286:         $maxtries = 10;
                   6287:     }
                   6288:     
                   6289:     if (($cdom eq '') || ($cnum eq '')) {
                   6290:         if ($env{'request.course.id'}) {
                   6291:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6292:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6293:         }
                   6294:         if (($cdom eq '') || ($cnum eq '')) {
                   6295:             return ('','ok','call to get suffix not in course context');
                   6296:         }
                   6297:     }
                   6298: 
                   6299: # construct locking item
                   6300:     my $lockhash = {
                   6301:                       $prefix."\0".'locked_'.$keyid => $who,
                   6302:                    };
                   6303:     my $tries = 0;
                   6304: 
                   6305: # attempt to get lock on nohist_$namespace file
                   6306:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6307:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6308:         $tries ++;
                   6309:         sleep 1;
                   6310:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6311:     }
                   6312: 
                   6313: # attempt to get unique identifier, based on current timestamp
                   6314:     if ($gotlock eq 'ok') {
                   6315:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6316:         my $id = time;
                   6317:         $newid = $id;
1.1268    raeburn  6318:         if ($idtype eq 'addcode') {
                   6319:             $newid .= &sixnum_code();
                   6320:         }
1.1198    raeburn  6321:         my $idtries = 0;
                   6322:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6323:             if ($idtype eq 'concat') {
                   6324:                 $newid = $id.$idtries;
1.1268    raeburn  6325:             } elsif ($idtype eq 'addcode') {
                   6326:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  6327:             } else {
                   6328:                 $newid ++;
                   6329:             }
                   6330:             $idtries ++;
                   6331:         }
                   6332:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6333:             my %new_item =  (
                   6334:                               $prefix."\0".$newid => $who,
                   6335:                             );
                   6336:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6337:                                                  $cdom,$cnum);
                   6338:             if ($putresult ne 'ok') {
                   6339:                 undef($newid);
                   6340:                 $error = 'error saving new item: '.$putresult;
                   6341:             }
                   6342:         } else {
1.1268    raeburn  6343:              undef($newid);
1.1198    raeburn  6344:              $error = ('error: no unique suffix available for the new item ');
                   6345:         }
                   6346: #  remove lock
                   6347:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6348:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6349:     } else {
                   6350:         $error = "error: could not obtain lockfile\n";
                   6351:         $dellock = 'ok';
1.1276    raeburn  6352:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6353:             $dellock = 'nolock';
                   6354:         }
1.1198    raeburn  6355:     }
                   6356:     return ($newid,$dellock,$error);
                   6357: }
                   6358: 
1.1268    raeburn  6359: sub sixnum_code {
                   6360:     my $code;
                   6361:     for (0..6) {
                   6362:         $code .= int( rand(9) );
                   6363:     }
                   6364:     return $code;
                   6365: }
                   6366: 
1.765     albertel 6367: # -------------------------------------------------- portfolio access checking
                   6368: 
                   6369: sub portfolio_access {
1.1270    raeburn  6370:     my ($requrl,$clientip) = @_;
1.765     albertel 6371:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  6372:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6373:     if ($result) {
                   6374:         my %setters;
                   6375:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6376:             my ($startblock,$endblock) =
                   6377:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6378:             if ($startblock && $endblock) {
                   6379:                 return 'B';
                   6380:             }
                   6381:         } else {
                   6382:             my ($startblock,$endblock) =
                   6383:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6384:             if ($startblock && $endblock) {
                   6385:                 return 'B';
                   6386:             }
                   6387:         }
                   6388:     }
1.765     albertel 6389:     if ($result eq 'ok') {
1.766     albertel 6390:        return 'F';
1.765     albertel 6391:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6392:        return 'A';
1.765     albertel 6393:     }
1.766     albertel 6394:     return '';
1.765     albertel 6395: }
                   6396: 
                   6397: sub get_portfolio_access {
1.1270    raeburn  6398:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 6399: 
                   6400:     if (!ref($access_hash)) {
                   6401: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6402: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6403: 						   $file_name);
                   6404: 	$access_hash = $access_controls{$file_name};
                   6405:     }
                   6406: 
1.1270    raeburn  6407:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 6408:     my $now = time;
                   6409:     if (ref($access_hash) eq 'HASH') {
                   6410:         foreach my $key (keys(%{$access_hash})) {
                   6411:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6412:             if ($start > $now) {
                   6413:                 next;
                   6414:             }
                   6415:             if ($end && $end<$now) {
                   6416:                 next;
                   6417:             }
                   6418:             if ($scope eq 'public') {
                   6419:                 $public = $key;
                   6420:                 last;
                   6421:             } elsif ($scope eq 'guest') {
                   6422:                 $guest = $key;
                   6423:             } elsif ($scope eq 'domains') {
                   6424:                 push(@domains,$key);
                   6425:             } elsif ($scope eq 'users') {
                   6426:                 push(@users,$key);
                   6427:             } elsif ($scope eq 'course') {
                   6428:                 push(@courses,$key);
                   6429:             } elsif ($scope eq 'group') {
                   6430:                 push(@groups,$key);
1.1270    raeburn  6431:             } elsif ($scope eq 'ip') {
                   6432:                 push(@ips,$key);
1.765     albertel 6433:             }
                   6434:         }
                   6435:         if ($public) {
                   6436:             return 'ok';
1.1270    raeburn  6437:         } elsif (@ips > 0) {
                   6438:             my $allowed;
                   6439:             foreach my $ipkey (@ips) {
                   6440:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   6441:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   6442:                         $allowed = 1;
                   6443:                         last; 
                   6444:                     }
                   6445:                 }
                   6446:             }
                   6447:             if ($allowed) {
                   6448:                 return 'ok';
                   6449:             }
1.765     albertel 6450:         }
                   6451:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6452:             if ($guest) {
                   6453:                 return $guest;
                   6454:             }
                   6455:         } else {
                   6456:             if (@domains > 0) {
                   6457:                 foreach my $domkey (@domains) {
                   6458:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6459:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6460:                             return 'ok';
                   6461:                         }
                   6462:                     }
                   6463:                 }
                   6464:             }
                   6465:             if (@users > 0) {
                   6466:                 foreach my $userkey (@users) {
1.865     raeburn  6467:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6468:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6469:                             if (ref($item) eq 'HASH') {
                   6470:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6471:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6472:                                     return 'ok';
                   6473:                                 }
                   6474:                             }
                   6475:                         }
                   6476:                     } 
1.765     albertel 6477:                 }
                   6478:             }
                   6479:             my %roleshash;
                   6480:             my @courses_and_groups = @courses;
                   6481:             push(@courses_and_groups,@groups); 
                   6482:             if (@courses_and_groups > 0) {
                   6483:                 my (%allgroups,%allroles); 
                   6484:                 my ($start,$end,$role,$sec,$group);
                   6485:                 foreach my $envkey (%env) {
1.1060    raeburn  6486:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6487:                         my $cid = $2.'_'.$3; 
                   6488:                         if ($1 eq 'gr') {
                   6489:                             $group = $4;
                   6490:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6491:                         } else {
                   6492:                             if ($4 eq '') {
                   6493:                                 $sec = 'none';
                   6494:                             } else {
                   6495:                                 $sec = $4;
                   6496:                             }
                   6497:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6498:                         }
1.811     albertel 6499:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6500:                         my $cid = $2.'_'.$3;
                   6501:                         if ($4 eq '') {
                   6502:                             $sec = 'none';
                   6503:                         } else {
                   6504:                             $sec = $4;
                   6505:                         }
                   6506:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6507:                     }
                   6508:                 }
                   6509:                 if (keys(%allroles) == 0) {
                   6510:                     return;
                   6511:                 }
                   6512:                 foreach my $key (@courses_and_groups) {
                   6513:                     my %content = %{$$access_hash{$key}};
                   6514:                     my $cnum = $content{'number'};
                   6515:                     my $cdom = $content{'domain'};
                   6516:                     my $cid = $cdom.'_'.$cnum;
                   6517:                     if (!exists($allroles{$cid})) {
                   6518:                         next;
                   6519:                     }    
                   6520:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6521:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6522:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6523:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6524:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6525:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6526:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6527:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6528:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6529:                                         if (grep/^all$/,@sections) {
                   6530:                                             return 'ok';
                   6531:                                         } else {
                   6532:                                             if (grep/^$sec$/,@sections) {
                   6533:                                                 return 'ok';
                   6534:                                             }
                   6535:                                         }
                   6536:                                     }
                   6537:                                 }
                   6538:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6539:                                     if (grep/^none$/,@groups) {
                   6540:                                         return 'ok';
                   6541:                                     }
                   6542:                                 } else {
                   6543:                                     if (grep/^all$/,@groups) {
                   6544:                                         return 'ok';
                   6545:                                     } 
                   6546:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6547:                                         if (grep/^$group$/,@groups) {
                   6548:                                             return 'ok';
                   6549:                                         }
                   6550:                                     }
                   6551:                                 } 
                   6552:                             }
                   6553:                         }
                   6554:                     }
                   6555:                 }
                   6556:             }
                   6557:             if ($guest) {
                   6558:                 return $guest;
                   6559:             }
                   6560:         }
                   6561:     }
                   6562:     return;
                   6563: }
                   6564: 
                   6565: sub course_group_datechecker {
                   6566:     my ($dates,$now,$status) = @_;
                   6567:     my ($start,$end) = split(/\./,$dates);
                   6568:     if (!$start && !$end) {
                   6569:         return 'ok';
                   6570:     }
                   6571:     if (grep/^active$/,@{$status}) {
                   6572:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6573:             return 'ok';
                   6574:         }
                   6575:     }
                   6576:     if (grep/^previous$/,@{$status}) {
                   6577:         if ($end > $now ) {
                   6578:             return 'ok';
                   6579:         }
                   6580:     }
                   6581:     if (grep/^future$/,@{$status}) {
                   6582:         if ($start > $now) {
                   6583:             return 'ok';
                   6584:         }
                   6585:     }
                   6586:     return; 
                   6587: }
                   6588: 
                   6589: sub parse_portfolio_url {
                   6590:     my ($url) = @_;
                   6591: 
                   6592:     my ($type,$udom,$unum,$group,$file_name);
                   6593:     
1.823     albertel 6594:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6595: 	$type = 1;
                   6596:         $udom = $1;
                   6597:         $unum = $2;
                   6598:         $file_name = $3;
1.823     albertel 6599:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6600: 	$type = 2;
                   6601:         $udom = $1;
                   6602:         $unum = $2;
                   6603:         $group = $3;
                   6604:         $file_name = $3.'/'.$4;
                   6605:     }
                   6606:     if (wantarray) {
                   6607: 	return ($type,$udom,$unum,$file_name,$group);
                   6608:     }
                   6609:     return $type;
                   6610: }
                   6611: 
                   6612: sub is_portfolio_url {
                   6613:     my ($url) = @_;
                   6614:     return scalar(&parse_portfolio_url($url));
                   6615: }
                   6616: 
1.798     raeburn  6617: sub is_portfolio_file {
                   6618:     my ($file) = @_;
1.820     raeburn  6619:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6620:         return 1;
                   6621:     }
                   6622:     return;
                   6623: }
                   6624: 
1.976     raeburn  6625: sub usertools_access {
1.1084    raeburn  6626:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6627:     my ($access,%tools);
                   6628:     if ($context eq '') {
                   6629:         $context = 'tools';
                   6630:     }
                   6631:     if ($context eq 'requestcourses') {
                   6632:         %tools = (
                   6633:                       official   => 1,
                   6634:                       unofficial => 1,
1.1006    raeburn  6635:                       community  => 1,
1.1246    raeburn  6636:                       textbook   => 1,
1.1305    raeburn  6637:                       placement  => 1,
1.985     raeburn  6638:                  );
1.1183    raeburn  6639:     } elsif ($context eq 'requestauthor') {
                   6640:         %tools = (
                   6641:                       requestauthor => 1,
                   6642:                  );
1.985     raeburn  6643:     } else {
                   6644:         %tools = (
                   6645:                       aboutme   => 1,
                   6646:                       blog      => 1,
1.1177    raeburn  6647:                       webdav    => 1,
1.985     raeburn  6648:                       portfolio => 1,
                   6649:                  );
                   6650:     }
1.976     raeburn  6651:     return if (!defined($tools{$tool}));
                   6652: 
1.1242    raeburn  6653:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6654:         $udom = $env{'user.domain'};
                   6655:         $uname = $env{'user.name'};
                   6656:     }
                   6657: 
1.978     raeburn  6658:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6659:         if ($action ne 'reload') {
1.985     raeburn  6660:             if ($context eq 'requestcourses') {
                   6661:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  6662:             } elsif ($context eq 'requestauthor') {
                   6663:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6664:             } else {
                   6665:                 return $env{'environment.availabletools.'.$tool};
                   6666:             }
                   6667:         }
1.976     raeburn  6668:     }
                   6669: 
1.1183    raeburn  6670:     my ($toolstatus,$inststatus,$envkey);
                   6671:     if ($context eq 'requestauthor') {
                   6672:         $envkey = $context; 
                   6673:     } else {
                   6674:         $envkey = $context.'.'.$tool;
                   6675:     }
1.976     raeburn  6676: 
1.985     raeburn  6677:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6678:          ($action ne 'reload')) {
1.1183    raeburn  6679:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6680:         $inststatus = $env{'environment.inststatus'};
                   6681:     } else {
1.1084    raeburn  6682:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  6683:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6684:             $inststatus = $userenvref->{'inststatus'};
                   6685:         } else {
1.1183    raeburn  6686:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6687:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6688:             $inststatus = $userenv{'inststatus'};
                   6689:         }
1.976     raeburn  6690:     }
                   6691: 
                   6692:     if ($toolstatus ne '') {
                   6693:         if ($toolstatus) {
                   6694:             $access = 1;
                   6695:         } else {
                   6696:             $access = 0;
                   6697:         }
                   6698:         return $access;
                   6699:     }
                   6700: 
1.1084    raeburn  6701:     my ($is_adv,%domdef);
                   6702:     if (ref($is_advref) eq 'HASH') {
                   6703:         $is_adv = $is_advref->{'is_adv'};
                   6704:     } else {
                   6705:         $is_adv = &is_advanced_user($udom,$uname);
                   6706:     }
                   6707:     if (ref($domdefref) eq 'HASH') {
                   6708:         %domdef = %{$domdefref};
                   6709:     } else {
                   6710:         %domdef = &get_domain_defaults($udom);
                   6711:     }
1.976     raeburn  6712:     if (ref($domdef{$tool}) eq 'HASH') {
                   6713:         if ($is_adv) {
                   6714:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6715:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6716:                     $access = 1;
                   6717:                 } else {
                   6718:                     $access = 0;
                   6719:                 }
                   6720:                 return $access;
                   6721:             }
                   6722:         }
                   6723:         if ($inststatus ne '') {
                   6724:             my ($hasaccess,$hasnoaccess);
                   6725:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6726:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6727:                     if ($domdef{$tool}{$affiliation}) {
                   6728:                         $hasaccess = 1;
                   6729:                     } else {
                   6730:                         $hasnoaccess = 1;
                   6731:                     }
                   6732:                 }
                   6733:             }
                   6734:             if ($hasaccess || $hasnoaccess) {
                   6735:                 if ($hasaccess) {
                   6736:                     $access = 1;
                   6737:                 } elsif ($hasnoaccess) {
                   6738:                     $access = 0; 
                   6739:                 }
                   6740:                 return $access;
                   6741:             }
                   6742:         } else {
                   6743:             if ($domdef{$tool}{'default'} ne '') {
                   6744:                 if ($domdef{$tool}{'default'}) {
                   6745:                     $access = 1;
                   6746:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6747:                     $access = 0;
                   6748:                 }
                   6749:                 return $access;
                   6750:             }
                   6751:         }
                   6752:     } else {
1.1177    raeburn  6753:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6754:             $access = 1;
                   6755:         } else {
                   6756:             $access = 0;
                   6757:         }
1.976     raeburn  6758:         return $access;
                   6759:     }
                   6760: }
                   6761: 
1.1050    raeburn  6762: sub is_course_owner {
                   6763:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6764:     if (($udom eq '') || ($uname eq '')) {
                   6765:         $udom = $env{'user.domain'};
                   6766:         $uname = $env{'user.name'};
                   6767:     }
                   6768:     unless (($udom eq '') || ($uname eq '')) {
                   6769:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6770:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6771:                 return 1;
                   6772:             } else {
                   6773:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6774:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6775:                     return 1;
                   6776:                 }
                   6777:             }
                   6778:         }
                   6779:     }
                   6780:     return;
                   6781: }
                   6782: 
1.976     raeburn  6783: sub is_advanced_user {
                   6784:     my ($udom,$uname) = @_;
1.1085    raeburn  6785:     if ($udom ne '' && $uname ne '') {
                   6786:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6787:             if (wantarray) {
                   6788:                 return ($env{'user.adv'},$env{'user.author'});
                   6789:             } else {
                   6790:                 return $env{'user.adv'};
                   6791:             }
1.1085    raeburn  6792:         }
                   6793:     }
1.976     raeburn  6794:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6795:     my %allroles;
1.1128    raeburn  6796:     my ($is_adv,$is_author);
1.976     raeburn  6797:     foreach my $role (keys(%roleshash)) {
                   6798:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6799:         my $area = '/'.$tdomain.'/'.$trest;
                   6800:         if ($sec ne '') {
                   6801:             $area .= '/'.$sec;
                   6802:         }
                   6803:         if (($area ne '') && ($trole ne '')) {
                   6804:             my $spec=$trole.'.'.$area;
                   6805:             if ($trole =~ /^cr\//) {
                   6806:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6807:             } elsif ($trole ne 'gr') {
                   6808:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6809:             }
1.1128    raeburn  6810:             if ($trole eq 'au') {
                   6811:                 $is_author = 1;
                   6812:             }
1.976     raeburn  6813:         }
                   6814:     }
                   6815:     foreach my $role (keys(%allroles)) {
                   6816:         last if ($is_adv);
                   6817:         foreach my $item (split(/:/,$allroles{$role})) {
                   6818:             if ($item ne '') {
                   6819:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6820:                 if ($privilege eq 'adv') {
                   6821:                     $is_adv = 1;
                   6822:                     last;
                   6823:                 }
                   6824:             }
                   6825:         }
                   6826:     }
1.1128    raeburn  6827:     if (wantarray) {
                   6828:         return ($is_adv,$is_author);
                   6829:     }
1.976     raeburn  6830:     return $is_adv;
                   6831: }
1.798     raeburn  6832: 
1.1035    raeburn  6833: sub check_can_request {
1.1036    raeburn  6834:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6835:     my $canreq = 0;
                   6836:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6837:     my @options = ('approval','validate','autolimit');
                   6838:     my $optregex = join('|',@options);
                   6839:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6840:         foreach my $type (@{$types}) {
                   6841:             if (&usertools_access($env{'user.name'},
                   6842:                                   $env{'user.domain'},
                   6843:                                   $type,undef,'requestcourses')) {
                   6844:                 $canreq ++;
1.1036    raeburn  6845:                 if (ref($request_domains) eq 'HASH') {
                   6846:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6847:                 }
1.1035    raeburn  6848:                 if ($dom eq $env{'user.domain'}) {
                   6849:                     $can_request->{$type} = 1;
                   6850:                 }
                   6851:             }
                   6852:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6853:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6854:                 if (@curr > 0) {
1.1036    raeburn  6855:                     foreach my $item (@curr) {
                   6856:                         if (ref($request_domains) eq 'HASH') {
                   6857:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6858:                             if ($otherdom ne '') {
                   6859:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6860:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6861:                                         push(@{$request_domains->{$type}},$otherdom);
                   6862:                                     }
                   6863:                                 } else {
                   6864:                                     push(@{$request_domains->{$type}},$otherdom);
                   6865:                                 }
                   6866:                             }
                   6867:                         }
                   6868:                     }
                   6869:                     unless($dom eq $env{'user.domain'}) {
                   6870:                         $canreq ++;
1.1035    raeburn  6871:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6872:                             $can_request->{$type} = 1;
                   6873:                         }
                   6874:                     }
                   6875:                 }
                   6876:             }
                   6877:         }
                   6878:     }
                   6879:     return $canreq;
                   6880: }
                   6881: 
1.341     www      6882: # ---------------------------------------------- Custom access rule evaluation
                   6883: 
                   6884: sub customaccess {
                   6885:     my ($priv,$uri)=@_;
1.807     albertel 6886:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6887:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6888:     $udom = &LONCAPA::clean_domain($udom);
                   6889:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6890:     my $access=0;
1.800     albertel 6891:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6892: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6893: 	if ($type eq 'user') {
                   6894: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6895: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6896: 		if ($tdom) {
                   6897: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6898: 		}
1.896     albertel 6899: 		if ($tuname) {
                   6900: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6901: 		}
                   6902: 		$access=($effect eq 'allow');
                   6903: 		last;
                   6904: 	    }
                   6905: 	} else {
                   6906: 	    if ($role) {
                   6907: 		if ($role ne $urole) { next; }
                   6908: 	    }
                   6909: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6910: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6911: 		if ($tdom) {
                   6912: 		    if ($tdom ne $udom) { next; }
                   6913: 		}
                   6914: 		if ($tcrs) {
                   6915: 		    if ($tcrs ne $ucrs) { next; }
                   6916: 		}
                   6917: 		if ($tsec) {
                   6918: 		    if ($tsec ne $usec) { next; }
                   6919: 		}
                   6920: 		$access=($effect eq 'allow');
                   6921: 		last;
                   6922: 	    }
                   6923: 	    if ($realm eq '' && $role eq '') {
                   6924: 		$access=($effect eq 'allow');
                   6925: 	    }
1.402     bowersj2 6926: 	}
1.341     www      6927:     }
                   6928:     return $access;
                   6929: }
                   6930: 
1.103     harris41 6931: # ------------------------------------------------- Check for a user privilege
1.12      www      6932: 
                   6933: sub allowed {
1.1281    raeburn  6934:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 6935:     my $ver_orguri=$uri;
1.439     www      6936:     $uri=&deversion($uri);
1.152     www      6937:     my $orguri=$uri;
1.52      www      6938:     $uri=&declutter($uri);
1.809     raeburn  6939: 
1.810     raeburn  6940:     if ($priv eq 'evb') {
                   6941: # Evade communication block restrictions for specified role in a course
                   6942:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6943:             return $1;
                   6944:         } else {
                   6945:             return;
                   6946:         }
                   6947:     }
                   6948: 
1.620     albertel 6949:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6950: # Free bre access to adm and meta resources
1.775     albertel 6951:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6952: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6953: 	&& ($priv eq 'bre')) {
1.14      www      6954: 	return 'F';
1.159     www      6955:     }
                   6956: 
1.545     banghart 6957: # Free bre access to user's own portfolio contents
1.714     raeburn  6958:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6959:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6960: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6961:         my %setters;
                   6962:         my ($startblock,$endblock) = 
                   6963:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6964:         if ($startblock && $endblock) {
                   6965:             return 'B';
                   6966:         } else {
                   6967:             return 'F';
                   6968:         }
1.545     banghart 6969:     }
                   6970: 
1.762     raeburn  6971: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6972:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6973:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6974:         if (exists($env{'request.course.id'})) {
                   6975:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6976:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6977:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6978:                 my $courseprivid=$env{'request.course.id'};
                   6979:                 $courseprivid=~s/\_/\//;
                   6980:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6981:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6982:                     return $1; 
1.762     raeburn  6983:                 } else {
                   6984:                     if ($env{'request.course.sec'}) {
                   6985:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6986:                     }
                   6987:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6988:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6989:                         return $2;
                   6990:                     }
1.714     raeburn  6991:                 }
                   6992:             }
                   6993:         }
                   6994:     }
                   6995: 
1.159     www      6996: # Free bre to public access
                   6997: 
                   6998:     if ($priv eq 'bre') {
1.238     www      6999:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7000: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7001:            return 'F'; 
                   7002:         }
1.238     www      7003:         if ($copyright eq 'priv') {
                   7004:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7005: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7006: 		return '';
                   7007:             }
                   7008:         }
                   7009:         if ($copyright eq 'domain') {
                   7010:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7011: 	    unless (($env{'user.domain'} eq $1) ||
                   7012:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7013: 		return '';
                   7014:             }
1.262     matthew  7015:         }
1.620     albertel 7016:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7017:             # Library role, so allow browsing of resources in this domain.
                   7018:             return 'F';
1.238     www      7019:         }
1.341     www      7020:         if ($copyright eq 'custom') {
                   7021: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7022:         }
1.14      www      7023:     }
1.264     matthew  7024:     # Domain coordinator is trying to create a course
1.620     albertel 7025:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7026:         # uri is the requested domain in this case.
                   7027:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7028:         # a role of dc for the domain in question.
1.620     albertel 7029:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7030:     }
1.29      www      7031: 
1.52      www      7032:     my $thisallowed='';
                   7033:     my $statecond=0;
                   7034:     my $courseprivid='';
                   7035: 
1.1039    raeburn  7036:     my $ownaccess;
1.1043    raeburn  7037:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7038:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7039:         if ($uri eq '') {
                   7040:             $ownaccess = 1;
                   7041:         } else {
                   7042:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7043:                 my $udom = $env{'user.domain'};
                   7044:                 my $uname = $env{'user.name'};
                   7045:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7046:                     $ownaccess = 1;
1.1040    raeburn  7047:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7048:                     unless ($uri =~ m{\.\./}) {
                   7049:                         $ownaccess = 1;
                   7050:                     }
                   7051:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7052:                     my $now = time;
                   7053:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7054:                         my $adom = $1;
                   7055:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7056:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7057:                                 my ($start,$end) = split('.',$env{$key});
                   7058:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7059:                                     $ownaccess = 1;
                   7060:                                     last;
                   7061:                                 }
                   7062:                             }
                   7063:                         }
                   7064:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7065:                         my $adom = $1;
                   7066:                         my $aname = $2;
1.1042    raeburn  7067:                         foreach my $role ('ca','aa') { 
                   7068:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7069:                                 my ($start,$end) =
                   7070:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7071:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7072:                                     $ownaccess = 1;
                   7073:                                     last;
                   7074:                                 }
1.1039    raeburn  7075:                             }
                   7076:                         }
                   7077:                     }
                   7078:                 }
                   7079:             }
                   7080:         }
                   7081:     }
                   7082: 
1.52      www      7083: # Course
                   7084: 
1.620     albertel 7085:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7086:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7087:             $thisallowed.=$1;
                   7088:         }
1.52      www      7089:     }
1.29      www      7090: 
1.52      www      7091: # Domain
                   7092: 
1.620     albertel 7093:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7094:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7095:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7096:             $thisallowed.=$1;
                   7097:         }
1.12      www      7098:     }
1.52      www      7099: 
1.1141    raeburn  7100: # User who is not author or co-author might still be able to edit
                   7101: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7102:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7103:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7104:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7105:             $thisallowed.=$1;
                   7106:         }
                   7107:     }
                   7108: 
1.52      www      7109: # Course: uri itself is a course
1.66      www      7110:     my $courseuri=$uri;
                   7111:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7112:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7113: 
1.620     albertel 7114:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7115:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7116:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7117:             $thisallowed.=$1;
                   7118:         }
1.12      www      7119:     }
1.29      www      7120: 
1.665     albertel 7121: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7122: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7123:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7124: 	$thisallowed='';
1.671     raeburn  7125:         my ($match)=&is_on_map($uri);
                   7126:         if ($match) {
                   7127:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7128:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  7129:                 my $value = $1;
                   7130:                 if ($noblockcheck) {
                   7131:                     $thisallowed.=$value;
1.1162    raeburn  7132:                 } else {
1.1281    raeburn  7133:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7134:                     if (@blockers > 0) {
                   7135:                         $thisallowed = 'B';
                   7136:                     } else {
                   7137:                         $thisallowed.=$value;
                   7138:                     }
1.1162    raeburn  7139:                 }
1.671     raeburn  7140:             }
                   7141:         } else {
1.705     albertel 7142:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7143:             if ($refuri) {
                   7144:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7145:                     $thisallowed='F';
1.671     raeburn  7146:                 } else {
                   7147:                     $refuri=&declutter($refuri);
                   7148:                     my ($match) = &is_on_map($refuri);
                   7149:                     if ($match) {
1.1281    raeburn  7150:                         if ($noblockcheck) {
                   7151:                             $thisallowed='F';
1.1162    raeburn  7152:                         } else {
1.1281    raeburn  7153:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7154:                             if (@blockers > 0) {
                   7155:                                 $thisallowed = 'B';
                   7156:                             } else {
                   7157:                                 $thisallowed='F';
                   7158:                             }
1.1162    raeburn  7159:                         }
1.671     raeburn  7160:                     }
1.669     raeburn  7161:                 }
1.671     raeburn  7162:             }
                   7163:         }
1.314     www      7164:     }
1.492     albertel 7165: 
1.766     albertel 7166:     if ($priv eq 'bre'
                   7167: 	&& $thisallowed ne 'F' 
                   7168: 	&& $thisallowed ne '2'
                   7169: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  7170: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7171:     }
1.1250    raeburn  7172: 
1.52      www      7173: # Full access at system, domain or course-wide level? Exit.
1.29      www      7174:     if ($thisallowed=~/F/) {
                   7175: 	return 'F';
                   7176:     }
                   7177: 
1.52      www      7178: # If this is generating or modifying users, exit with special codes
1.29      www      7179: 
1.643     www      7180:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7181: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7182: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7183: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7184: 	    unless ($auname) { return $thisallowed; }
                   7185: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7186: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7187: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7188: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7189: 	}
1.52      www      7190: 	return $thisallowed;
                   7191:     }
                   7192: #
1.103     harris41 7193: # Gathered so far: system, domain and course wide privileges
1.52      www      7194: #
                   7195: # Course: See if uri or referer is an individual resource that is part of 
                   7196: # the course
                   7197: 
1.620     albertel 7198:     if ($env{'request.course.id'}) {
1.232     www      7199: 
1.620     albertel 7200:        $courseprivid=$env{'request.course.id'};
                   7201:        if ($env{'request.course.sec'}) {
                   7202:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7203:        }
                   7204:        $courseprivid=~s/\_/\//;
                   7205:        my $checkreferer=1;
1.232     www      7206:        my ($match,$cond)=&is_on_map($uri);
                   7207:        if ($match) {
                   7208:            $statecond=$cond;
1.620     albertel 7209:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7210:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7211:                my $value = $1;
                   7212:                if ($priv eq 'bre') {
1.1281    raeburn  7213:                    if ($noblockcheck) {
                   7214:                        $thisallowed.=$value;
1.1162    raeburn  7215:                    } else {
1.1281    raeburn  7216:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7217:                        if (@blockers > 0) {
                   7218:                            $thisallowed = 'B';
                   7219:                        } else {
                   7220:                            $thisallowed.=$value;
                   7221:                        }
1.1162    raeburn  7222:                    }
                   7223:                } else {
                   7224:                    $thisallowed.=$value;
                   7225:                }
1.52      www      7226:                $checkreferer=0;
                   7227:            }
1.29      www      7228:        }
1.83      www      7229:        
1.148     www      7230:        if ($checkreferer) {
1.620     albertel 7231: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7232:             unless ($refuri) {
1.800     albertel 7233:                 foreach my $key (keys(%env)) {
                   7234: 		    if ($key=~/^httpref\..*\*/) {
                   7235: 			my $pattern=$key;
1.156     www      7236:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7237:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7238:                         $pattern=~s/\//\\\//g;
1.152     www      7239:                         if ($orguri=~/$pattern/) {
1.800     albertel 7240: 			    $refuri=$env{$key};
1.148     www      7241:                         }
                   7242:                     }
1.191     harris41 7243:                 }
1.148     www      7244:             }
1.232     www      7245: 
1.148     www      7246:          if ($refuri) { 
1.152     www      7247: 	  $refuri=&declutter($refuri);
1.232     www      7248:           my ($match,$cond)=&is_on_map($refuri);
                   7249:             if ($match) {
                   7250:               my $refstatecond=$cond;
1.620     albertel 7251:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7252:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7253:                   my $value = $1;
                   7254:                   if ($priv eq 'bre') {
1.1281    raeburn  7255:                       if ($noblockcheck) {
                   7256:                           $thisallowed.=$value;
1.1162    raeburn  7257:                       } else {
1.1281    raeburn  7258:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7259:                           if (@blockers > 0) {
                   7260:                               $thisallowed = 'B';
                   7261:                           } else {
                   7262:                               $thisallowed.=$value;
                   7263:                           }
1.1162    raeburn  7264:                       }
                   7265:                   } else {
                   7266:                       $thisallowed.=$value;
                   7267:                   }
1.53      www      7268:                   $uri=$refuri;
                   7269:                   $statecond=$refstatecond;
1.52      www      7270:               }
                   7271:           }
1.148     www      7272:         }
1.29      www      7273:        }
1.52      www      7274:    }
1.29      www      7275: 
1.52      www      7276: #
1.103     harris41 7277: # Gathered now: all privileges that could apply, and condition number
1.52      www      7278: # 
                   7279: #
                   7280: # Full or no access?
                   7281: #
1.29      www      7282: 
1.52      www      7283:     if ($thisallowed=~/F/) {
                   7284: 	return 'F';
                   7285:     }
1.29      www      7286: 
1.52      www      7287:     unless ($thisallowed) {
                   7288:         return '';
                   7289:     }
1.29      www      7290: 
1.52      www      7291: # Restrictions exist, deal with them
                   7292: #
                   7293: #   C:according to course preferences
                   7294: #   R:according to resource settings
                   7295: #   L:unless locked
                   7296: #   X:according to user session state
                   7297: #
                   7298: 
                   7299: # Possibly locked functionality, check all courses
1.54      www      7300: # Locks might take effect only after 10 minutes cache expiration for other
                   7301: # courses, and 2 minutes for current course
1.52      www      7302: 
                   7303:     my $envkey;
                   7304:     if ($thisallowed=~/L/) {
1.1000    raeburn  7305:         foreach $envkey (keys(%env)) {
1.54      www      7306:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7307:                my $courseid=$2;
                   7308:                my $roleid=$1.'.'.$2;
1.92      www      7309:                $courseid=~s/^\///;
1.54      www      7310:                my $expiretime=600;
1.620     albertel 7311:                if ($env{'request.role'} eq $roleid) {
1.54      www      7312: 		  $expiretime=120;
                   7313:                }
                   7314: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7315:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7316:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7317: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7318:                }
1.620     albertel 7319:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7320:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7321: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7322:                        &log($env{'user.domain'},$env{'user.name'},
                   7323:                             $env{'user.home'},
1.57      www      7324:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7325:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7326:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7327: 		       return '';
                   7328:                    }
                   7329:                }
1.620     albertel 7330:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7331:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7332: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7333:                        &log($env{'user.domain'},$env{'user.name'},
                   7334:                             $env{'user.home'},
1.57      www      7335:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7336:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7337:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7338: 		       return '';
                   7339:                    }
                   7340:                }
                   7341: 	   }
1.29      www      7342:        }
1.52      www      7343:     }
                   7344:    
                   7345: #
                   7346: # Rest of the restrictions depend on selected course
                   7347: #
                   7348: 
1.620     albertel 7349:     unless ($env{'request.course.id'}) {
1.766     albertel 7350: 	if ($thisallowed eq 'A') {
                   7351: 	    return 'A';
1.814     raeburn  7352:         } elsif ($thisallowed eq 'B') {
                   7353:             return 'B';
1.766     albertel 7354: 	} else {
                   7355: 	    return '1';
                   7356: 	}
1.52      www      7357:     }
1.29      www      7358: 
1.52      www      7359: #
                   7360: # Now user is definitely in a course
                   7361: #
1.53      www      7362: 
                   7363: 
                   7364: # Course preferences
                   7365: 
                   7366:    if ($thisallowed=~/C/) {
1.620     albertel 7367:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7368:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7369:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7370: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  7371: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 7372: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7373: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7374: 			$env{'request.course.id'});
                   7375: 	   }
1.237     www      7376:            return '';
                   7377:        }
                   7378: 
1.620     albertel 7379:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7380: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  7381: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 7382: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7383: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7384: 			$env{'request.course.id'});
                   7385: 	   }
1.54      www      7386:            return '';
                   7387:        }
1.53      www      7388:    }
                   7389: 
                   7390: # Resource preferences
                   7391: 
                   7392:    if ($thisallowed=~/R/) {
1.620     albertel 7393:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7394:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7395: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7396: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7397: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7398: 	   }
                   7399: 	   return '';
1.54      www      7400:        }
1.53      www      7401:    }
1.30      www      7402: 
1.246     www      7403: # Restricted by state or randomout?
1.30      www      7404: 
1.52      www      7405:    if ($thisallowed=~/X/) {
1.620     albertel 7406:       if ($env{'acc.randomout'}) {
1.579     albertel 7407: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7408:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7409:             return ''; 
                   7410:          }
1.247     www      7411:       }
                   7412:       if (&condval($statecond)) {
1.52      www      7413: 	 return '2';
                   7414:       } else {
                   7415:          return '';
                   7416:       }
                   7417:    }
1.30      www      7418: 
1.766     albertel 7419:     if ($thisallowed eq 'A') {
                   7420: 	return 'A';
1.814     raeburn  7421:     } elsif ($thisallowed eq 'B') {
                   7422:         return 'B';
1.766     albertel 7423:     }
1.52      www      7424:    return 'F';
1.232     www      7425: }
1.1162    raeburn  7426: 
1.1192    raeburn  7427: # ------------------------------------------- Check construction space access
                   7428: 
                   7429: sub constructaccess {
                   7430:     my ($url,$setpriv)=@_;
                   7431: 
                   7432: # We do not allow editing of previous versions of files
                   7433:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7434: 
                   7435: # Get username and domain from URL
                   7436:     my ($ownername,$ownerdomain,$ownerhome);
                   7437: 
                   7438:     ($ownerdomain,$ownername) =
1.1297    damieng  7439:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)/});
1.1192    raeburn  7440: 
                   7441: # The URL does not really point to any authorspace, forget it
                   7442:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7443: 
                   7444: # Now we need to see if the user has access to the authorspace of
                   7445: # $ownername at $ownerdomain
                   7446: 
                   7447:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7448: # Real author for this?
                   7449:        $ownerhome = $env{'user.home'};
                   7450:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7451:           return ($ownername,$ownerdomain,$ownerhome);
                   7452:        }
                   7453:     } else {
                   7454: # Co-author for this?
                   7455:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7456:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7457:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7458:             return ($ownername,$ownerdomain,$ownerhome);
                   7459:         }
1.1312    raeburn  7460:         if ($env{'request.course.id'}) {
                   7461:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
                   7462:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
                   7463:                 if (&allowed('mdc',$env{'request.course.id'})) {
                   7464:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   7465:                     return ($ownername,$ownerdomain,$ownerhome);
                   7466:                 }
                   7467:             }
                   7468:         }
1.1192    raeburn  7469:     }
                   7470: 
                   7471: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7472: # we might as well leave
                   7473:    unless ($setpriv) { return ''; }
                   7474: 
                   7475: # Backdoor access?
                   7476:     my $allowed=&allowed('eco',$ownerdomain);
                   7477: # Nope
                   7478:     unless ($allowed) { return ''; }
                   7479: # Looks like we may have access, but could be locked by the owner of the construction space
                   7480:     if ($allowed eq 'U') {
                   7481:         my %blocked=&get('environment',['domcoord.author'],
                   7482:                          $ownerdomain,$ownername);
                   7483: # Is blocked by owner
                   7484:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7485:     }
                   7486:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7487: # Grant temporary access
                   7488:         my $then=$env{'user.login.time'};
1.1209    raeburn  7489:         my $update=$env{'user.update.time'};
1.1192    raeburn  7490:         if (!$update) { $update = $then; }
                   7491:         my $refresh=$env{'user.refresh.time'};
                   7492:         if (!$refresh) { $refresh = $update; }
                   7493:         my $now = time;
                   7494:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7495:                            $now,'ca','constructaccess');
                   7496:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7497:         return($ownername,$ownerdomain,$ownerhome);
                   7498:     }
                   7499: # No business here
                   7500:     return '';
                   7501: }
                   7502: 
1.1282    raeburn  7503: # ----------------------------------------------------------- Content Blocking
                   7504: 
                   7505: {
                   7506: # Caches for faster Course Contents display where content blocking
                   7507: # is in operation (i.e., interval param set) for timed quiz.
                   7508: #
                   7509: # User for whom data are being temporarily cached.
                   7510: my $cacheduser='';
                   7511: # Cached blockers for this user (a hash of blocking items). 
                   7512: my %cachedblockers=();
                   7513: # When the data were last cached.
                   7514: my $cachedlast='';
                   7515: 
                   7516: sub load_all_blockers {
                   7517:     my ($uname,$udom,$blocks)=@_;
                   7518:     if (($uname ne '') && ($udom ne '')) { 
                   7519:         if (($cacheduser eq $uname.':'.$udom) &&
                   7520:             (abs($cachedlast-time)<5)) {
                   7521:             return;
                   7522:         }
                   7523:     }
                   7524:     $cachedlast=time;
                   7525:     $cacheduser=$uname.':'.$udom;
                   7526:     %cachedblockers = &get_commblock_resources($blocks);
                   7527: }
                   7528: 
1.1162    raeburn  7529: sub get_comm_blocks {
                   7530:     my ($cdom,$cnum) = @_;
                   7531:     if ($cdom eq '' || $cnum eq '') {
                   7532:         return unless ($env{'request.course.id'});
                   7533:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7534:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7535:     }
                   7536:     my %commblocks;
                   7537:     my $hashid=$cdom.'_'.$cnum;
                   7538:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7539:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7540:         %commblocks = %{$blocksref};
                   7541:     } else {
                   7542:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7543:         my $cachetime = 600;
                   7544:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7545:     }
                   7546:     return %commblocks;
                   7547: }
                   7548: 
1.1282    raeburn  7549: sub get_commblock_resources {
                   7550:     my ($blocks) = @_;
                   7551:     my %blockers = ();
                   7552:     return %blockers unless ($env{'request.course.id'});
                   7553:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  7554:     my %commblocks;
                   7555:     if (ref($blocks) eq 'HASH') {
                   7556:         %commblocks = %{$blocks};
                   7557:     } else {
                   7558:         %commblocks = &get_comm_blocks();
                   7559:     }
1.1282    raeburn  7560:     return %blockers unless (keys(%commblocks) > 0); 
                   7561:     my $navmap = Apache::lonnavmaps::navmap->new();
                   7562:     return %blockers unless (ref($navmap));
1.1162    raeburn  7563:     my $now = time;
                   7564:     foreach my $block (keys(%commblocks)) {
                   7565:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7566:             my ($start,$end) = ($1,$2);
                   7567:             if ($start <= $now && $end >= $now) {
                   7568:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7569:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7570:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  7571:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7572:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  7573:                             }
                   7574:                         }
                   7575:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  7576:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7577:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  7578:                             }
                   7579:                         }
                   7580:                     }
                   7581:                 }
                   7582:             }
                   7583:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7584:             my $item = $1;
1.1163    raeburn  7585:             my @to_test;
1.1162    raeburn  7586:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7587:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282    raeburn  7588:                     my @interval;
                   7589:                     my $type = 'map';
                   7590:                     if ($item eq 'course') {
                   7591:                         $type = 'course';
                   7592:                         @interval=&EXT("resource.0.interval");
                   7593:                     } else {
                   7594:                         if ($item =~ /___\d+___/) {
                   7595:                             $type = 'resource';
                   7596:                             @interval=&EXT("resource.0.interval",$item);
                   7597:                             if (ref($navmap)) {                        
                   7598:                                 my $res = $navmap->getBySymb($item); 
                   7599:                                 push(@to_test,$res);
                   7600:                             }
1.1162    raeburn  7601:                         } else {
1.1282    raeburn  7602:                             my $mapsymb = &symbread($item,1);
                   7603:                             if ($mapsymb) {
                   7604:                                 if (ref($navmap)) {
                   7605:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   7606:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   7607:                                     foreach my $res (@to_test) {
                   7608:                                         my $symb = $res->symb();
                   7609:                                         next if ($symb eq $mapsymb);
                   7610:                                         if ($symb ne '') {
                   7611:                                             @interval=&EXT("resource.0.interval",$symb);
                   7612:                                             if ($interval[1] eq 'map') {
                   7613:                                                 last;
1.1162    raeburn  7614:                                             }
                   7615:                                         }
                   7616:                                     }
                   7617:                                 }
                   7618:                             }
                   7619:                         }
1.1282    raeburn  7620:                     }
1.1310    raeburn  7621:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  7622:                         my $timelimit = $1; 
1.1282    raeburn  7623:                         my $first_access;
                   7624:                         if ($type eq 'resource') {
                   7625:                             $first_access=&get_first_access($interval[1],$item);
                   7626:                         } elsif ($type eq 'map') {
                   7627:                             $first_access=&get_first_access($interval[1],undef,$item);
                   7628:                         } else {
                   7629:                             $first_access=&get_first_access($interval[1]);
                   7630:                         }
                   7631:                         if ($first_access) {
1.1292    raeburn  7632:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  7633:                             if ($timesup > $now) {
                   7634:                                 my $activeblock;
                   7635:                                 foreach my $res (@to_test) {
1.1283    raeburn  7636:                                     if ($res->answerable()) {
1.1282    raeburn  7637:                                         $activeblock = 1;
                   7638:                                         last;
                   7639:                                     }
                   7640:                                 }
                   7641:                                 if ($activeblock) {
                   7642:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7643:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7644:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   7645:                                          }
                   7646:                                     }
                   7647:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7648:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7649:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  7650:                                         }
1.1162    raeburn  7651:                                     }
                   7652:                                 }
                   7653:                             }
                   7654:                         }
                   7655:                     }
                   7656:                 }
                   7657:             }
                   7658:         }
                   7659:     }
1.1282    raeburn  7660:     return %blockers;
1.1162    raeburn  7661: }
                   7662: 
1.1282    raeburn  7663: sub has_comm_blocking {
                   7664:     my ($priv,$symb,$uri,$blocks) = @_;
                   7665:     my @blockers;
                   7666:     return unless ($env{'request.course.id'});
                   7667:     return unless ($priv eq 'bre');
                   7668:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7669:     return if ($env{'request.state'} eq 'construct');
                   7670:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   7671:     return unless (keys(%cachedblockers) > 0);
                   7672:     my (%possibles,@symbs);
                   7673:     if (!$symb) {
                   7674:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  7675:     }
1.1282    raeburn  7676:     if ($symb) {
                   7677:         @symbs = ($symb);
                   7678:     } elsif (keys(%possibles)) { 
                   7679:         @symbs = keys(%possibles);
                   7680:     }
                   7681:     my $noblock;
                   7682:     foreach my $symb (@symbs) {
                   7683:         last if ($noblock);
                   7684:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   7685:         foreach my $block (keys(%cachedblockers)) {
                   7686:             if ($block =~ /^firstaccess____(.+)$/) {
                   7687:                 my $item = $1;
                   7688:                 if (($item eq $map) || ($item eq $symb)) {
                   7689:                     $noblock = 1;
                   7690:                     last;
                   7691:                 }
                   7692:             }
                   7693:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   7694:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   7695:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   7696:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   7697:                             push(@blockers,$block);
                   7698:                         }
                   7699:                     }
                   7700:                 }
1.1162    raeburn  7701:             }
1.1282    raeburn  7702:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   7703:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   7704:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   7705:                         push(@blockers,$block);
                   7706:                     }
                   7707:                 }
1.1162    raeburn  7708:             }
                   7709:         }
                   7710:     }
1.1282    raeburn  7711:     return if ($noblock);
                   7712:     return @blockers;
                   7713: }
1.1162    raeburn  7714: }
                   7715: 
1.1282    raeburn  7716: # -------------------------------- Deversion and split uri into path an filename   
                   7717: 
1.1133    foxr     7718: #
1.1282    raeburn  7719: #   Removes the version from a URI and
1.1133    foxr     7720: #   splits it in to its filename and path to the filename.
                   7721: #   Seems like File::Basename could have done this more clearly.
                   7722: #   Parameters:
                   7723: #      $uri   - input URI
                   7724: #   Returns:
                   7725: #     Two element list consisting of 
                   7726: #     $pathname  - the URI up to and excluding the trailing /
                   7727: #     $filename  - The part of the URI following the last /
                   7728: #  NOTE:
                   7729: #    Another realization of this is simply:
                   7730: #    use File::Basename;
                   7731: #    ...
                   7732: #    $uri = shift;
                   7733: #    $filename = basename($uri);
                   7734: #    $path     = dirname($uri);
                   7735: #    return ($filename, $path);
                   7736: #
                   7737: #     The implementation below is probably faster however.
                   7738: #
1.710     albertel 7739: sub split_uri_for_cond {
                   7740:     my $uri=&deversion(&declutter(shift));
                   7741:     my @uriparts=split(/\//,$uri);
                   7742:     my $filename=pop(@uriparts);
                   7743:     my $pathname=join('/',@uriparts);
                   7744:     return ($pathname,$filename);
                   7745: }
1.232     www      7746: # --------------------------------------------------- Is a resource on the map?
                   7747: 
                   7748: sub is_on_map {
1.710     albertel 7749:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7750:     #Trying to find the conditional for the file
1.620     albertel 7751:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7752: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7753:     if ($match) {
1.289     bowersj2 7754: 	return (1,$1);
                   7755:     } else {
1.434     www      7756: 	return (0,0);
1.289     bowersj2 7757:     }
1.12      www      7758: }
                   7759: 
1.427     www      7760: # --------------------------------------------------------- Get symb from alias
                   7761: 
                   7762: sub get_symb_from_alias {
                   7763:     my $symb=shift;
                   7764:     my ($map,$resid,$url)=&decode_symb($symb);
                   7765: # Already is a symb
                   7766:     if ($url) { return $symb; }
                   7767: # Must be an alias
                   7768:     my $aliassymb='';
                   7769:     my %bighash;
1.620     albertel 7770:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7771:                             &GDBM_READER(),0640)) {
                   7772:         my $rid=$bighash{'mapalias_'.$symb};
                   7773: 	if ($rid) {
                   7774: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7775: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7776: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7777: 	}
                   7778:         untie %bighash;
                   7779:     }
                   7780:     return $aliassymb;
                   7781: }
                   7782: 
1.12      www      7783: # ----------------------------------------------------------------- Define Role
                   7784: 
                   7785: sub definerole {
                   7786:   if (allowed('mcr','/')) {
                   7787:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7788:     foreach my $role (split(':',$sysrole)) {
                   7789: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7790:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7791:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7792: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7793:                return "refused:s:$crole&$cqual"; 
                   7794:             }
                   7795:         }
1.191     harris41 7796:     }
1.800     albertel 7797:     foreach my $role (split(':',$domrole)) {
                   7798: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7799:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7800:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7801: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7802:                return "refused:d:$crole&$cqual"; 
                   7803:             }
                   7804:         }
1.191     harris41 7805:     }
1.800     albertel 7806:     foreach my $role (split(':',$courole)) {
                   7807: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7808:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7809:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7810: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7811:                return "refused:c:$crole&$cqual"; 
                   7812:             }
                   7813:         }
1.191     harris41 7814:     }
1.620     albertel 7815:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7816:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7817: 	        "rolesdef_$rolename=".
                   7818:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7819:     return reply($command,$env{'user.home'});
1.12      www      7820:   } else {
                   7821:     return 'refused';
                   7822:   }
1.105     harris41 7823: }
                   7824: 
                   7825: # ---------------- Make a metadata query against the network of library servers
                   7826: 
                   7827: sub metadata_query {
1.1237    raeburn  7828:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 7829:     my %rhash;
1.845     albertel 7830:     my %libserv = &all_library();
1.244     matthew  7831:     my @server_list = (defined($server_array) ? @$server_array
                   7832:                                               : keys(%libserv) );
                   7833:     for my $server (@server_list) {
1.1237    raeburn  7834:         my $domains = ''; 
                   7835:         if (ref($domains_hash) eq 'HASH') {
                   7836:             $domains = $domains_hash->{$server}; 
                   7837:         }
1.118     harris41 7838: 	unless ($custom or $customshow) {
1.1237    raeburn  7839: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 7840: 	    $rhash{$server}=$reply;
                   7841: 	}
                   7842: 	else {
                   7843: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  7844: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 7845: 			     $server);
                   7846: 	    $rhash{$server}=$reply;
                   7847: 	}
1.112     harris41 7848:     }
1.118     harris41 7849:     return \%rhash;
1.240     www      7850: }
                   7851: 
                   7852: # ----------------------------------------- Send log queries and wait for reply
                   7853: 
                   7854: sub log_query {
                   7855:     my ($uname,$udom,$query,%filters)=@_;
                   7856:     my $uhome=&homeserver($uname,$udom);
                   7857:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7858:     my $uhost=&hostname($uhome);
1.800     albertel 7859:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7860:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7861:                        $uhome);
1.479     albertel 7862:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7863:     return get_query_reply($queryid);
                   7864: }
                   7865: 
1.818     raeburn  7866: # -------------------------- Update MySQL table for portfolio file
                   7867: 
                   7868: sub update_portfolio_table {
1.821     raeburn  7869:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7870:     if ($group ne '') {
                   7871:         $file_name =~s /^\Q$group\E//;
                   7872:     }
1.818     raeburn  7873:     my $homeserver = &homeserver($uname,$udom);
                   7874:     my $queryid=
1.821     raeburn  7875:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7876:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7877:     my $reply = &get_query_reply($queryid);
                   7878:     return $reply;
                   7879: }
                   7880: 
1.899     raeburn  7881: # -------------------------- Update MySQL allusers table
                   7882: 
                   7883: sub update_allusers_table {
                   7884:     my ($uname,$udom,$names) = @_;
                   7885:     my $homeserver = &homeserver($uname,$udom);
                   7886:     my $queryid=
                   7887:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7888:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7889:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7890:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7891:                'generation='.&escape($names->{'generation'}).'%%'.
                   7892:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7893:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7894:     return;
1.899     raeburn  7895: }
                   7896: 
1.508     raeburn  7897: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7898: 
                   7899: sub fetch_enrollment_query {
1.511     raeburn  7900:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317    raeburn  7901:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  7902:     my $maxtries = 1;
1.508     raeburn  7903:     if ($context eq 'automated') {
                   7904:         $homeserver = $perlvar{'lonHostID'};
1.1317    raeburn  7905:         $sleep = 2;
                   7906:         $loopmax = 100;
1.547     raeburn  7907:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7908:     } else {
                   7909:         $homeserver = &homeserver($cnum,$dom);
                   7910:     }
1.838     albertel 7911:     my $host=&hostname($homeserver);
1.506     raeburn  7912:     my $cmd = '';
1.1000    raeburn  7913:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7914:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7915:     }
                   7916:     $cmd =~ s/%%$//;
                   7917:     $cmd = &escape($cmd);
                   7918:     my $query = 'fetchenrollment';
1.620     albertel 7919:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7920:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7921:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7922:         return 'error: '.$queryid;
                   7923:     }
1.1317    raeburn  7924:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  7925:     my $tries = 1;
                   7926:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317    raeburn  7927:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  7928:         $tries ++;
                   7929:     }
1.526     raeburn  7930:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7931:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7932:     } else {
1.901     albertel 7933:         my @responses = split(/:/,$reply);
1.1322    raeburn  7934:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 7935:             foreach my $line (@responses) {
                   7936:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7937:                 $$replyref{$key} = $value;
                   7938:             }
                   7939:         } else {
1.1117    foxr     7940:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7941:             foreach my $line (@responses) {
                   7942:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7943:                 $$replyref{$key} = $value;
                   7944:                 if ($value > 0) {
1.800     albertel 7945:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7946:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7947:                         my $destname = $pathname.'/'.$filename;
                   7948:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7949:                         if ($xml_classlist =~ /^error/) {
                   7950:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7951:                         } else {
1.506     raeburn  7952:                             if ( open(FILE,">$destname") ) {
                   7953:                                 print FILE &unescape($xml_classlist);
                   7954:                                 close(FILE);
1.526     raeburn  7955:                             } else {
                   7956:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7957:                             }
                   7958:                         }
                   7959:                     }
                   7960:                 }
                   7961:             }
                   7962:         }
                   7963:         return 'ok';
                   7964:     }
                   7965:     return 'error';
                   7966: }
                   7967: 
1.242     www      7968: sub get_query_reply {
1.1317    raeburn  7969:     my ($queryid,$sleep,$loopmax) = @_;;
                   7970:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   7971:         $sleep = 0.2;
                   7972:     }
                   7973:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   7974:         $loopmax = 100;
                   7975:     }
1.1117    foxr     7976:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7977:     my $reply='';
1.1317    raeburn  7978:     for (1..$loopmax) {
                   7979: 	sleep($sleep);
1.240     www      7980:         if (-e $replyfile.'.end') {
1.448     albertel 7981: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7982: 		$reply = join('',<$fh>);
                   7983: 		close($fh);
1.240     www      7984: 	   } else { return 'error: reply_file_error'; }
1.242     www      7985:            return &unescape($reply);
                   7986: 	}
1.240     www      7987:     }
1.242     www      7988:     return 'timeout:'.$queryid;
1.240     www      7989: }
                   7990: 
                   7991: sub courselog_query {
1.241     www      7992: #
                   7993: # possible filters:
                   7994: # url: url or symb
                   7995: # username
                   7996: # domain
                   7997: # action: view, submit, grade
                   7998: # start: timestamp
                   7999: # end: timestamp
                   8000: #
1.240     www      8001:     my (%filters)=@_;
1.620     albertel 8002:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8003:     if ($filters{'url'}) {
                   8004: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8005:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8006:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8007:     }
1.620     albertel 8008:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8009:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8010:     return &log_query($cname,$cdom,'courselog',%filters);
                   8011: }
                   8012: 
                   8013: sub userlog_query {
1.858     raeburn  8014: #
                   8015: # possible filters:
                   8016: # action: log check role
                   8017: # start: timestamp
                   8018: # end: timestamp
                   8019: #
1.240     www      8020:     my ($uname,$udom,%filters)=@_;
                   8021:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8022: }
                   8023: 
1.506     raeburn  8024: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8025: 
                   8026: sub auto_run {
1.508     raeburn  8027:     my ($cnum,$cdom) = @_;
1.876     raeburn  8028:     my $response = 0;
                   8029:     my $settings;
                   8030:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8031:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8032:         $settings = $domconfig{'autoenroll'};
                   8033:         if ($settings->{'run'} eq '1') {
                   8034:             $response = 1;
                   8035:         }
                   8036:     } else {
1.934     raeburn  8037:         my $homeserver;
                   8038:         if (&is_course($cdom,$cnum)) {
                   8039:             $homeserver = &homeserver($cnum,$cdom);
                   8040:         } else {
                   8041:             $homeserver = &domain($cdom,'primary');
                   8042:         }
                   8043:         if ($homeserver ne 'no_host') {
                   8044:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8045:         }
1.876     raeburn  8046:     }
1.506     raeburn  8047:     return $response;
                   8048: }
1.776     albertel 8049: 
1.506     raeburn  8050: sub auto_get_sections {
1.508     raeburn  8051:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8052:     my $homeserver;
                   8053:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8054:         $homeserver = &homeserver($cnum,$cdom);
                   8055:     }
                   8056:     if (!defined($homeserver)) { 
                   8057:         if ($cdom =~ /^$match_domain$/) {
                   8058:             $homeserver = &domain($cdom,'primary');
                   8059:         }
                   8060:     }
                   8061:     my @secs;
                   8062:     if (defined($homeserver)) {
                   8063:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8064:         unless ($response eq 'refused') {
                   8065:             @secs = split(/:/,$response);
                   8066:         }
1.506     raeburn  8067:     }
                   8068:     return @secs;
                   8069: }
1.776     albertel 8070: 
1.506     raeburn  8071: sub auto_new_course {
1.1099    raeburn  8072:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8073:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8074:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8075:     return $response;
                   8076: }
1.776     albertel 8077: 
1.506     raeburn  8078: sub auto_validate_courseID {
1.508     raeburn  8079:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8080:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8081:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8082:     return $response;
                   8083: }
1.776     albertel 8084: 
1.1007    raeburn  8085: sub auto_validate_instcode {
1.1020    raeburn  8086:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8087:     my ($homeserver,$response);
                   8088:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8089:         $homeserver = &homeserver($cnum,$cdom);
                   8090:     }
                   8091:     if (!defined($homeserver)) {
                   8092:         if ($cdom =~ /^$match_domain$/) {
                   8093:             $homeserver = &domain($cdom,'primary');
                   8094:         }
                   8095:     }
1.1065    raeburn  8096:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8097:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  8098:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8099:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8100: }
                   8101: 
1.506     raeburn  8102: sub auto_create_password {
1.873     raeburn  8103:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8104:     my ($homeserver,$response);
1.506     raeburn  8105:     my $create_passwd = 0;
                   8106:     my $authchk = '';
1.873     raeburn  8107:     if ($udom =~ /^$match_domain$/) {
                   8108:         $homeserver = &domain($udom,'primary');
                   8109:     }
                   8110:     if ($homeserver eq '') {
                   8111:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8112:             $homeserver = &homeserver($cnum,$cdom);
                   8113:         }
                   8114:     }
                   8115:     if ($homeserver eq '') {
                   8116:         $authchk = 'nodomain';
1.506     raeburn  8117:     } else {
1.873     raeburn  8118:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8119:         if ($response eq 'refused') {
                   8120:             $authchk = 'refused';
                   8121:         } else {
1.901     albertel 8122:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8123:         }
1.506     raeburn  8124:     }
                   8125:     return ($authparam,$create_passwd,$authchk);
                   8126: }
                   8127: 
1.706     raeburn  8128: sub auto_photo_permission {
                   8129:     my ($cnum,$cdom,$students) = @_;
                   8130:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8131:     my ($outcome,$perm_reqd,$conditions) = 
                   8132: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8133:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8134: 	return (undef,undef);
                   8135:     }
1.706     raeburn  8136:     return ($outcome,$perm_reqd,$conditions);
                   8137: }
                   8138: 
                   8139: sub auto_checkphotos {
                   8140:     my ($uname,$udom,$pid) = @_;
                   8141:     my $homeserver = &homeserver($uname,$udom);
                   8142:     my ($result,$resulttype);
                   8143:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8144: 				   &escape($uname).':'.&escape($pid),
                   8145: 				   $homeserver));
1.709     albertel 8146:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8147: 	return (undef,undef);
                   8148:     }
1.706     raeburn  8149:     if ($outcome) {
                   8150:         ($result,$resulttype) = split(/:/,$outcome);
                   8151:     } 
                   8152:     return ($result,$resulttype);
                   8153: }
                   8154: 
                   8155: sub auto_photochoice {
                   8156:     my ($cnum,$cdom) = @_;
                   8157:     my $homeserver = &homeserver($cnum,$cdom);
                   8158:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8159: 						       &escape($cdom),
                   8160: 						       $homeserver)));
1.709     albertel 8161:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8162: 	return (undef,undef);
                   8163:     }
1.706     raeburn  8164:     return ($update,$comment);
                   8165: }
                   8166: 
                   8167: sub auto_photoupdate {
                   8168:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8169:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8170:     my $host=&hostname($homeserver);
1.706     raeburn  8171:     my $cmd = '';
                   8172:     my $maxtries = 1;
1.800     albertel 8173:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8174:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8175:     }
                   8176:     $cmd =~ s/%%$//;
                   8177:     $cmd = &escape($cmd);
                   8178:     my $query = 'institutionalphotos';
                   8179:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8180:     unless ($queryid=~/^\Q$host\E\_/) {
                   8181:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8182:         return 'error: '.$queryid;
                   8183:     }
                   8184:     my $reply = &get_query_reply($queryid);
                   8185:     my $tries = 1;
                   8186:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8187:         $reply = &get_query_reply($queryid);
                   8188:         $tries ++;
                   8189:     }
                   8190:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8191:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8192:     } else {
                   8193:         my @responses = split(/:/,$reply);
                   8194:         my $outcome = shift(@responses); 
                   8195:         foreach my $item (@responses) {
                   8196:             my ($key,$value) = split(/=/,$item);
                   8197:             $$photo{$key} = $value;
                   8198:         }
                   8199:         return $outcome;
                   8200:     }
                   8201:     return 'error';
                   8202: }
                   8203: 
1.521     raeburn  8204: sub auto_instcode_format {
1.793     albertel 8205:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8206: 	$cat_order) = @_;
1.521     raeburn  8207:     my $courses = '';
1.772     raeburn  8208:     my @homeservers;
1.521     raeburn  8209:     if ($caller eq 'global') {
1.841     albertel 8210: 	my %servers = &get_servers($codedom,'library');
                   8211: 	foreach my $tryserver (keys(%servers)) {
                   8212: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8213: 		push(@homeservers,$tryserver);
                   8214: 	    }
1.584     raeburn  8215:         }
1.1022    raeburn  8216:     } elsif ($caller eq 'requests') {
                   8217:         if ($codedom =~ /^$match_domain$/) {
                   8218:             my $chome = &domain($codedom,'primary');
                   8219:             unless ($chome eq 'no_host') {
                   8220:                 push(@homeservers,$chome);
                   8221:             }
                   8222:         }
1.521     raeburn  8223:     } else {
1.772     raeburn  8224:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8225:     }
1.793     albertel 8226:     foreach my $code (keys(%{$instcodes})) {
                   8227:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8228:     }
                   8229:     chop($courses);
1.772     raeburn  8230:     my $ok_response = 0;
                   8231:     my $response;
                   8232:     while (@homeservers > 0 && $ok_response == 0) {
                   8233:         my $server = shift(@homeservers); 
                   8234:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8235:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8236:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8237: 		split(/:/,$response);
1.772     raeburn  8238:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8239:             push(@{$codetitles},&str2array($codetitles_str));
                   8240:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8241:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8242:             $ok_response = 1;
                   8243:         }
                   8244:     }
                   8245:     if ($ok_response) {
1.521     raeburn  8246:         return 'ok';
1.772     raeburn  8247:     } else {
                   8248:         return $response;
1.521     raeburn  8249:     }
                   8250: }
                   8251: 
1.792     raeburn  8252: sub auto_instcode_defaults {
                   8253:     my ($domain,$returnhash,$code_order) = @_;
                   8254:     my @homeservers;
1.841     albertel 8255: 
                   8256:     my %servers = &get_servers($domain,'library');
                   8257:     foreach my $tryserver (keys(%servers)) {
                   8258: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8259: 	    push(@homeservers,$tryserver);
                   8260: 	}
1.792     raeburn  8261:     }
1.841     albertel 8262: 
1.792     raeburn  8263:     my $response;
1.841     albertel 8264:     foreach my $server (@homeservers) {
1.792     raeburn  8265:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8266:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8267: 	
                   8268: 	foreach my $pair (split(/\&/,$response)) {
                   8269: 	    my ($name,$value)=split(/\=/,$pair);
                   8270: 	    if ($name eq 'code_order') {
                   8271: 		@{$code_order} = split(/\&/,&unescape($value));
                   8272: 	    } else {
                   8273: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8274: 	    }
                   8275: 	}
                   8276: 	return 'ok';
1.792     raeburn  8277:     }
1.841     albertel 8278: 
                   8279:     return $response;
1.1003    raeburn  8280: }
                   8281: 
                   8282: sub auto_possible_instcodes {
1.1007    raeburn  8283:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8284:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8285:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8286:         return;
                   8287:     }
1.1003    raeburn  8288:     my (@homeservers,$uhome);
                   8289:     if (defined(&domain($domain,'primary'))) {
                   8290:         $uhome=&domain($domain,'primary');
                   8291:         push(@homeservers,&domain($domain,'primary'));
                   8292:     } else {
                   8293:         my %servers = &get_servers($domain,'library');
                   8294:         foreach my $tryserver (keys(%servers)) {
                   8295:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8296:                 push(@homeservers,$tryserver);
                   8297:             }
                   8298:         }
                   8299:     }
                   8300:     my $response;
                   8301:     foreach my $server (@homeservers) {
                   8302:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8303:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8304:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8305:             split(':',$response);
                   8306:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8307:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8308:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8309:             my ($name,$value)=split('=',$item);
                   8310:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8311:         }
                   8312:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8313:             my ($name,$value)=split('=',$item);
                   8314:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8315:         }
                   8316:         return 'ok';
                   8317:     }
                   8318:     return $response;
                   8319: }
1.792     raeburn  8320: 
1.1010    raeburn  8321: sub auto_courserequest_checks {
                   8322:     my ($dom) = @_;
1.1020    raeburn  8323:     my ($homeserver,%validations);
                   8324:     if ($dom =~ /^$match_domain$/) {
                   8325:         $homeserver = &domain($dom,'primary');
                   8326:     }
                   8327:     unless ($homeserver eq 'no_host') {
                   8328:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8329:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8330:             my @items = split(/&/,$response);
                   8331:             foreach my $item (@items) {
                   8332:                 my ($key,$value) = split('=',$item);
                   8333:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8334:             }
                   8335:         }
                   8336:     }
1.1010    raeburn  8337:     return %validations; 
                   8338: }
                   8339: 
1.1020    raeburn  8340: sub auto_courserequest_validation {
1.1255    raeburn  8341:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8342:     my ($homeserver,$response);
                   8343:     if ($dom =~ /^$match_domain$/) {
                   8344:         $homeserver = &domain($dom,'primary');
                   8345:     }
1.1255    raeburn  8346:     unless ($homeserver eq 'no_host') {
                   8347:         my $customdata;
                   8348:         if (ref($custominfo) eq 'HASH') {
                   8349:             $customdata = &freeze_escape($custominfo);
                   8350:         }
1.1020    raeburn  8351:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8352:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  8353:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8354:                                     $customdata,$homeserver));
1.1020    raeburn  8355:     }
                   8356:     return $response;
                   8357: }
                   8358: 
1.777     albertel 8359: sub auto_validate_class_sec {
1.918     raeburn  8360:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8361:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8362:     my $ownerlist;
                   8363:     if (ref($owners) eq 'ARRAY') {
                   8364:         $ownerlist = join(',',@{$owners});
                   8365:     } else {
                   8366:         $ownerlist = $owners;
                   8367:     }
1.773     raeburn  8368:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8369:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8370:     return $response;
                   8371: }
                   8372: 
1.1248    raeburn  8373: sub auto_crsreq_update {
                   8374:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  8375:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  8376:     my ($homeserver,%crsreqresponse);
                   8377:     if ($cdom =~ /^$match_domain$/) {
                   8378:         $homeserver = &domain($cdom,'primary');
                   8379:     }
                   8380:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8381:         my $info;
                   8382:         if (ref($inbound) eq 'HASH') {
                   8383:             $info = &freeze_escape($inbound);
                   8384:         }
                   8385:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8386:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8387:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  8388:                             &escape($title).':'.&escape($code).':'.
                   8389:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   8390:                             $homeserver);
1.1248    raeburn  8391:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8392:             my @items = split(/&/,$response);
                   8393:             foreach my $item (@items) {
                   8394:                 my ($key,$value) = split('=',$item);
                   8395:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8396:             }
                   8397:         }
                   8398:     }
                   8399:     return \%crsreqresponse;
                   8400: }
                   8401: 
1.1305    raeburn  8402: sub auto_export_grades {
1.1309    raeburn  8403:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   8404:     my ($homeserver,%exportresponse);
                   8405:     if ($cdom =~ /^$match_domain$/) {
                   8406:         $homeserver = &domain($cdom,'primary');
                   8407:     }
                   8408:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8409:         my $info;
                   8410:         if (ref($inforef) eq 'HASH') {
                   8411:             $info = &freeze_escape($inforef);
                   8412:         }
                   8413:         if (ref($gradesref) eq 'HASH') {
                   8414:             my $grades = &freeze_escape($gradesref);
                   8415:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   8416:                                 $info.':'.$grades,$homeserver);
                   8417:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   8418:                 my @items = split(/&/,$response);
                   8419:                 foreach my $item (@items) {
                   8420:                     my ($key,$value) = split('=',$item);
                   8421:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   8422:                 }
                   8423:             }
                   8424:         }
                   8425:     }
                   8426:     return \%exportresponse;
1.1305    raeburn  8427: }
                   8428: 
1.1287    raeburn  8429: sub check_instcode_cloning {
                   8430:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   8431:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8432:         return;
                   8433:     }
                   8434:     my $canclone;
                   8435:     if (@{$code_order} > 0) {
                   8436:         my $instcoderegexp ='^';
                   8437:         my @clonecodes = split(/\&/,$cloner);
                   8438:         foreach my $item (@{$code_order}) {
                   8439:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   8440:                 foreach my $pair (@clonecodes) {
                   8441:                     my ($key,$val) = split(/\=/,$pair,2);
                   8442:                     $val = &unescape($val);
                   8443:                     if ($key eq $item) {
                   8444:                         $instcoderegexp .= '('.$val.')';
                   8445:                         last;
                   8446:                     }
                   8447:                 }
                   8448:             } else {
                   8449:                 $instcoderegexp .= $codedefaults->{$item};
                   8450:             }
                   8451:         }
                   8452:         $instcoderegexp .= '$';
                   8453:         my (@from,@to);
                   8454:         eval {
                   8455:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8456:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8457:         };
                   8458:         if ((@from > 0) && (@to > 0)) {
                   8459:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8460:             if (!@diffs) {
                   8461:                 $canclone = 1;
                   8462:             }
                   8463:         }
                   8464:     }
                   8465:     return $canclone;
                   8466: }
                   8467: 
                   8468: sub default_instcode_cloning {
                   8469:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   8470:     my (%codedefaults,@code_order,$canclone);
                   8471:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   8472:         %codedefaults = %{$codedefaultsref};
                   8473:         @code_order = @{$codeorderref};
                   8474:     } elsif ($clonedom) {
                   8475:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   8476:     }
                   8477:     if (($domdefclone) && (@code_order)) {
                   8478:         my @clonecodes = split(/\+/,$domdefclone);
                   8479:         my $instcoderegexp ='^';
                   8480:         foreach my $item (@code_order) {
                   8481:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   8482:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   8483:             } else {
                   8484:                 $instcoderegexp .= $codedefaults{$item};
                   8485:             }
                   8486:         }
                   8487:         $instcoderegexp .= '$';
                   8488:         my (@from,@to);
                   8489:         eval {
                   8490:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8491:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8492:         };
                   8493:         if ((@from > 0) && (@to > 0)) {
                   8494:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8495:             if (!@diffs) {
                   8496:                 $canclone = 1;
                   8497:             }
                   8498:         }
                   8499:     }
                   8500:     return $canclone;
                   8501: }
                   8502: 
1.679     raeburn  8503: # ------------------------------------------------------- Course Group routines
                   8504: 
                   8505: sub get_coursegroups {
1.809     raeburn  8506:     my ($cdom,$cnum,$group,$namespace) = @_;
                   8507:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  8508: }
                   8509: 
1.679     raeburn  8510: sub modify_coursegroup {
                   8511:     my ($cdom,$cnum,$groupsettings) = @_;
                   8512:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   8513: }
                   8514: 
1.809     raeburn  8515: sub toggle_coursegroup_status {
                   8516:     my ($cdom,$cnum,$group,$action) = @_;
                   8517:     my ($from_namespace,$to_namespace);
                   8518:     if ($action eq 'delete') {
                   8519:         $from_namespace = 'coursegroups';
                   8520:         $to_namespace = 'deleted_groups';
                   8521:     } else {
                   8522:         $from_namespace = 'deleted_groups';
                   8523:         $to_namespace = 'coursegroups';
                   8524:     }
                   8525:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  8526:     if (my $tmp = &error(%curr_group)) {
                   8527:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   8528:         return ('read error',$tmp);
                   8529:     } else {
                   8530:         my %savedsettings = %curr_group; 
1.809     raeburn  8531:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  8532:         my $deloutcome;
                   8533:         if ($result eq 'ok') {
1.809     raeburn  8534:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  8535:         } else {
                   8536:             return ('write error',$result);
                   8537:         }
                   8538:         if ($deloutcome eq 'ok') {
                   8539:             return 'ok';
                   8540:         } else {
                   8541:             return ('delete error',$deloutcome);
                   8542:         }
                   8543:     }
                   8544: }
                   8545: 
1.679     raeburn  8546: sub modify_group_roles {
1.957     raeburn  8547:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  8548:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   8549:     my $role = 'gr/'.&escape($userprivs);
                   8550:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  8551:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  8552:     if ($result eq 'ok') {
                   8553:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   8554:     }
1.679     raeburn  8555:     return $result;
                   8556: }
                   8557: 
                   8558: sub modify_coursegroup_membership {
                   8559:     my ($cdom,$cnum,$membership) = @_;
                   8560:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   8561:     return $result;
                   8562: }
                   8563: 
1.682     raeburn  8564: sub get_active_groups {
                   8565:     my ($udom,$uname,$cdom,$cnum) = @_;
                   8566:     my $now = time;
                   8567:     my %groups = ();
                   8568:     foreach my $key (keys(%env)) {
1.811     albertel 8569:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  8570:             my ($start,$end) = split(/\./,$env{$key});
                   8571:             if (($end!=0) && ($end<$now)) { next; }
                   8572:             if (($start!=0) && ($start>$now)) { next; }
                   8573:             if ($1 eq $cdom && $2 eq $cnum) {
                   8574:                 $groups{$3} = $env{$key} ;
                   8575:             }
                   8576:         }
                   8577:     }
                   8578:     return %groups;
                   8579: }
                   8580: 
1.683     raeburn  8581: sub get_group_membership {
                   8582:     my ($cdom,$cnum,$group) = @_;
                   8583:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   8584: }
                   8585: 
                   8586: sub get_users_groups {
                   8587:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  8588:     my @usersgroups;
1.683     raeburn  8589:     my $cachetime=1800;
                   8590: 
                   8591:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  8592:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   8593:     if (defined($cached)) {
1.734     albertel 8594:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  8595:     } else {  
                   8596:         $grouplist = '';
1.816     raeburn  8597:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  8598:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  8599:         my $access_end = $env{'course.'.$courseid.
                   8600:                               '.default_enrollment_end_date'};
                   8601:         my $now = time;
                   8602:         foreach my $key (keys(%roleshash)) {
                   8603:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   8604:                 my $group = $1;
                   8605:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   8606:                     my $start = $2;
                   8607:                     my $end = $1;
                   8608:                     if ($start == -1) { next; } # deleted from group
                   8609:                     if (($start!=0) && ($start>$now)) { next; }
                   8610:                     if (($end!=0) && ($end<$now)) {
                   8611:                         if ($access_end && $access_end < $now) {
                   8612:                             if ($access_end - $end < 86400) {
                   8613:                                 push(@usersgroups,$group);
1.733     raeburn  8614:                             }
                   8615:                         }
1.817     raeburn  8616:                         next;
1.733     raeburn  8617:                     }
1.817     raeburn  8618:                     push(@usersgroups,$group);
1.683     raeburn  8619:                 }
                   8620:             }
                   8621:         }
1.817     raeburn  8622:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8623:         $grouplist = join(':',@usersgroups);
                   8624:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8625:     }
1.733     raeburn  8626:     return @usersgroups;
1.683     raeburn  8627: }
                   8628: 
                   8629: sub devalidate_getgroups_cache {
                   8630:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8631:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8632: 
1.683     raeburn  8633:     my $hashid="$udom:$uname:$courseid";
                   8634:     &devalidate_cache_new('getgroups',$hashid);
                   8635: }
                   8636: 
1.12      www      8637: # ------------------------------------------------------------------ Plain Text
                   8638: 
                   8639: sub plaintext {
1.988     raeburn  8640:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8641:     if ($short =~ m{^cr/}) {
1.758     albertel 8642: 	return (split('/',$short))[-1];
                   8643:     }
1.742     raeburn  8644:     if (!defined($cid)) {
                   8645:         $cid = $env{'request.course.id'};
                   8646:     }
                   8647:     my %rolenames = (
1.1008    raeburn  8648:                       Course    => 'std',
                   8649:                       Community => 'alt1',
1.1305    raeburn  8650:                       Placement => 'std',
1.742     raeburn  8651:                     );
1.1037    raeburn  8652:     if ($cid ne '') {
                   8653:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8654:             unless ($forcedefault) {
                   8655:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8656:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8657:                 return &Apache::lonlocal::mt($roletext);
                   8658:             }
                   8659:         }
                   8660:     }
                   8661:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8662:         (defined($rolenames{$type})) && 
                   8663:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8664:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8665:     } elsif ($cid ne '') {
                   8666:         my $crstype = $env{'course.'.$cid.'.type'};
                   8667:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8668:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8669:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8670:         }
1.742     raeburn  8671:     }
1.1037    raeburn  8672:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8673: }
                   8674: 
                   8675: # ----------------------------------------------------------------- Assign Role
                   8676: 
                   8677: sub assignrole {
1.957     raeburn  8678:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8679:         $context)=@_;
1.21      www      8680:     my $mrole;
                   8681:     if ($role =~ /^cr\//) {
1.393     www      8682:         my $cwosec=$url;
1.811     albertel 8683:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8684: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8685:            my $refused = 1;
                   8686:            if ($context eq 'requestcourses') {
                   8687:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8688:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8689:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8690:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8691:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8692:                            if ($crsenv{'internal.courseowner'} eq
                   8693:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8694:                                $refused = '';
                   8695:                            }
                   8696:                        }
                   8697:                    }
                   8698:                }
                   8699:            }
                   8700:            if ($refused) {
                   8701:                &logthis('Refused custom assignrole: '.
                   8702:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8703:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8704:                return 'refused';
                   8705:            }
1.104     www      8706:         }
1.21      www      8707:         $mrole='cr';
1.678     raeburn  8708:     } elsif ($role =~ /^gr\//) {
                   8709:         my $cwogrp=$url;
1.811     albertel 8710:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8711:         unless (&allowed('mdg',$cwogrp)) {
                   8712:             &logthis('Refused group assignrole: '.
                   8713:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   8714:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   8715:             return 'refused';
                   8716:         }
                   8717:         $mrole='gr';
1.21      www      8718:     } else {
1.82      www      8719:         my $cwosec=$url;
1.811     albertel 8720:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  8721:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   8722:             my $refused;
                   8723:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   8724:                 if (!(&allowed('c'.$role,$url))) {
                   8725:                     $refused = 1;
                   8726:                 }
                   8727:             } else {
                   8728:                 $refused = 1;
                   8729:             }
1.947     raeburn  8730:             if ($refused) {
1.1045    raeburn  8731:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8732:                 if (!$selfenroll && $context eq 'course') {
                   8733:                     my %crsenv;
                   8734:                     if ($role eq 'cc' || $role eq 'co') {
                   8735:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8736:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   8737:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   8738:                                 if ($crsenv{'internal.courseowner'} eq 
                   8739:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8740:                                     $refused = '';
                   8741:                                 }
                   8742:                             }
                   8743:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   8744:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   8745:                                 if ($crsenv{'internal.courseowner'} eq 
                   8746:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8747:                                     $refused = '';
                   8748:                                 }
                   8749:                             }
                   8750:                         }
                   8751:                     }
                   8752:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8753:                     $refused = '';
1.1017    raeburn  8754:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8755:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8756:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8757:                         my $wrongcc;
                   8758:                         if ($cnum =~ /^$match_community$/) {
                   8759:                             $wrongcc = 1 if ($role eq 'cc');
                   8760:                         } else {
                   8761:                             $wrongcc = 1 if ($role eq 'co');
                   8762:                         }
                   8763:                         unless ($wrongcc) {
                   8764:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8765:                             if ($crsenv{'internal.courseowner'} eq 
                   8766:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8767:                                 $refused = '';
                   8768:                             }
1.1017    raeburn  8769:                         }
                   8770:                     }
1.1183    raeburn  8771:                 } elsif ($context eq 'requestauthor') {
                   8772:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   8773:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8774:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8775:                             $refused = '';
                   8776:                         } else {
                   8777:                             my %domdefaults = &get_domain_defaults($udom);
                   8778:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   8779:                                 my $checkbystatus;
                   8780:                                 if ($env{'user.adv'}) { 
                   8781:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8782:                                     if ($disposition eq 'automatic') {
                   8783:                                         $refused = '';
                   8784:                                     } elsif ($disposition eq '') {
                   8785:                                         $checkbystatus = 1;
                   8786:                                     } 
                   8787:                                 } else {
                   8788:                                     $checkbystatus = 1;
                   8789:                                 }
                   8790:                                 if ($checkbystatus) {
                   8791:                                     if ($env{'environment.inststatus'}) {
                   8792:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8793:                                         foreach my $type (@inststatuses) {
                   8794:                                             if (($type ne '') &&
                   8795:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   8796:                                                 $refused = '';
                   8797:                                             }
                   8798:                                         }
                   8799:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8800:                                         $refused = '';
                   8801:                                     }
                   8802:                                 }
                   8803:                             }
                   8804:                         }
                   8805:                     }
1.1017    raeburn  8806:                 }
                   8807:                 if ($refused) {
1.947     raeburn  8808:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8809:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8810: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8811:                     return 'refused';
                   8812:                 }
1.932     raeburn  8813:             }
1.1131    raeburn  8814:         } elsif ($role eq 'au') {
                   8815:             if ($url ne '/'.$udom.'/') {
                   8816:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8817:                          ' to assign author role for '.$uname.':'.$udom.
                   8818:                          ' in domain: '.$url.' refused (wrong domain).');
                   8819:                 return 'refused';
                   8820:             }
1.104     www      8821:         }
1.21      www      8822:         $mrole=$role;
                   8823:     }
1.620     albertel 8824:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8825:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8826:     if ($end) { $command.='_'.$end; }
1.21      www      8827:     if ($start) {
                   8828: 	if ($end) { 
1.81      www      8829:            $command.='_'.$start; 
1.21      www      8830:         } else {
1.81      www      8831:            $command.='_0_'.$start;
1.21      www      8832:         }
                   8833:     }
1.739     raeburn  8834:     my $origstart = $start;
                   8835:     my $origend = $end;
1.957     raeburn  8836:     my $delflag;
1.357     www      8837: # actually delete
                   8838:     if ($deleteflag) {
1.373     www      8839: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8840: # modify command to delete the role
1.620     albertel 8841:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8842:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8843: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8844: # set start and finish to negative values for userrolelog
                   8845:            $start=-1;
                   8846:            $end=-1;
1.957     raeburn  8847:            $delflag = 1;
1.357     www      8848:         }
                   8849:     }
                   8850: # send command
1.349     www      8851:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8852: # log new user role if status is ok
1.349     www      8853:     if ($answer eq 'ok') {
1.663     raeburn  8854: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  8855:         if (($role eq 'cc') || ($role eq 'in') ||
                   8856:             ($role eq 'ep') || ($role eq 'ad') ||
                   8857:             ($role eq 'ta') || ($role eq 'st') ||
                   8858:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8859:             ($role eq 'co')) {
1.1200    raeburn  8860: # for course roles, perform group memberships changes triggered by role change.
                   8861:             unless ($role =~ /^gr/) {
                   8862:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8863:                                                  $origstart,$selfenroll,$context);
                   8864:             }
1.1184    raeburn  8865:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8866:                            $selfenroll,$context);
                   8867:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8868:                  ($role eq 'au') || ($role eq 'dc')) {
                   8869:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8870:                            $context);
                   8871:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8872:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8873:                              $context); 
                   8874:         }
1.1053    raeburn  8875:         if ($role eq 'cc') {
                   8876:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8877:         }
1.349     www      8878:     }
                   8879:     return $answer;
1.169     harris41 8880: }
                   8881: 
1.1053    raeburn  8882: sub autoupdate_coowners {
                   8883:     my ($url,$end,$start,$uname,$udom) = @_;
                   8884:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8885:     if (($cdom ne '') && ($cnum ne '')) {
                   8886:         my $now = time;
                   8887:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8888:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8889:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8890:             my $instcode = $coursehash{'internal.coursecode'};
                   8891:             if ($instcode ne '') {
1.1056    raeburn  8892:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8893:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8894:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8895:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8896:                         if ($result eq 'valid') {
                   8897:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8898:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8899:                                     push(@newcoowners,$coowner);
                   8900:                                 }
                   8901:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8902:                                     push(@newcoowners,$uname.':'.$udom);
                   8903:                                 }
                   8904:                                 @newcoowners = sort(@newcoowners);
                   8905:                             } else {
                   8906:                                 push(@newcoowners,$uname.':'.$udom);
                   8907:                             }
                   8908:                         } else {
                   8909:                             if ($coursehash{'internal.co-owners'}) {
                   8910:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8911:                                     unless ($coowner eq $uname.':'.$udom) {
                   8912:                                         push(@newcoowners,$coowner);
                   8913:                                     }
                   8914:                                 }
                   8915:                                 unless (@newcoowners > 0) {
                   8916:                                     $delcoowners = 1;
                   8917:                                     $coowners = '';
                   8918:                                 }
                   8919:                             }
                   8920:                         }
                   8921:                         if (@newcoowners || $delcoowners) {
                   8922:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8923:                                             $delcoowners,@newcoowners);
                   8924:                         }
                   8925:                     }
                   8926:                 }
                   8927:             }
                   8928:         }
                   8929:     }
                   8930: }
                   8931: 
                   8932: sub store_coowners {
                   8933:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8934:     my $cid = $cdom.'_'.$cnum;
                   8935:     my ($coowners,$delresult,$putresult);
                   8936:     if (@newcoowners) {
                   8937:         $coowners = join(',',@newcoowners);
                   8938:         my %coownershash = (
                   8939:                             'internal.co-owners' => $coowners,
                   8940:                            );
                   8941:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8942:         if ($putresult eq 'ok') {
                   8943:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8944:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8945:             }
                   8946:         }
                   8947:     }
                   8948:     if ($delcoowners) {
                   8949:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8950:         if ($delresult eq 'ok') {
                   8951:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8952:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8953:             }
                   8954:         }
                   8955:     }
                   8956:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8957:         my %crsinfo =
                   8958:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8959:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8960:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8961:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8962:         }
                   8963:     }
                   8964: }
                   8965: 
1.169     harris41 8966: # -------------------------------------------------- Modify user authentication
1.197     www      8967: # Overrides without validation
                   8968: 
1.169     harris41 8969: sub modifyuserauth {
                   8970:     my ($udom,$uname,$umode,$upass)=@_;
                   8971:     my $uhome=&homeserver($uname,$udom);
1.197     www      8972:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8973:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8974:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8975:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8976:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8977: 		     &escape($upass),$uhome);
1.620     albertel 8978:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8979:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8980:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8981:     &log($udom,,$uname,$uhome,
1.620     albertel 8982:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8983:                                      $env{'user.name'}.', '.$umode.
1.197     www      8984:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8985:     unless ($reply eq 'ok') {
1.197     www      8986:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8987: 	return 'error: '.$reply;
                   8988:     }   
1.170     harris41 8989:     return 'ok';
1.80      www      8990: }
                   8991: 
1.81      www      8992: # --------------------------------------------------------------- Modify a user
1.80      www      8993: 
1.81      www      8994: sub modifyuser {
1.206     matthew  8995:     my ($udom,    $uname, $uid,
                   8996:         $umode,   $upass, $first,
                   8997:         $middle,  $last,  $gene,
1.1058    raeburn  8998:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8999:     $udom= &LONCAPA::clean_domain($udom);
                   9000:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9001:     my $showcandelete = 'none';
                   9002:     if (ref($candelete) eq 'ARRAY') {
                   9003:         if (@{$candelete} > 0) {
                   9004:             $showcandelete = join(', ',@{$candelete});
                   9005:         }
                   9006:     }
1.81      www      9007:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9008:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9009: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9010:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9011:                                      ' desiredhome not specified'). 
1.620     albertel 9012:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9013:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9014:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9015:     my $newuser;
                   9016:     if ($uhome eq 'no_host') {
                   9017:         $newuser = 1;
                   9018:     }
1.80      www      9019: # ----------------------------------------------------------------- Create User
1.406     albertel 9020:     if (($uhome eq 'no_host') && 
                   9021: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      9022:         my $unhome='';
1.844     albertel 9023:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9024:             $unhome = $desiredhome;
1.620     albertel 9025: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9026: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9027:         } else { # load balancing routine for determining $unhome
1.81      www      9028:             my $loadm=10000000;
1.841     albertel 9029: 	    my %servers = &get_servers($udom,'library');
                   9030: 	    foreach my $tryserver (keys(%servers)) {
                   9031: 		my $answer=reply('load',$tryserver);
                   9032: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9033: 		    $loadm=$answer;
                   9034: 		    $unhome=$tryserver;
                   9035: 		}
1.80      www      9036: 	    }
                   9037:         }
                   9038:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9039: 	    return 'error: unable to find a home server for '.$uname.
                   9040:                    ' in domain '.$udom;
1.80      www      9041:         }
                   9042:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9043:                          &escape($upass),$unhome);
                   9044: 	unless ($reply eq 'ok') {
                   9045:             return 'error: '.$reply;
                   9046:         }   
1.230     stredwic 9047:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9048:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9049: 	    return 'error: unable verify users home machine.';
1.80      www      9050:         }
1.209     matthew  9051:     }   # End of creation of new user
1.80      www      9052: # ---------------------------------------------------------------------- Add ID
                   9053:     if ($uid) {
                   9054:        $uid=~tr/A-Z/a-z/;
                   9055:        my %uidhash=&idrget($udom,$uname);
1.196     www      9056:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9057:          && (!$forceid)) {
1.80      www      9058: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9059: 	      return 'error: user id "'.$uid.'" does not match '.
                   9060:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9061:           }
                   9062:        } else {
1.1300    raeburn  9063: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      9064:        }
                   9065:     }
                   9066: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9067:     my @tmp=&get('environment',
1.899     raeburn  9068: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9069:                     'permanentemail','inststatus'],
1.134     albertel 9070: 		   $udom,$uname);
1.1075    raeburn  9071:     my (%names,%oldnames);
1.313     matthew  9072:     if ($tmp[0] =~ m/^error:.*/) { 
                   9073:         %names=(); 
                   9074:     } else {
                   9075:         %names = @tmp;
1.1075    raeburn  9076:         %oldnames = %names;
1.313     matthew  9077:     }
1.388     www      9078: #
1.1058    raeburn  9079: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9080: # of users did not contain them), do not overwrite existing values
                   9081: # unless field is in $candelete array ref.  
                   9082: #
                   9083: 
                   9084:     my @fields = ('firstname','middlename','lastname','generation',
                   9085:                   'permanentemail','id');
                   9086:     my %newvalues;
                   9087:     if (ref($candelete) eq 'ARRAY') {
                   9088:         foreach my $field (@fields) {
                   9089:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9090:                 if ($field eq 'firstname') {
                   9091:                     $names{$field} = $first;
                   9092:                 } elsif ($field eq 'middlename') {
                   9093:                     $names{$field} = $middle;
                   9094:                 } elsif ($field eq 'lastname') {
                   9095:                     $names{$field} = $last;
                   9096:                 } elsif ($field eq 'generation') { 
                   9097:                     $names{$field} = $gene;
                   9098:                 } elsif ($field eq 'permanentemail') {
                   9099:                     $names{$field} = $email;
                   9100:                 } elsif ($field eq 'id') {
                   9101:                     $names{$field}  = $uid;
                   9102:                 }
                   9103:             }
                   9104:         }
                   9105:     }
1.388     www      9106:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9107:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9108:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9109:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9110:     if ($email) {
                   9111:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9112:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9113:     }
1.899     raeburn  9114:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9115:     if (defined($inststatus)) {
                   9116:         $names{'inststatus'} = '';
                   9117:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9118:         if (ref($usertypes) eq 'HASH') {
                   9119:             my @okstatuses; 
                   9120:             foreach my $item (split(/:/,$inststatus)) {
                   9121:                 if (defined($usertypes->{$item})) {
                   9122:                     push(@okstatuses,$item);  
                   9123:                 }
                   9124:             }
                   9125:             if (@okstatuses) {
                   9126:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9127:             }
                   9128:         }
                   9129:     }
1.1075    raeburn  9130:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9131:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9132:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9133:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9134:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9135:     } else {
                   9136:         $logmsg .= ' during self creation';
                   9137:     }
1.1075    raeburn  9138:     my $changed;
                   9139:     if ($newuser) {
                   9140:         $changed = 1;
                   9141:     } else {
                   9142:         foreach my $field (@fields) {
                   9143:             if ($names{$field} ne $oldnames{$field}) {
                   9144:                 $changed = 1;
                   9145:                 last;
                   9146:             }
                   9147:         }
                   9148:     }
                   9149:     unless ($changed) {
                   9150:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9151:         &logthis($logmsg);
                   9152:         return 'ok';
                   9153:     }
                   9154:     my $reply = &put('environment', \%names, $udom,$uname);
                   9155:     if ($reply ne 'ok') { 
                   9156:         return 'error: '.$reply;
                   9157:     }
1.1087    raeburn  9158:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9159:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9160:     }
1.1075    raeburn  9161:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9162:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9163:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9164:     &logthis($logmsg);
1.134     albertel 9165:     return 'ok';
1.80      www      9166: }
                   9167: 
1.81      www      9168: # -------------------------------------------------------------- Modify student
1.80      www      9169: 
1.81      www      9170: sub modifystudent {
                   9171:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9172:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314    raeburn  9173:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9174:     if (!$cid) {
1.620     albertel 9175: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9176: 	    return 'not_in_class';
                   9177: 	}
1.80      www      9178:     }
                   9179: # --------------------------------------------------------------- Make the user
1.81      www      9180:     my $reply=&modifyuser
1.209     matthew  9181: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9182:          $desiredhome,$email,$inststatus);
1.80      www      9183:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9184:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  9185:     # student's environment
1.297     matthew  9186:     $uid = undef if (!$forceid);
1.455     albertel 9187:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  9188:                                         $gene,$usec,$end,$start,$type,$locktype,
1.1314    raeburn  9189:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9190:     return $reply;
                   9191: }
                   9192: 
                   9193: sub modify_student_enrollment {
1.1216    raeburn  9194:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314    raeburn  9195:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9196:     my ($cdom,$cnum,$chome);
                   9197:     if (!$cid) {
1.620     albertel 9198: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9199: 	    return 'not_in_class';
                   9200: 	}
1.620     albertel 9201: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9202: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9203:     } else {
                   9204: 	($cdom,$cnum)=split(/_/,$cid);
                   9205:     }
1.620     albertel 9206:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9207:     if (!$chome) {
1.457     raeburn  9208: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9209:     }
1.455     albertel 9210:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9211:     # Make sure the user exists
1.81      www      9212:     my $uhome=&homeserver($uname,$udom);
                   9213:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9214: 	return 'error: no such user';
                   9215:     }
1.297     matthew  9216:     # Get student data if we were not given enough information
                   9217:     if (!defined($first)  || $first  eq '' || 
                   9218:         !defined($last)   || $last   eq '' || 
                   9219:         !defined($uid)    || $uid    eq '' || 
                   9220:         !defined($middle) || $middle eq '' || 
                   9221:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9222:         # They did not supply us with enough data to enroll the student, so
                   9223:         # we need to pick up more information.
1.297     matthew  9224:         my %tmp = &get('environment',
1.294     matthew  9225:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9226:                        ,$udom,$uname);
                   9227: 
1.800     albertel 9228:         #foreach my $key (keys(%tmp)) {
                   9229:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9230:         #}
1.294     matthew  9231:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9232:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9233:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9234:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9235:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9236:     }
1.556     albertel 9237:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9238:     my $user = "$uname:$udom";
                   9239:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9240:     my $reply=cput('classlist',
1.1148    raeburn  9241: 		   {$user => 
1.1314    raeburn  9242: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 9243: 		   $cdom,$cnum);
1.1148    raeburn  9244:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9245:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9246:     } else { 
1.81      www      9247: 	return 'error: '.$reply;
                   9248:     }
1.297     matthew  9249:     # Add student role to user
1.83      www      9250:     my $uurl='/'.$cid;
1.81      www      9251:     $uurl=~s/\_/\//g;
                   9252:     if ($usec) {
                   9253: 	$uurl.='/'.$usec;
                   9254:     }
1.1148    raeburn  9255:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9256:                              $selfenroll,$context);
                   9257:     if ($result ne 'ok') {
                   9258:         if ($old_entry{$user} ne '') {
                   9259:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9260:         } else {
                   9261:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9262:         }
                   9263:     }
                   9264:     return $result; 
1.21      www      9265: }
                   9266: 
1.556     albertel 9267: sub format_name {
                   9268:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9269:     my $name;
                   9270:     if ($first ne 'lastname') {
                   9271: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9272:     } else {
                   9273: 	if ($lastname=~/\S/) {
                   9274: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9275: 	    $name=~s/\s+,/,/;
                   9276: 	} else {
                   9277: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9278: 	}
                   9279:     }
                   9280:     $name=~s/^\s+//;
                   9281:     $name=~s/\s+$//;
                   9282:     $name=~s/\s+/ /g;
                   9283:     return $name;
                   9284: }
                   9285: 
1.84      www      9286: # ------------------------------------------------- Write to course preferences
                   9287: 
                   9288: sub writecoursepref {
                   9289:     my ($courseid,%prefs)=@_;
                   9290:     $courseid=~s/^\///;
                   9291:     $courseid=~s/\_/\//g;
                   9292:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9293:     my $chome=homeserver($cnum,$cdomain);
                   9294:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9295: 	return 'error: no such course';
                   9296:     }
                   9297:     my $cstring='';
1.800     albertel 9298:     foreach my $pref (keys(%prefs)) {
                   9299: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9300:     }
1.84      www      9301:     $cstring=~s/\&$//;
                   9302:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9303: }
                   9304: 
                   9305: # ---------------------------------------------------------- Make/modify course
                   9306: 
                   9307: sub createcourse {
1.741     raeburn  9308:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  9309:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      9310:     $url=&declutter($url);
                   9311:     my $cid='';
1.1028    raeburn  9312:     if ($context eq 'requestcourses') {
                   9313:         my $can_create = 0;
                   9314:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9315:         if ($udom eq $ownerdom) {
                   9316:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   9317:                                   $context)) {
                   9318:                 $can_create = 1;
                   9319:             }
                   9320:         } else {
                   9321:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9322:                                            $category);
                   9323:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   9324:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   9325:                 if (@curr > 0) {
                   9326:                     my @options = qw(approval validate autolimit);
                   9327:                     my $optregex = join('|',@options);
                   9328:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   9329:                         $can_create = 1;
                   9330:                     }
                   9331:                 }
                   9332:             }
                   9333:         }
                   9334:         if ($can_create) {
                   9335:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   9336:                 unless (&allowed('ccc',$udom)) {
                   9337:                     return 'refused'; 
                   9338:                 }
1.1017    raeburn  9339:             }
                   9340:         } else {
                   9341:             return 'refused';
                   9342:         }
1.1028    raeburn  9343:     } elsif (!&allowed('ccc',$udom)) {
                   9344:         return 'refused';
1.84      www      9345:     }
1.1011    raeburn  9346: # --------------------------------------------------------------- Get Unique ID
                   9347:     my $uname;
                   9348:     if ($cnum =~ /^$match_courseid$/) {
                   9349:         my $chome=&homeserver($cnum,$udom,'true');
                   9350:         if (($chome eq '') || ($chome eq 'no_host')) {
                   9351:             $uname = $cnum;
                   9352:         } else {
1.1038    raeburn  9353:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9354:         }
                   9355:     } else {
1.1038    raeburn  9356:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9357:     }
                   9358:     return $uname if ($uname =~ /^error/);
                   9359: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  9360:     if (!defined($course_server)) {
                   9361:         if (defined(&domain($udom,'primary'))) {
                   9362:             $course_server = &domain($udom,'primary');
                   9363:         } else {
                   9364:             $course_server = $env{'user.home'}; 
                   9365:         }
                   9366:     }
                   9367:     my %host_servers =
                   9368:         &Apache::lonnet::get_servers($udom,'library');
                   9369:     unless ($host_servers{$course_server}) {
                   9370:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  9371:     }
1.84      www      9372: # ------------------------------------------------------------- Make the course
                   9373:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  9374:                       $course_server);
1.84      www      9375:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  9376:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      9377:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9378: 	return 'error: no such course';
                   9379:     }
1.271     www      9380: # ----------------------------------------------------------------- Course made
1.516     raeburn  9381: # log existence
1.1029    raeburn  9382:     my $now = time;
1.918     raeburn  9383:     my $newcourse = {
                   9384:                     $udom.'_'.$uname => {
1.921     raeburn  9385:                                      description => $description,
                   9386:                                      inst_code   => $inst_code,
                   9387:                                      owner       => $course_owner,
                   9388:                                      type        => $crstype,
1.1029    raeburn  9389:                                      creator     => $env{'user.name'}.':'.
                   9390:                                                     $env{'user.domain'},
                   9391:                                      created     => $now,
                   9392:                                      context     => $context,
1.918     raeburn  9393:                                                 },
                   9394:                     };
1.921     raeburn  9395:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      9396: # set toplevel url
1.271     www      9397:     my $topurl=$url;
                   9398:     unless ($nonstandard) {
                   9399: # ------------------------------------------ For standard courses, make top url
                   9400:         my $mapurl=&clutter($url);
1.278     www      9401:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 9402:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      9403: <map>
                   9404: <resource id="1" type="start"></resource>
                   9405: <resource id="2" src="$mapurl"></resource>
                   9406: <resource id="3" type="finish"></resource>
                   9407: <link index="1" from="1" to="2"></link>
                   9408: <link index="2" from="2" to="3"></link>
                   9409: </map>
                   9410: ENDINITMAP
                   9411:         $topurl=&declutter(
1.638     albertel 9412:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      9413:                           );
                   9414:     }
                   9415: # ----------------------------------------------------------- Write preferences
1.84      www      9416:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  9417:                      ('description'              => $description,
                   9418:                       'url'                      => $topurl,
                   9419:                       'internal.creator'         => $env{'user.name'}.':'.
                   9420:                                                     $env{'user.domain'},
                   9421:                       'internal.created'         => $now,
                   9422:                       'internal.creationcontext' => $context)
                   9423:                     );
1.84      www      9424:     return '/'.$udom.'/'.$uname;
                   9425: }
                   9426: 
1.1011    raeburn  9427: # ------------------------------------------------------------------- Create ID
                   9428: sub generate_coursenum {
1.1038    raeburn  9429:     my ($udom,$crstype) = @_;
1.1011    raeburn  9430:     my $domdesc = &domain($udom);
                   9431:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  9432:     my $first;
                   9433:     if ($crstype eq 'Community') {
                   9434:         $first = '0';
                   9435:     } else {
                   9436:         $first = int(1+rand(9)); 
                   9437:     } 
                   9438:     my $uname=$first.
1.1011    raeburn  9439:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9440:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9441:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9442: # ----------------------------------------------- Make sure that does not exist
                   9443:     my $uhome=&homeserver($uname,$udom,'true');
                   9444:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  9445:         if ($crstype eq 'Community') {
                   9446:             $first = '0';
                   9447:         } else {
                   9448:             $first = int(1+rand(9));
                   9449:         }
                   9450:         $uname=$first.
1.1011    raeburn  9451:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9452:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9453:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9454:         $uhome=&homeserver($uname,$udom,'true');
                   9455:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   9456:             return 'error: unable to generate unique course-ID';
                   9457:         }
                   9458:     }
                   9459:     return $uname;
                   9460: }
                   9461: 
1.813     albertel 9462: sub is_course {
1.1167    droeschl 9463:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   9464:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   9465: 
                   9466:     return unless $cdom and $cnum;
                   9467: 
                   9468:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   9469:         '.');
                   9470: 
1.1219    raeburn  9471:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 9472:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 9473: }
                   9474: 
1.1015    raeburn  9475: sub store_userdata {
                   9476:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  9477:     my $result;
1.1016    raeburn  9478:     if ($datakey ne '') {
1.1013    raeburn  9479:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  9480:             if ($udom eq '' || $uname eq '') {
                   9481:                 $udom = $env{'user.domain'};
                   9482:                 $uname = $env{'user.name'};
                   9483:             }
                   9484:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  9485:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   9486:                 $result = 'error: no_host';
                   9487:             } else {
                   9488:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   9489:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   9490: 
                   9491:                 my $namevalue='';
                   9492:                 foreach my $key (keys(%{$storehash})) {
                   9493:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   9494:                 }
                   9495:                 $namevalue=~s/\&$//;
1.1224    raeburn  9496:                 unless ($namespace eq 'courserequests') {
                   9497:                     $datakey = &escape($datakey);
                   9498:                 }
1.1105    raeburn  9499:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   9500:                                   $namevalue,$uhome);
1.1013    raeburn  9501:             }
                   9502:         } else {
                   9503:             $result = 'error: data to store was not a hash reference'; 
                   9504:         }
                   9505:     } else {
                   9506:         $result= 'error: invalid requestkey'; 
                   9507:     }
                   9508:     return $result;
                   9509: }
                   9510: 
1.21      www      9511: # ---------------------------------------------------------- Assign Custom Role
                   9512: 
                   9513: sub assigncustomrole {
1.957     raeburn  9514:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9515:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  9516:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      9517: }
                   9518: 
                   9519: # ----------------------------------------------------------------- Revoke Role
                   9520: 
                   9521: sub revokerole {
1.957     raeburn  9522:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9523:     my $now=time;
1.965     raeburn  9524:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      9525: }
                   9526: 
                   9527: # ---------------------------------------------------------- Revoke Custom Role
                   9528: 
                   9529: sub revokecustomrole {
1.957     raeburn  9530:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9531:     my $now=time;
1.357     www      9532:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  9533:            $deleteflag,$selfenroll,$context);
1.17      www      9534: }
                   9535: 
1.533     banghart 9536: # ------------------------------------------------------------ Disk usage
1.535     albertel 9537: sub diskusage {
1.955     raeburn  9538:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   9539:     $directorypath =~ s/\/$//;
                   9540:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   9541:                        .&escape($getpropath).':'.&escape($uname).':'
                   9542:                        .&escape($udom),homeserver($uname,$udom));
                   9543:     if ($listing eq 'unknown_cmd') {
                   9544:         if ($getpropath) {
                   9545:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   9546:         }
                   9547:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   9548:     }
1.514     albertel 9549:     return $listing;
1.512     banghart 9550: }
                   9551: 
1.566     banghart 9552: sub is_locked {
1.1096    raeburn  9553:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 9554:     my @check;
                   9555:     my $is_locked;
1.1093    raeburn  9556:     push (@check,$file_name);
1.613     albertel 9557:     my %locked = &get('file_permissions',\@check,
1.620     albertel 9558: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 9559:     my ($tmp)=keys(%locked);
                   9560:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  9561:     
1.566     banghart 9562:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  9563:         $is_locked = 'false';
                   9564:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  9565:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  9566:                $is_locked = 'true';
1.1096    raeburn  9567:                if (ref($which) eq 'ARRAY') {
                   9568:                    push(@{$which},$entry);
                   9569:                } else {
                   9570:                    last;
                   9571:                }
1.745     raeburn  9572:            }
                   9573:        }
1.566     banghart 9574:     } else {
                   9575:         $is_locked = 'false';
                   9576:     }
1.1093    raeburn  9577:     return $is_locked;
1.566     banghart 9578: }
                   9579: 
1.759     albertel 9580: sub declutter_portfile {
                   9581:     my ($file) = @_;
1.833     albertel 9582:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 9583:     return $file;
                   9584: }
                   9585: 
1.559     banghart 9586: # ------------------------------------------------------------- Mark as Read Only
                   9587: 
                   9588: sub mark_as_readonly {
                   9589:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 9590:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9591:     my ($tmp)=keys(%current_permissions);
                   9592:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 9593:     foreach my $file (@{$files}) {
1.759     albertel 9594: 	$file = &declutter_portfile($file);
1.561     banghart 9595:         push(@{$current_permissions{$file}},$what);
1.559     banghart 9596:     }
1.613     albertel 9597:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9598:     return;
                   9599: }
                   9600: 
1.572     banghart 9601: # ------------------------------------------------------------Save Selected Files
                   9602: 
                   9603: sub save_selected_files {
                   9604:     my ($user, $path, @files) = @_;
                   9605:     my $filename = $user."savedfiles";
1.573     banghart 9606:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 9607:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 9608:     foreach my $file (@files) {
1.620     albertel 9609:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 9610:     }
                   9611:     foreach my $file (@other_files) {
1.574     banghart 9612:         print (OUT $file."\n");
1.572     banghart 9613:     }
1.574     banghart 9614:     close (OUT);
1.572     banghart 9615:     return 'ok';
                   9616: }
                   9617: 
1.574     banghart 9618: sub clear_selected_files {
                   9619:     my ($user) = @_;
                   9620:     my $filename = $user."savedfiles";
1.1117    foxr     9621:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 9622:     print (OUT undef);
                   9623:     close (OUT);
                   9624:     return ("ok");    
                   9625: }
                   9626: 
1.572     banghart 9627: sub files_in_path {
                   9628:     my ($user, $path) = @_;
                   9629:     my $filename = $user."savedfiles";
                   9630:     my %return_files;
1.1117    foxr     9631:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 9632:     while (my $line_in = <IN>) {
1.574     banghart 9633:         chomp ($line_in);
                   9634:         my @paths_and_file = split (m!/!, $line_in);
                   9635:         my $file_part = pop (@paths_and_file);
                   9636:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9637:         $path_part.='/';
                   9638:         my $path_and_file = $path_part.$file_part;
                   9639:         if ($path_part eq $path) {
                   9640:             $return_files{$file_part}= 'selected';
                   9641:         }
                   9642:     }
1.574     banghart 9643:     close (IN);
                   9644:     return (\%return_files);
1.572     banghart 9645: }
                   9646: 
                   9647: # called in portfolio select mode, to show files selected NOT in current directory
                   9648: sub files_not_in_path {
                   9649:     my ($user, $path) = @_;
                   9650:     my $filename = $user."savedfiles";
                   9651:     my @return_files;
                   9652:     my $path_part;
1.1117    foxr     9653:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 9654:     while (my $line = <IN>) {
1.572     banghart 9655:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9656:         my @paths_and_file = split(m|/|, $line);
                   9657:         my $file_part = pop(@paths_and_file);
                   9658:         chomp($file_part);
                   9659:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9660:         $path_part .= '/';
                   9661:         my $path_and_file = $path_part.$file_part;
                   9662:         if ($path_part ne $path) {
1.800     albertel 9663:             push(@return_files, ($path_and_file));
1.572     banghart 9664:         }
                   9665:     }
1.800     albertel 9666:     close(OUT);
1.574     banghart 9667:     return (@return_files);
1.572     banghart 9668: }
                   9669: 
1.1273    raeburn  9670: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   9671:  
                   9672: sub portfiles_versioning {
                   9673:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   9674:     my $portfolio_root = '/userfiles/portfolio';
                   9675:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   9676:     foreach my $file (@{$portfiles}) {
                   9677:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   9678:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   9679:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   9680:         my $getpropath = 1;
                   9681:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   9682:                                              $stu_name,$getpropath);
                   9683:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   9684:         my $new_answer = 
                   9685:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   9686:         if ($new_answer ne 'problem getting file') {
                   9687:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   9688:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   9689:                               [$symb,$env{'request.course.id'},'graded']);
                   9690:         }
                   9691:     }
                   9692: }
                   9693: 
                   9694: sub get_next_version {
                   9695:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   9696:     my $version;
                   9697:     if (ref($dir_list) eq 'ARRAY') {
                   9698:         foreach my $row (@{$dir_list}) {
                   9699:             my ($file) = split(/\&/,$row,2);
                   9700:             my ($file_name,$file_version,$file_ext) =
                   9701:                 &file_name_version_ext($file);
                   9702:             if (($file_name eq $answer_name) &&
                   9703:                 ($file_ext eq $answer_ext)) {
                   9704:                      # gets here if filename and extension match,
                   9705:                      # regardless of version
                   9706:                 if ($file_version ne '') {
                   9707:                     # a versioned file is found  so save it for later
                   9708:                     if ($file_version > $version) {
                   9709:                         $version = $file_version;
                   9710:                     }
                   9711:                 }
                   9712:             }
                   9713:         }
                   9714:     }
                   9715:     $version ++;
                   9716:     return($version);
                   9717: }
                   9718: 
                   9719: sub version_selected_portfile {
                   9720:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   9721:     my ($answer_name,$answer_ver,$answer_ext) =
                   9722:         &file_name_version_ext($file_name);
                   9723:     my $new_answer;
                   9724:     $env{'form.copy'} =
                   9725:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   9726:     if($env{'form.copy'} eq '-1') {
                   9727:         $new_answer = 'problem getting file';
                   9728:     } else {
                   9729:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   9730:         my $copy_result = 
                   9731:             &finishuserfileupload($stu_name,$domain,'copy',
                   9732:                                   '/portfolio'.$directory.$new_answer);
                   9733:     }
                   9734:     undef($env{'form.copy'});
                   9735:     return ($new_answer);
                   9736: }
                   9737: 
                   9738: sub file_name_version_ext {
                   9739:     my ($file)=@_;
                   9740:     my @file_parts = split(/\./, $file);
                   9741:     my ($name,$version,$ext);
                   9742:     if (@file_parts > 1) {
                   9743:         $ext=pop(@file_parts);
                   9744:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   9745:             $version=pop(@file_parts);
                   9746:         }
                   9747:         $name=join('.',@file_parts);
                   9748:     } else {
                   9749:         $name=join('.',@file_parts);
                   9750:     }
                   9751:     return($name,$version,$ext);
                   9752: }
                   9753: 
1.745     raeburn  9754: #----------------------------------------------Get portfolio file permissions
1.629     banghart 9755: 
1.745     raeburn  9756: sub get_portfile_permissions {
                   9757:     my ($domain,$user) = @_;
1.613     albertel 9758:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9759:     my ($tmp)=keys(%current_permissions);
                   9760:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9761:     return \%current_permissions;
                   9762: }
                   9763: 
                   9764: #---------------------------------------------Get portfolio file access controls
                   9765: 
1.749     raeburn  9766: sub get_access_controls {
1.745     raeburn  9767:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 9768:     my %access;
                   9769:     my $real_file = $file;
                   9770:     $file =~ s/\.meta$//;
1.745     raeburn  9771:     if (defined($file)) {
1.749     raeburn  9772:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   9773:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 9774:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  9775:             }
                   9776:         }
1.745     raeburn  9777:     } else {
1.749     raeburn  9778:         foreach my $key (keys(%{$current_permissions})) {
                   9779:             if ($key =~ /\0accesscontrol$/) {
                   9780:                 if (defined($group)) {
                   9781:                     if ($key !~ m-^\Q$group\E/-) {
                   9782:                         next;
                   9783:                     }
                   9784:                 }
                   9785:                 my ($fullpath) = split(/\0/,$key);
                   9786:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   9787:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   9788:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   9789:                     }
                   9790:                 }
                   9791:             }
                   9792:         }
                   9793:     }
                   9794:     return %access;
                   9795: }
                   9796: 
                   9797: sub modify_access_controls {
                   9798:     my ($file_name,$changes,$domain,$user)=@_;
                   9799:     my ($outcome,$deloutcome);
                   9800:     my %store_permissions;
                   9801:     my %new_values;
                   9802:     my %new_control;
                   9803:     my %translation;
                   9804:     my @deletions = ();
                   9805:     my $now = time;
                   9806:     if (exists($$changes{'activate'})) {
                   9807:         if (ref($$changes{'activate'}) eq 'HASH') {
                   9808:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   9809:             my $numnew = scalar(@newitems);
                   9810:             for (my $i=0; $i<$numnew; $i++) {
                   9811:                 my $newkey = $newitems[$i];
                   9812:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  9813:                 if ($newkey =~ /^\d+:/) { 
                   9814:                     $newkey =~ s/^(\d+)/$newid/;
                   9815:                     $translation{$1} = $newid;
                   9816:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   9817:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   9818:                     $translation{$1} = $newid;
                   9819:                 }
1.749     raeburn  9820:                 $new_values{$file_name."\0".$newkey} = 
                   9821:                                           $$changes{'activate'}{$newitems[$i]};
                   9822:                 $new_control{$newkey} = $now;
                   9823:             }
                   9824:         }
                   9825:     }
                   9826:     my %todelete;
                   9827:     my %changed_items;
                   9828:     foreach my $action ('delete','update') {
                   9829:         if (exists($$changes{$action})) {
                   9830:             if (ref($$changes{$action}) eq 'HASH') {
                   9831:                 foreach my $key (keys(%{$$changes{$action}})) {
                   9832:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   9833:                     if ($action eq 'delete') { 
                   9834:                         $todelete{$itemnum} = 1;
                   9835:                     } else {
                   9836:                         $changed_items{$itemnum} = $key;
                   9837:                     }
                   9838:                 }
1.745     raeburn  9839:             }
                   9840:         }
1.749     raeburn  9841:     }
                   9842:     # get lock on access controls for file.
                   9843:     my $lockhash = {
                   9844:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   9845:                                                        ':'.$env{'user.domain'},
                   9846:                    }; 
                   9847:     my $tries = 0;
                   9848:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9849:    
1.1288    damieng  9850:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  9851:         $tries ++;
1.1289    damieng  9852:         sleep(0.1);
1.749     raeburn  9853:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9854:     }
                   9855:     if ($gotlock eq 'ok') {
                   9856:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   9857:         my ($tmp)=keys(%curr_permissions);
                   9858:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   9859:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   9860:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   9861:             if (ref($curr_controls) eq 'HASH') {
                   9862:                 foreach my $control_item (keys(%{$curr_controls})) {
                   9863:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   9864:                     if (defined($todelete{$itemnum})) {
                   9865:                         push(@deletions,$file_name."\0".$control_item);
                   9866:                     } else {
                   9867:                         if (defined($changed_items{$itemnum})) {
                   9868:                             $new_control{$changed_items{$itemnum}} = $now;
                   9869:                             push(@deletions,$file_name."\0".$control_item);
                   9870:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   9871:                         } else {
                   9872:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   9873:                         }
                   9874:                     }
1.745     raeburn  9875:                 }
                   9876:             }
                   9877:         }
1.970     raeburn  9878:         my ($group);
                   9879:         if (&is_course($domain,$user)) {
                   9880:             ($group,my $file) = split(/\//,$file_name,2);
                   9881:         }
1.749     raeburn  9882:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   9883:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   9884:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   9885:         #  remove lock
                   9886:         my @del_lock = ($file_name."\0".'locked_access_records');
                   9887:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9888:         my $sqlresult =
1.970     raeburn  9889:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9890:                                     $group);
1.749     raeburn  9891:     } else {
                   9892:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9893:     }
1.749     raeburn  9894:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9895: }
                   9896: 
1.827     raeburn  9897: sub make_public_indefinitely {
1.1271    raeburn  9898:     my (@requrl) = @_;
                   9899:     return &automated_portfile_access('public',\@requrl);
                   9900: }
                   9901: 
                   9902: sub automated_portfile_access {
                   9903:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  9904:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   9905:         return 'invalid';
                   9906:     }
1.1271    raeburn  9907:     my %urls;
                   9908:     if (ref($addsref) eq 'ARRAY') {
                   9909:         foreach my $requrl (@{$addsref}) {
                   9910:             if (&is_portfolio_url($requrl)) {
                   9911:                 unless (exists($urls{$requrl})) {
                   9912:                     $urls{$requrl} = 'add';
                   9913:                 }
                   9914:             }
                   9915:         }
                   9916:     }
                   9917:     if (ref($delsref) eq 'ARRAY') {
                   9918:         foreach my $requrl (@{$delsref}) { 
                   9919:             if (&is_portfolio_url($requrl)) {
                   9920:                 unless (exists($urls{$requrl})) {
                   9921:                     $urls{$requrl} = 'delete'; 
                   9922:                 }
                   9923:             }
                   9924:         }
                   9925:     }
                   9926:     unless (keys(%urls)) {
                   9927:         return 'invalid';
                   9928:     }
                   9929:     my $ip;
                   9930:     if ($accesstype eq 'ip') {
                   9931:         if (ref($info) eq 'HASH') {
                   9932:             if ($info->{'ip'} ne '') {
                   9933:                 $ip = $info->{'ip'};
                   9934:             }
                   9935:         }
                   9936:         if ($ip eq '') {
                   9937:             return 'invalid';
                   9938:         }
                   9939:     }
                   9940:     my $errors;
1.827     raeburn  9941:     my $now = time;
1.1271    raeburn  9942:     my %current_perms;
                   9943:     foreach my $requrl (sort(keys(%urls))) {
                   9944:         my $action;
                   9945:         if ($urls{$requrl} eq 'add') {
                   9946:             $action = 'activate';
                   9947:         } else {
                   9948:             $action = 'none';
                   9949:         }
                   9950:         my $aclnum = 0;
1.827     raeburn  9951:         my (undef,$udom,$unum,$file_name,$group) =
                   9952:             &parse_portfolio_url($requrl);
1.1271    raeburn  9953:         unless (exists($current_perms{$unum.':'.$udom})) {
                   9954:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   9955:         }
                   9956:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  9957:                                                    $group,$file_name);
                   9958:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9959:             my ($num,$scope,$end,$start) = 
                   9960:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  9961:             if ($scope eq $accesstype) {
                   9962:                 if (($start <= $now) && ($end == 0)) {
                   9963:                     if ($accesstype eq 'ip') {
                   9964:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   9965:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   9966:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   9967:                                     if ($urls{$requrl} eq 'add') {
                   9968:                                         $action = 'none';
                   9969:                                         last;
                   9970:                                     } else {
                   9971:                                         $action = 'delete';
                   9972:                                         $aclnum = $num;
                   9973:                                         last;
                   9974:                                     }
                   9975:                                 }
                   9976:                             }
                   9977:                         }
                   9978:                     } elsif ($accesstype eq 'public') {
                   9979:                         if ($urls{$requrl} eq 'add') {
                   9980:                             $action = 'none';
                   9981:                             last;
                   9982:                         } else {
                   9983:                             $action = 'delete';
                   9984:                             $aclnum = $num;
                   9985:                             last;
                   9986:                         }
                   9987:                     }
                   9988:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  9989:                     $action = 'update';
                   9990:                     $aclnum = $num;
1.1271    raeburn  9991:                     last;
1.827     raeburn  9992:                 }
                   9993:             }
                   9994:         }
                   9995:         if ($action eq 'none') {
1.1271    raeburn  9996:             next;
1.827     raeburn  9997:         } else {
                   9998:             my %changes;
                   9999:             my $newend = 0;
                   10000:             my $newstart = $now;
1.1271    raeburn  10001:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  10002:             $changes{$action}{$newkey} = {
1.1271    raeburn  10003:                 type => $accesstype,
1.827     raeburn  10004:                 time => {
                   10005:                     start => $newstart,
                   10006:                     end   => $newend,
                   10007:                 },
                   10008:             };
1.1271    raeburn  10009:             if ($accesstype eq 'ip') {
                   10010:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   10011:             }
1.827     raeburn  10012:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10013:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  10014:             unless ($outcome eq 'ok') {
                   10015:                 $errors .= $outcome.' ';
                   10016:             }
1.827     raeburn  10017:         }
1.1271    raeburn  10018:     }
                   10019:     if ($errors) {
                   10020:         $errors =~ s/\s$//;
                   10021:         return $errors;
1.827     raeburn  10022:     } else {
1.1271    raeburn  10023:         return 'ok';
1.827     raeburn  10024:     }
                   10025: }
                   10026: 
1.745     raeburn  10027: #------------------------------------------------------Get Marked as Read Only
                   10028: 
                   10029: sub get_marked_as_readonly {
                   10030:     my ($domain,$user,$what,$group) = @_;
                   10031:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10032:     my @readonly_files;
1.629     banghart 10033:     my $cmp1=$what;
                   10034:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10035:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10036:         if (defined($group)) {
                   10037:             if ($file_name !~ m-^\Q$group\E/-) {
                   10038:                 next;
                   10039:             }
                   10040:         }
1.561     banghart 10041:         if (ref($value) eq "ARRAY"){
                   10042:             foreach my $stored_what (@{$value}) {
1.629     banghart 10043:                 my $cmp2=$stored_what;
1.759     albertel 10044:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10045:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10046:                 }
1.629     banghart 10047:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10048:                     push(@readonly_files, $file_name);
1.745     raeburn  10049:                     last;
1.563     banghart 10050:                 } elsif (!defined($what)) {
                   10051:                     push(@readonly_files, $file_name);
1.745     raeburn  10052:                     last;
1.561     banghart 10053:                 }
                   10054:             }
1.745     raeburn  10055:         }
1.561     banghart 10056:     }
                   10057:     return @readonly_files;
                   10058: }
1.577     banghart 10059: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10060: 
1.577     banghart 10061: sub get_marked_as_readonly_hash {
1.745     raeburn  10062:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10063:     my %readonly_files;
1.745     raeburn  10064:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10065:         if (defined($group)) {
                   10066:             if ($file_name !~ m-^\Q$group\E/-) {
                   10067:                 next;
                   10068:             }
                   10069:         }
1.577     banghart 10070:         if (ref($value) eq "ARRAY"){
                   10071:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10072:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10073:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10074:                         if ($lock_descriptor eq 'graded') {
                   10075:                             $readonly_files{$file_name} = 'graded';
                   10076:                         } elsif ($lock_descriptor eq 'handback') {
                   10077:                             $readonly_files{$file_name} = 'handback';
                   10078:                         } else {
                   10079:                             if (!exists($readonly_files{$file_name})) {
                   10080:                                 $readonly_files{$file_name} = 'locked';
                   10081:                             }
                   10082:                         }
1.745     raeburn  10083:                     }
1.750     banghart 10084:                 } 
1.577     banghart 10085:             }
                   10086:         } 
                   10087:     }
                   10088:     return %readonly_files;
                   10089: }
1.559     banghart 10090: # ------------------------------------------------------------ Unmark as Read Only
                   10091: 
                   10092: sub unmark_as_readonly {
1.629     banghart 10093:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10094:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10095:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10096:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10097:     my $symb_crs = $what;
                   10098:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10099:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10100:     my ($tmp)=keys(%current_permissions);
                   10101:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10102:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10103:     foreach my $file (@readonly_files) {
1.759     albertel 10104: 	my $clean_file = &declutter_portfile($file);
                   10105: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10106: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10107:         my @new_locks;
                   10108:         my @del_keys;
                   10109:         if (ref($current_locks) eq "ARRAY"){
                   10110:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10111:                 my $compare=$locker;
1.749     raeburn  10112:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10113:                     $compare=join('',@{$locker});
1.746     raeburn  10114:                     if ($compare ne $symb_crs) {
                   10115:                         push(@new_locks, $locker);
                   10116:                     }
1.563     banghart 10117:                 }
                   10118:             }
1.650     albertel 10119:             if (scalar(@new_locks) > 0) {
1.563     banghart 10120:                 $current_permissions{$file} = \@new_locks;
                   10121:             } else {
                   10122:                 push(@del_keys, $file);
1.613     albertel 10123:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10124:                 delete($current_permissions{$file});
1.563     banghart 10125:             }
                   10126:         }
1.561     banghart 10127:     }
1.613     albertel 10128:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10129:     return;
                   10130: }
1.512     banghart 10131: 
1.17      www      10132: # ------------------------------------------------------------ Directory lister
                   10133: 
                   10134: sub dirlist {
1.955     raeburn  10135:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10136:     $uri=~s/^\///;
                   10137:     $uri=~s/\/$//;
1.253     stredwic 10138:     my ($udom, $uname);
1.955     raeburn  10139:     if ($getuserdir) {
1.253     stredwic 10140:         $udom = $userdomain;
                   10141:         $uname = $username;
1.955     raeburn  10142:     } else {
                   10143:         (undef,$udom,$uname)=split(/\//,$uri);
                   10144:         if(defined($userdomain)) {
                   10145:             $udom = $userdomain;
                   10146:         }
                   10147:         if(defined($username)) {
                   10148:             $uname = $username;
                   10149:         }
1.253     stredwic 10150:     }
1.955     raeburn  10151:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10152: 
1.955     raeburn  10153:     $dirRoot = $perlvar{'lonDocRoot'};
                   10154:     if (defined($getpropath)) {
                   10155:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10156:         $dirRoot =~ s/\/$//;
1.955     raeburn  10157:     } elsif (defined($getuserdir)) {
                   10158:         my $subdir=$uname.'__';
                   10159:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10160:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10161:                    ."/$udom/$subdir/$uname";
                   10162:     } elsif (defined($alternateRoot)) {
                   10163:         $dirRoot = $alternateRoot;
1.751     banghart 10164:     }
1.253     stredwic 10165: 
                   10166:     if($udom) {
                   10167:         if($uname) {
1.1135    raeburn  10168:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10169:             if ($uhome eq 'no_host') {
                   10170:                 return ([],'no_host');
                   10171:             }
1.955     raeburn  10172:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10173:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10174:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10175:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10176:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10177:             } else {
                   10178:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10179:             }
1.605     matthew  10180:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10181:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10182:                 @listing_results = split(/:/,$listing);
                   10183:             } else {
                   10184:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10185:             }
1.1135    raeburn  10186:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10187:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10188:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10189:                 return ([],$listing);
                   10190:             } else {
                   10191:                 return (\@listing_results);
1.1135    raeburn  10192:             }
1.955     raeburn  10193:         } elsif(!$alternateRoot) {
1.1136    raeburn  10194:             my (%allusers,%listerror);
1.841     albertel 10195: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10196:  	    foreach my $tryserver (keys(%servers)) {
                   10197:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10198:                                   &escape($udom),$tryserver);
                   10199:                 if ($listing eq 'unknown_cmd') {
                   10200: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10201: 				      $udom, $tryserver);
                   10202:                 } else {
                   10203:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10204:                 }
1.841     albertel 10205: 		if ($listing eq 'unknown_cmd') {
                   10206: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10207: 				      $udom, $tryserver);
                   10208: 		    @listing_results = split(/:/,$listing);
                   10209: 		} else {
                   10210: 		    @listing_results =
                   10211: 			map { &unescape($_); } split(/:/,$listing);
                   10212: 		}
1.1136    raeburn  10213:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10214:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10215:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10216:                     $listerror{$tryserver} = $listing;
                   10217:                 } else {
1.841     albertel 10218: 		    foreach my $line (@listing_results) {
                   10219: 			my ($entry) = split(/&/,$line,2);
                   10220: 			$allusers{$entry} = 1;
                   10221: 		    }
                   10222: 		}
1.253     stredwic 10223:             }
1.1136    raeburn  10224:             my @alluserslist=();
1.800     albertel 10225:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10226:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10227:             }
1.1318    droeschl 10228: 
                   10229:             if (!%listerror) {
                   10230:                 # no errors
                   10231:                 return (\@alluserslist);
                   10232:             } elsif (scalar(keys(%servers)) == 1) {
                   10233:                 # one library server, one error 
                   10234:                 my ($key) = keys(%listerror);
                   10235:                 return (\@alluserslist, $listerror{$key});
                   10236:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10237:                 # con_lost indicates that we might miss data from at least one
                   10238:                 # library server
                   10239:                 return (\@alluserslist, 'con_lost');
                   10240:             } else {
                   10241:                 # multiple library servers and no con_lost -> data should be
                   10242:                 # complete. 
                   10243:                 return (\@alluserslist);
                   10244:             }
                   10245: 
1.253     stredwic 10246:         } else {
1.1136    raeburn  10247:             return ([],'missing username');
1.253     stredwic 10248:         }
1.955     raeburn  10249:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10250:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10251:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10252:         return (\@all_domains);
1.955     raeburn  10253:     } else {
1.1136    raeburn  10254:         return ([],'missing domain');
1.275     stredwic 10255:     }
                   10256: }
                   10257: 
                   10258: # --------------------------------------------- GetFileTimestamp
                   10259: # This function utilizes dirlist and returns the date stamp for
                   10260: # when it was last modified.  It will also return an error of -1
                   10261: # if an error occurs
                   10262: 
                   10263: sub GetFileTimestamp {
1.955     raeburn  10264:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10265:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10266:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10267:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10268:                                     undef,$getuserdir);
                   10269:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10270:         return -1;
                   10271:     }
                   10272:     if (ref($fileref) eq 'ARRAY') {
                   10273:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10274:         # @stats contains first the filename, then the stat output
                   10275:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10276:     } else {
                   10277:         return -1;
1.253     stredwic 10278:     }
1.26      www      10279: }
                   10280: 
1.712     albertel 10281: sub stat_file {
                   10282:     my ($uri) = @_;
1.787     albertel 10283:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10284: 
1.955     raeburn  10285:     my ($udom,$uname,$file);
1.712     albertel 10286:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10287: 	($udom,$uname,$file) =
1.811     albertel 10288: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10289: 	$file = 'userfiles/'.$file;
                   10290:     }
                   10291:     if ($uri =~ m-^/res/-) {
                   10292: 	($udom,$uname) = 
1.807     albertel 10293: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10294: 	$file = $uri;
                   10295:     }
                   10296: 
                   10297:     if (!$udom || !$uname || !$file) {
                   10298: 	# unable to handle the uri
                   10299: 	return ();
                   10300:     }
1.956     raeburn  10301:     my $getpropath;
                   10302:     if ($file =~ /^userfiles\//) {
                   10303:         $getpropath = 1;
                   10304:     }
1.1136    raeburn  10305:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10306:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10307:         return ();
                   10308:     } else {
                   10309:         if (ref($listref) eq 'ARRAY') {
                   10310:             my @stats = split('&',$listref->[0]);
                   10311: 	    shift(@stats); #filename is first
                   10312: 	    return @stats;
                   10313:         }
1.712     albertel 10314:     }
                   10315:     return ();
                   10316: }
                   10317: 
1.1313    raeburn  10318: # --------------------------------------------------------- recursedirs
                   10319: # Recursive function to traverse either a specific user's Authoring Space
                   10320: # or corresponding Published Resource Space, and populate the hash ref:
                   10321: # $dirhashref with URLs of all directories, and if $filehashref hash
                   10322: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
                   10323: # or .rights files in resource space, and .meta, .save, .log, and .bak
                   10324: # files in Authoring Space.
                   10325: #
                   10326: # Inputs:
                   10327: #
                   10328: # $is_home - true if current server is home server for user's space
                   10329: # $context - either: priv, or res respectively for Authoring or Resource Space.
                   10330: # $docroot - Document root (i.e., /home/httpd/html
                   10331: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
                   10332: # $relpath - Current path (relative to top level).
                   10333: # $dirhashref - reference to hash to populate with URLs of directories (Required)
                   10334: # $filehashref - reference to hash to populate with URLs of files (Optional)
                   10335: #
                   10336: # Returns: nothing
                   10337: #
                   10338: # Side Effects: populates $dirhashref, and $filehashref (if provided).
                   10339: #
                   10340: # Currently used by interface/londocs.pm to create linked select boxes for
                   10341: # directory and filename to import a Course "Author" resource into a course, and
                   10342: # also to create linked select boxes for Authoring Space and Directory to choose
                   10343: # save location for creation of a new "standard" problem from the Course Editor.
                   10344: #
                   10345: 
                   10346: sub recursedirs {
                   10347:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
                   10348:     return unless (ref($dirhashref) eq 'HASH');
                   10349:     my $currpath = $docroot.$toppath;
                   10350:     if ($relpath) {
                   10351:         $currpath .= "/$relpath";
                   10352:     }
                   10353:     my $savefile;
                   10354:     if (ref($filehashref)) {
                   10355:         $savefile = 1;
                   10356:     }
                   10357:     if ($is_home) {
                   10358:         if (opendir(my $dirh,$currpath)) {
                   10359:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
                   10360:                 next if ($item eq '');
                   10361:                 if (-d "$currpath/$item") {
                   10362:                     my $newpath;
                   10363:                     if ($relpath) {
                   10364:                         $newpath = "$relpath/$item";
                   10365:                     } else {
                   10366:                         $newpath = $item;
                   10367:                     }
                   10368:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   10369:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   10370:                 } elsif ($savefile) {
                   10371:                     if ($context eq 'priv') {
                   10372:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   10373:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   10374:                         }
                   10375:                     } else {
                   10376:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
                   10377:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   10378:                         }
                   10379:                     }
                   10380:                 }
                   10381:             }
                   10382:             closedir($dirh);
                   10383:         }
                   10384:     } else {
                   10385:         my ($dirlistref,$listerror) =
                   10386:             &dirlist($toppath.$relpath);
                   10387:         my @dir_lines;
                   10388:         my $dirptr=16384;
                   10389:         if (ref($dirlistref) eq 'ARRAY') {
                   10390:             foreach my $dir_line (sort
                   10391:                               {
                   10392:                                   my ($afile)=split('&',$a,2);
                   10393:                                   my ($bfile)=split('&',$b,2);
                   10394:                                   return (lc($afile) cmp lc($bfile));
                   10395:                               } (@{$dirlistref})) {
                   10396:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
                   10397:                     split(/\&/,$dir_line,16);
                   10398:                 $item =~ s/\s+$//;
                   10399:                 next if (($item =~ /^\.\.?$/) || ($obs));
                   10400:                 if ($dirptr&$testdir) {
                   10401:                     my $newpath;
                   10402:                     if ($relpath) {
                   10403:                         $newpath = "$relpath/$item";
                   10404:                     } else {
                   10405:                         $relpath = '/';
                   10406:                         $newpath = $item;
                   10407:                     }
                   10408:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   10409:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   10410:                 } elsif ($savefile) {
                   10411:                     if ($context eq 'priv') {
                   10412:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   10413:                             $filehashref->{$relpath}{$item} = 1;
                   10414:                         }
                   10415:                     } else {
                   10416:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
                   10417:                             $filehashref->{$relpath}{$item} = 1;
                   10418:                         }
                   10419:                     }
                   10420:                 }
                   10421:             }
                   10422:         }
                   10423:     }
                   10424:     return;
                   10425: }
                   10426: 
1.26      www      10427: # -------------------------------------------------------- Value of a Condition
                   10428: 
1.713     albertel 10429: # gets the value of a specific preevaluated condition
                   10430: #    stored in the string  $env{user.state.<cid>}
                   10431: # or looks up a condition reference in the bighash and if if hasn't
                   10432: # already been evaluated recurses into docondval to get the value of
                   10433: # the condition, then memoizing it to 
                   10434: #   $env{user.state.<cid>.<condition>}
1.40      www      10435: sub directcondval {
                   10436:     my $number=shift;
1.620     albertel 10437:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 10438: 	&Apache::lonuserstate::evalstate();
                   10439:     }
1.713     albertel 10440:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   10441: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   10442:     } elsif ($number =~ /^_/) {
                   10443: 	my $sub_condition;
                   10444: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10445: 		&GDBM_READER(),0640)) {
                   10446: 	    $sub_condition=$bighash{'conditions'.$number};
                   10447: 	    untie(%bighash);
                   10448: 	}
                   10449: 	my $value = &docondval($sub_condition);
1.949     raeburn  10450: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 10451: 	return $value;
                   10452:     }
1.620     albertel 10453:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   10454:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      10455:     } else {
                   10456:        return 2;
                   10457:     }
                   10458: }
                   10459: 
1.713     albertel 10460: # get the collection of conditions for this resource
1.26      www      10461: sub condval {
                   10462:     my $condidx=shift;
1.54      www      10463:     my $allpathcond='';
1.713     albertel 10464:     foreach my $cond (split(/\|/,$condidx)) {
                   10465: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   10466: 	    $allpathcond.=
                   10467: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   10468: 	}
1.191     harris41 10469:     }
1.54      www      10470:     $allpathcond=~s/\|$//;
1.713     albertel 10471:     return &docondval($allpathcond);
                   10472: }
                   10473: 
                   10474: #evaluates an expression of conditions
                   10475: sub docondval {
                   10476:     my ($allpathcond) = @_;
                   10477:     my $result=0;
                   10478:     if ($env{'request.course.id'}
                   10479: 	&& defined($allpathcond)) {
                   10480: 	my $operand='|';
                   10481: 	my @stack;
                   10482: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   10483: 	    if ($chunk eq '(') {
                   10484: 		push @stack,($operand,$result);
                   10485: 	    } elsif ($chunk eq ')') {
                   10486: 		my $before=pop @stack;
                   10487: 		if (pop @stack eq '&') {
                   10488: 		    $result=$result>$before?$before:$result;
                   10489: 		} else {
                   10490: 		    $result=$result>$before?$result:$before;
                   10491: 		}
                   10492: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   10493: 		$operand=$chunk;
                   10494: 	    } else {
                   10495: 		my $new=directcondval($chunk);
                   10496: 		if ($operand eq '&') {
                   10497: 		    $result=$result>$new?$new:$result;
                   10498: 		} else {
                   10499: 		    $result=$result>$new?$result:$new;
                   10500: 		}
                   10501: 	    }
                   10502: 	}
1.26      www      10503:     }
                   10504:     return $result;
1.421     albertel 10505: }
                   10506: 
                   10507: # ---------------------------------------------------- Devalidate courseresdata
                   10508: 
                   10509: sub devalidatecourseresdata {
                   10510:     my ($coursenum,$coursedomain)=@_;
                   10511:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10512:     &devalidate_cache_new('courseres',$hashid);
1.28      www      10513: }
                   10514: 
1.763     www      10515: 
1.200     www      10516: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     10517: #
                   10518: #  Parameters:
                   10519: #      $coursenum    - Number of the course.
                   10520: #      $coursedomain - Domain at which the course was created.
                   10521: #  Returns:
                   10522: #     A hash of the course parameters along (I think) with timestamps
                   10523: #     and version info.
1.877     foxr     10524: 
1.624     albertel 10525: sub get_courseresdata {
                   10526:     my ($coursenum,$coursedomain)=@_;
1.200     www      10527:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   10528:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10529:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 10530:     my %dumpreply;
1.417     albertel 10531:     unless (defined($cached)) {
1.624     albertel 10532: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 10533: 	$result=\%dumpreply;
1.251     albertel 10534: 	my ($tmp) = keys(%dumpreply);
                   10535: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 10536: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 10537: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   10538: 	    return $tmp;
1.416     albertel 10539: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 10540: 	    $result=undef;
1.599     albertel 10541: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 10542: 	}
                   10543:     }
1.624     albertel 10544:     return $result;
                   10545: }
                   10546: 
1.633     albertel 10547: sub devalidateuserresdata {
                   10548:     my ($uname,$udom)=@_;
                   10549:     my $hashid="$udom:$uname";
                   10550:     &devalidate_cache_new('userres',$hashid);
                   10551: }
                   10552: 
1.624     albertel 10553: sub get_userresdata {
                   10554:     my ($uname,$udom)=@_;
                   10555:     #most student don\'t have any data set, check if there is some data
                   10556:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   10557: 
                   10558:     my $hashid="$udom:$uname";
                   10559:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   10560:     if (!defined($cached)) {
                   10561: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   10562: 	$result=\%resourcedata;
                   10563: 	&do_cache_new('userres',$hashid,$result,600);
                   10564:     }
                   10565:     my ($tmp)=keys(%$result);
                   10566:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   10567: 	return $result;
                   10568:     }
                   10569:     #error 2 occurs when the .db doesn't exist
                   10570:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  10571:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   10572: 	    &logthis("<font color=\"blue\">WARNING:".
                   10573: 		     " Trying to get resource data for ".
                   10574: 		     $uname." at ".$udom.": ".
                   10575: 		     $tmp."</font>");
                   10576:         }
1.624     albertel 10577:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 10578: 	#&EXT_cache_set($udom,$uname);
                   10579: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 10580: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 10581:     }
                   10582:     return $tmp;
                   10583: }
1.879     foxr     10584: #----------------------------------------------- resdata - return resource data
                   10585: #  Purpose:
                   10586: #    Return resource data for either users or for a course.
                   10587: #  Parameters:
                   10588: #     $name      - Course/user name.
                   10589: #     $domain    - Name of the domain the user/course is registered on.
1.1311    raeburn  10590: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  10591: #     $mapp      - decluttered URL of enclosing map  
                   10592: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   10593: #     $recurseup - Ref to array of map URLs, starting with map containing
                   10594: #                  $mapp up through hierarchy of nested maps to top level map.  
                   10595: #     $courseid  - CourseID (first part of param identifier).
                   10596: #     $modifier  - Middle part of param identifier.
                   10597: #     $what      - Last part of param identifier.
1.879     foxr     10598: #     @which     - Array of names of resources desired.
                   10599: #  Returns:
                   10600: #     The value of the first reasource in @which that is found in the
                   10601: #     resource hash.
                   10602: #  Exceptional Conditions:
                   10603: #     If the $type passed in is not valid (not the string 'course' or 
                   10604: #     'user', an undefined  reference is returned.
                   10605: #     If none of the resources are found, an undef is returned
1.624     albertel 10606: sub resdata {
1.1301    raeburn  10607:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   10608:         $modifier,$what,@which)=@_;
1.624     albertel 10609:     my $result;
                   10610:     if ($type eq 'course') {
                   10611: 	$result=&get_courseresdata($name,$domain);
                   10612:     } elsif ($type eq 'user') {
                   10613: 	$result=&get_userresdata($name,$domain);
                   10614:     }
                   10615:     if (!ref($result)) { return $result; }    
1.251     albertel 10616:     foreach my $item (@which) {
1.1301    raeburn  10617:         if ($item->[1] eq 'course') {
                   10618:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   10619:                 unless ($$recursed) {
1.1302    raeburn  10620:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  10621:                     $$recursed = 1;
                   10622:                 }
                   10623:                 foreach my $item (@${recurseup}) {
                   10624:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   10625:                     last if (defined($result->{$norecursechk}));
                   10626:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   10627:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   10628:                 }
                   10629:             }
                   10630:         }
                   10631:         if (defined($result->{$item->[0]})) {
1.927     albertel 10632: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 10633: 	}
1.250     albertel 10634:     }
1.291     albertel 10635:     return undef;
1.200     www      10636: }
                   10637: 
1.1298    raeburn  10638: sub get_domain_ltitools {
                   10639:     my ($cdom) = @_;
                   10640:     my %ltitools;
                   10641:     my ($result,$cached)=&is_cached_new('ltitools',$cdom);
                   10642:     if (defined($cached)) {
                   10643:         if (ref($result) eq 'HASH') {
                   10644:             %ltitools = %{$result};
                   10645:         }
                   10646:     } else {
                   10647:         my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
                   10648:         if (ref($domconfig{'ltitools'}) eq 'HASH') {
                   10649:             %ltitools = %{$domconfig{'ltitools'}};
                   10650:         }
                   10651:         my $cachetime = 24*60*60;
                   10652:         &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
                   10653:     }
                   10654:     return %ltitools;
                   10655: }
                   10656: 
1.1236    raeburn  10657: sub get_numsuppfiles {
                   10658:     my ($cnum,$cdom,$ignorecache)=@_;
                   10659:     my $hashid=$cnum.':'.$cdom;
                   10660:     my ($suppcount,$cached);
                   10661:     unless ($ignorecache) {
                   10662:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   10663:     }
                   10664:     unless (defined($cached)) {
                   10665:         my $chome=&homeserver($cnum,$cdom);
                   10666:         unless ($chome eq 'no_host') {
                   10667:             ($suppcount,my $errors) = (0,0);
                   10668:             my $suppmap = 'supplemental.sequence';
                   10669:             ($suppcount,$errors) = 
                   10670:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   10671:         }
                   10672:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   10673:     }
                   10674:     return $suppcount;
                   10675: }
                   10676: 
1.379     matthew  10677: #
                   10678: # EXT resource caching routines
                   10679: #
                   10680: 
1.1302    raeburn  10681: {
                   10682: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   10683: #
                   10684: # The course for which we cache
                   10685: my $cachedmapkey='';
                   10686: # The cached recursive maps for this course
                   10687: my %cachedmaps=();
                   10688: # When this was last done
                   10689: my $cachedmaptime='';
                   10690: 
1.379     matthew  10691: sub clear_EXT_cache_status {
1.383     albertel 10692:     &delenv('cache.EXT.');
1.379     matthew  10693: }
                   10694: 
                   10695: sub EXT_cache_status {
                   10696:     my ($target_domain,$target_user) = @_;
1.383     albertel 10697:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 10698:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  10699:         # We know already the user has no data
                   10700:         return 1;
                   10701:     } else {
                   10702:         return 0;
                   10703:     }
                   10704: }
                   10705: 
                   10706: sub EXT_cache_set {
                   10707:     my ($target_domain,$target_user) = @_;
1.383     albertel 10708:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  10709:     #&appenv({$cachename => time});
1.379     matthew  10710: }
                   10711: 
1.28      www      10712: # --------------------------------------------------------- Value of a Variable
1.58      www      10713: sub EXT {
1.715     albertel 10714: 
1.1228    raeburn  10715:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      10716:     unless ($varname) { return ''; }
1.218     albertel 10717:     #get real user name/domain, courseid and symb
                   10718:     my $courseid;
1.359     albertel 10719:     my $publicuser;
1.427     www      10720:     if ($symbparm) {
                   10721: 	$symbparm=&get_symb_from_alias($symbparm);
                   10722:     }
1.218     albertel 10723:     if (!($uname && $udom)) {
1.790     albertel 10724:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 10725:       if (!$symbparm) {	$symbparm=$cursymb; }
                   10726:     } else {
1.620     albertel 10727: 	$courseid=$env{'request.course.id'};
1.218     albertel 10728:     }
1.48      www      10729:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   10730:     my $rest;
1.320     albertel 10731:     if (defined($therest[0])) {
1.48      www      10732:        $rest=join('.',@therest);
                   10733:     } else {
                   10734:        $rest='';
                   10735:     }
1.320     albertel 10736: 
1.57      www      10737:     my $qualifierrest=$qualifier;
                   10738:     if ($rest) { $qualifierrest.='.'.$rest; }
                   10739:     my $spacequalifierrest=$space;
                   10740:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      10741:     if ($realm eq 'user') {
1.48      www      10742: # --------------------------------------------------------------- user.resource
                   10743: 	if ($space eq 'resource') {
1.651     albertel 10744: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   10745: 		  || defined($Apache::lonhomework::parsing_a_task))
                   10746: 		 &&
1.744     albertel 10747: 		 ($symbparm eq &symbread()) ) {	
                   10748: 		# if we are in the middle of processing the resource the
                   10749: 		# get the value we are planning on committing
                   10750:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   10751:                     return $Apache::lonhomework::results{$qualifierrest};
                   10752:                 } else {
                   10753:                     return $Apache::lonhomework::history{$qualifierrest};
                   10754:                 }
1.335     albertel 10755: 	    } else {
1.359     albertel 10756: 		my %restored;
1.620     albertel 10757: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 10758: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   10759: 		} else {
                   10760: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   10761: 		}
1.335     albertel 10762: 		return $restored{$qualifierrest};
                   10763: 	    }
1.48      www      10764: # ----------------------------------------------------------------- user.access
                   10765:         } elsif ($space eq 'access') {
1.218     albertel 10766: 	    # FIXME - not supporting calls for a specific user
1.48      www      10767:             return &allowed($qualifier,$rest);
                   10768: # ------------------------------------------ user.preferences, user.environment
                   10769:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 10770: 	    if (($uname eq $env{'user.name'}) &&
                   10771: 		($udom eq $env{'user.domain'})) {
                   10772: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 10773: 	    } else {
1.359     albertel 10774: 		my %returnhash;
                   10775: 		if (!$publicuser) {
                   10776: 		    %returnhash=&userenvironment($udom,$uname,
                   10777: 						 $qualifierrest);
                   10778: 		}
1.218     albertel 10779: 		return $returnhash{$qualifierrest};
                   10780: 	    }
1.48      www      10781: # ----------------------------------------------------------------- user.course
                   10782:         } elsif ($space eq 'course') {
1.218     albertel 10783: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10784:             return $env{join('.',('request.course',$qualifier))};
1.48      www      10785: # ------------------------------------------------------------------- user.role
                   10786:         } elsif ($space eq 'role') {
1.218     albertel 10787: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10788:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      10789:             if ($qualifier eq 'value') {
                   10790: 		return $role;
                   10791:             } elsif ($qualifier eq 'extent') {
                   10792:                 return $where;
                   10793:             }
                   10794: # ----------------------------------------------------------------- user.domain
                   10795:         } elsif ($space eq 'domain') {
1.218     albertel 10796:             return $udom;
1.48      www      10797: # ------------------------------------------------------------------- user.name
                   10798:         } elsif ($space eq 'name') {
1.218     albertel 10799:             return $uname;
1.48      www      10800: # ---------------------------------------------------- Any other user namespace
1.29      www      10801:         } else {
1.359     albertel 10802: 	    my %reply;
                   10803: 	    if (!$publicuser) {
                   10804: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   10805: 	    }
                   10806: 	    return $reply{$qualifierrest};
1.48      www      10807:         }
1.236     www      10808:     } elsif ($realm eq 'query') {
                   10809: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 10810:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   10811: 						[$spacequalifierrest]);
1.620     albertel 10812: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      10813:    } elsif ($realm eq 'request') {
1.48      www      10814: # ------------------------------------------------------------- request.browser
                   10815:         if ($space eq 'browser') {
1.1145    bisitz   10816:             return $env{'browser.'.$qualifier};
1.57      www      10817: # ------------------------------------------------------------ request.filename
                   10818:         } else {
1.620     albertel 10819:             return $env{'request.'.$spacequalifierrest};
1.29      www      10820:         }
1.28      www      10821:     } elsif ($realm eq 'course') {
1.48      www      10822: # ---------------------------------------------------------- course.description
1.620     albertel 10823:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      10824:     } elsif ($realm eq 'resource') {
1.165     www      10825: 
1.620     albertel 10826: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 10827: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   10828: 	}
1.693     albertel 10829: 
1.1232    raeburn  10830:         if ($qualifier eq '') {
                   10831: 	    if ($space eq 'title') {
                   10832: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   10833: 	        return &gettitle($symbparm);
                   10834: 	    }
1.693     albertel 10835: 	
1.1232    raeburn  10836: 	    if ($space eq 'map') {
                   10837: 	        my ($map) = &decode_symb($symbparm);
                   10838: 	        return &symbread($map);
                   10839: 	    }
                   10840:             if ($space eq 'maptitle') {
                   10841:                 my ($map) = &decode_symb($symbparm);
                   10842:                 return &gettitle($map);
                   10843:             }
                   10844: 	    if ($space eq 'filename') {
                   10845: 	        if ($symbparm) {
                   10846: 		    return &clutter((&decode_symb($symbparm))[2]);
                   10847: 	        }
                   10848: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 10849: 	    }
1.1232    raeburn  10850: 
1.1233    raeburn  10851:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   10852:                 if ($space eq 'visibleparts') {
                   10853:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10854:                     my $item;
                   10855:                     if (ref($navmap)) {
                   10856:                         my $res = $navmap->getBySymb($symbparm);
                   10857:                         my $parts = $res->parts();
                   10858:                         if (ref($parts) eq 'ARRAY') {
                   10859:                             $item = join(',',@{$parts});
                   10860:                         }
                   10861:                         undef($navmap);
1.1232    raeburn  10862:                     }
1.1233    raeburn  10863:                     return $item;
1.1232    raeburn  10864:                 }
                   10865:             }
                   10866:         }
1.693     albertel 10867: 
1.1301    raeburn  10868: 	my ($section, $group, @groups, @recurseup, $recursed);
                   10869: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  10870:         if (($courseid eq '') && ($cid)) {
                   10871:             $courseid = $cid;
                   10872:         }
                   10873: 	if (($symbparm && $courseid) && 
                   10874: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      10875: 
1.218     albertel 10876: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      10877: 
1.60      www      10878: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 10879: 	    my $symbp=$symbparm;
1.1301    raeburn  10880: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 10881: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  10882:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 10883: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 10884: 	    if (($env{'user.name'} eq $uname) &&
                   10885: 		($env{'user.domain'} eq $udom)) {
                   10886: 		$section=$env{'request.course.sec'};
1.733     raeburn  10887:                 @groups = split(/:/,$env{'request.course.groups'});  
                   10888:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 10889: 	    } else {
1.539     albertel 10890: 		if (! defined($usection)) {
1.551     albertel 10891: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 10892: 		} else {
                   10893: 		    $section = $usection;
                   10894: 		}
1.733     raeburn  10895:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 10896: 	    }
                   10897: 
                   10898: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   10899: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  10900:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 10901: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   10902: 
1.593     albertel 10903: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 10904: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  10905:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 10906: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      10907: 
1.60      www      10908: # ----------------------------------------------------------- first, check user
1.624     albertel 10909: 
1.1301    raeburn  10910: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   10911:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 10912: 				       ([$courselevelr,'resource'],
                   10913: 					[$courselevelm,'map'     ],
1.1301    raeburn  10914:                                         [$courseleveli,'map'     ],
1.927     albertel 10915: 					[$courselevel, 'course'  ]));
1.931     albertel 10916: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      10917: 
1.594     albertel 10918: # ------------------------------------------------ second, check some of course
1.684     raeburn  10919:             my $coursereply;
1.691     raeburn  10920:             if (@groups > 0) {
                   10921:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  10922:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   10923:                                        $mapp,\$recursed,\@recurseup);
                   10924:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  10925:             }
1.96      www      10926: 
1.684     raeburn  10927: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 10928: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  10929: 				  'course',$mapp,\$recursed,\@recurseup,
                   10930:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 10931: 				  ([$seclevelr,   'resource'],
                   10932: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  10933:                                    [$secleveli,   'map'     ],
1.927     albertel 10934: 				   [$seclevel,    'course'  ],
                   10935: 				   [$courselevelr,'resource']));
                   10936: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      10937: 
1.60      www      10938: # ------------------------------------------------------ third, check map parms
1.218     albertel 10939: 	    my %parmhash=();
                   10940: 	    my $thisparm='';
                   10941: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 10942: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 10943: 		    &GDBM_READER(),0640)) {
1.218     albertel 10944: 		$thisparm=$parmhash{$symbparm};
                   10945: 		untie(%parmhash);
                   10946: 	    }
1.927     albertel 10947: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 10948: 	}
1.594     albertel 10949: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  10950:  
                   10951:         my $what = $spacequalifierrest;
                   10952: 	$what=~s/\./\_/;
1.282     albertel 10953: 	my $filename;
                   10954: 	if (!$symbparm) { $symbparm=&symbread(); }
                   10955: 	if ($symbparm) {
1.409     www      10956: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 10957: 	} else {
1.620     albertel 10958: 	    $filename=$env{'request.filename'};
1.282     albertel 10959: 	}
1.1301    raeburn  10960: 	my $metadata=&metadata($filename,$what);
1.927     albertel 10961: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1301    raeburn  10962: 	$metadata=&metadata($filename,'parameter_'.$what);
1.927     albertel 10963: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      10964: 
1.1301    raeburn  10965: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 10966: 	if ($symbparm && defined($courseid) && 
1.620     albertel 10967: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 10968: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   10969: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  10970: 				     'course',$mapp,\$recursed,\@recurseup,
                   10971:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 10972: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  10973:                                       [$courseleveli,'map'   ],
1.927     albertel 10974: 				      [$courselevel, 'course']));
                   10975: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 10976: 	}
1.145     www      10977: # ------------------------------------------------------------------ Cascade up
1.218     albertel 10978: 	unless ($space eq '0') {
1.336     albertel 10979: 	    my @parts=split(/_/,$space);
                   10980: 	    my $id=pop(@parts);
                   10981: 	    my $part=join('_',@parts);
                   10982: 	    if ($part eq '') { $part='0'; }
1.927     albertel 10983: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 10984: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  10985: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 10986: 	}
1.395     albertel 10987: 	if ($recurse) { return undef; }
                   10988: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 10989: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      10990: # ---------------------------------------------------- Any other user namespace
                   10991:     } elsif ($realm eq 'environment') {
                   10992: # ----------------------------------------------------------------- environment
1.620     albertel 10993: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   10994: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 10995: 	} else {
1.770     albertel 10996: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   10997: 		return '';
                   10998: 	    }
1.219     albertel 10999: 	    my %returnhash=&userenvironment($udom,$uname,
                   11000: 					    $spacequalifierrest);
                   11001: 	    return $returnhash{$spacequalifierrest};
                   11002: 	}
1.28      www      11003:     } elsif ($realm eq 'system') {
1.48      www      11004: # ----------------------------------------------------------------- system.time
                   11005: 	if ($space eq 'time') {
                   11006: 	    return time;
                   11007:         }
1.696     albertel 11008:     } elsif ($realm eq 'server') {
                   11009: # ----------------------------------------------------------------- system.time
                   11010: 	if ($space eq 'name') {
                   11011: 	    return $ENV{'SERVER_NAME'};
                   11012:         }
1.28      www      11013:     }
1.48      www      11014:     return '';
1.61      www      11015: }
                   11016: 
1.927     albertel 11017: sub get_reply {
                   11018:     my ($reply_value) = @_;
1.940     raeburn  11019:     if (ref($reply_value) eq 'ARRAY') {
                   11020:         if (wantarray) {
                   11021: 	    return @$reply_value;
                   11022:         }
                   11023:         return $reply_value->[0];
                   11024:     } else {
                   11025:         return $reply_value;
1.927     albertel 11026:     }
                   11027: }
                   11028: 
1.691     raeburn  11029: sub check_group_parms {
1.1301    raeburn  11030:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   11031:         $recursed,$recurseupref) = @_;
                   11032:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   11033:                   [$what,'course']);
                   11034:     my $coursereply;
1.691     raeburn  11035:     foreach my $group (@{$groups}) {
1.1301    raeburn  11036:         my @groupitems = ();
1.691     raeburn  11037:         foreach my $level (@levels) {
1.927     albertel 11038:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11039:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11040:         }
1.1301    raeburn  11041:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11042:                                    $env{'course.'.$courseid.'.domain'},
                   11043:                                    'course',$mapp,$recursed,$recurseupref,
                   11044:                                    $courseid,'.['.$group.'].',$what,
                   11045:                                    @groupitems);
                   11046:         last if (defined($coursereply));
1.691     raeburn  11047:     }
                   11048:     return $coursereply;
                   11049: }
                   11050: 
1.1301    raeburn  11051: sub get_map_hierarchy {
1.1302    raeburn  11052:     my ($mapname,$courseid) = @_;
                   11053:     my @recurseup = ();
1.1301    raeburn  11054:     if ($mapname) {
1.1302    raeburn  11055:         if (($cachedmapkey eq $courseid) &&
                   11056:             (abs($cachedmaptime-time)<5)) {
                   11057:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   11058:                 return @{$cachedmaps{$mapname}};
                   11059:             }
                   11060:         }
1.1301    raeburn  11061:         my $navmap = Apache::lonnavmaps::navmap->new();
                   11062:         if (ref($navmap)) {
                   11063:             @recurseup = $navmap->recurseup_maps($mapname);
                   11064:             undef($navmap);
1.1302    raeburn  11065:             $cachedmaps{$mapname} = \@recurseup;
                   11066:             $cachedmaptime=time;
                   11067:             $cachedmapkey=$courseid;
1.1301    raeburn  11068:         }
                   11069:     }
                   11070:     return @recurseup;
                   11071: }
                   11072: 
1.1302    raeburn  11073: }
                   11074: 
1.691     raeburn  11075: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11076:     my ($courseid,@groups) = @_;
                   11077:     @groups = sort(@groups);
1.691     raeburn  11078:     return @groups;
                   11079: }
                   11080: 
1.395     albertel 11081: sub packages_tab_default {
                   11082:     my ($uri,$varname)=@_;
                   11083:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11084: 
                   11085:     my (@extension,@specifics,$do_default);
                   11086:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11087: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11088: 	if ($pack_type eq 'default') {
                   11089: 	    $do_default=1;
                   11090: 	} elsif ($pack_type eq 'extension') {
                   11091: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11092: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11093: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11094: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11095: 	}
                   11096:     }
                   11097:     # first look for a package that matches the requested part id
                   11098:     foreach my $package (@specifics) {
                   11099: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11100: 	next if ($pack_part ne $part);
                   11101: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11102: 	    return $packagetab{"$pack_type&$name&default"};
                   11103: 	}
                   11104:     }
                   11105:     # look for any possible matching non extension_ package
                   11106:     foreach my $package (@specifics) {
                   11107: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11108: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11109: 	    return $packagetab{"$pack_type&$name&default"};
                   11110: 	}
1.585     albertel 11111: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11112: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11113: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11114: 	}
                   11115:     }
1.738     albertel 11116:     # look for any posible extension_ match
                   11117:     foreach my $package (@extension) {
                   11118: 	my ($package,$pack_type)=@{$package};
                   11119: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11120: 	    return $packagetab{"$pack_type&$name&default"};
                   11121: 	}
                   11122: 	if (defined($packagetab{$package."&$name&default"})) {
                   11123: 	    return $packagetab{$package."&$name&default"};
                   11124: 	}
                   11125:     }
                   11126:     # look for a global default setting
                   11127:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11128: 	return $packagetab{"default&$name&default"};
                   11129:     }
1.395     albertel 11130:     return undef;
                   11131: }
                   11132: 
1.334     albertel 11133: sub add_prefix_and_part {
                   11134:     my ($prefix,$part)=@_;
                   11135:     my $keyroot;
                   11136:     if (defined($prefix) && $prefix !~ /^__/) {
                   11137: 	# prefix that has a part already
                   11138: 	$keyroot=$prefix;
                   11139:     } elsif (defined($prefix)) {
                   11140: 	# prefix that is missing a part
                   11141: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11142:     } else {
                   11143: 	# no prefix at all
                   11144: 	if (defined($part)) { $keyroot='_'.$part; }
                   11145:     }
                   11146:     return $keyroot;
                   11147: }
                   11148: 
1.71      www      11149: # ---------------------------------------------------------------- Get metadata
                   11150: 
1.599     albertel 11151: my %metaentry;
1.1070    www      11152: my %importedpartids;
1.71      www      11153: sub metadata {
1.176     www      11154:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11155:     $uri=&declutter($uri);
1.288     albertel 11156:     # if it is a non metadata possible uri return quickly
1.529     albertel 11157:     if (($uri eq '') || 
                   11158: 	(($uri =~ m|^/*adm/|) && 
1.1298    raeburn  11159: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|exttools?)$})) ||
1.1108    raeburn  11160:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11161: 	return undef;
                   11162:     }
1.1261    raeburn  11163:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11164: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11165: 	return undef;
1.288     albertel 11166:     }
1.73      www      11167:     my $filename=$uri;
                   11168:     $uri=~s/\.meta$//;
1.172     www      11169: #
                   11170: # Is the metadata already cached?
1.177     www      11171: # Look at timestamp of caching
1.172     www      11172: # Everything is cached by the main uri, libraries are never directly cached
                   11173: #
1.428     albertel 11174:     if (!defined($liburi)) {
1.599     albertel 11175: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11176: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11177:     }
                   11178:     {
1.1069    www      11179: # Imported parts would go here
1.1070    www      11180:         my %importedids=();
                   11181:         my @origfileimportpartids=();
1.1069    www      11182:         my $importedparts=0;
1.172     www      11183: #
                   11184: # Is this a recursive call for a library?
                   11185: #
1.599     albertel 11186: #	if (! exists($metacache{$uri})) {
                   11187: #	    $metacache{$uri}={};
                   11188: #	}
1.924     albertel 11189: 	my $cachetime = 60*60;
1.171     www      11190:         if ($liburi) {
                   11191: 	    $liburi=&declutter($liburi);
                   11192:             $filename=$liburi;
1.401     bowersj2 11193:         } else {
1.599     albertel 11194: 	    &devalidate_cache_new('meta',$uri);
                   11195: 	    undef(%metaentry);
1.401     bowersj2 11196: 	}
1.140     www      11197:         my %metathesekeys=();
1.73      www      11198:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11199: 	my $metastring;
1.1140    www      11200: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11201: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11202: 	    $metastring = 
1.929     albertel 11203: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11204: 					  ('grade_target' => 'meta'));
                   11205: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11206: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11207:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11208: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11209: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11210: 	    $metastring=&getfile($file);
1.489     albertel 11211: 	}
1.208     albertel 11212:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11213:         my $token;
1.140     www      11214:         undef %metathesekeys;
1.71      www      11215:         while ($token=$parser->get_token) {
1.339     albertel 11216: 	    if ($token->[0] eq 'S') {
                   11217: 		if (defined($token->[2]->{'package'})) {
1.172     www      11218: #
                   11219: # This is a package - get package info
                   11220: #
1.339     albertel 11221: 		    my $package=$token->[2]->{'package'};
                   11222: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11223: 		    if (defined($token->[2]->{'id'})) { 
                   11224: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11225: 		    }
1.599     albertel 11226: 		    if ($metaentry{':packages'}) {
                   11227: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11228: 		    } else {
1.599     albertel 11229: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11230: 		    }
1.736     albertel 11231: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11232: 			my $part=$keyroot;
                   11233: 			$part=~s/^\_//;
1.736     albertel 11234: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11235: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11236: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11237: 			    # ignore package.tab specified default values
                   11238:                             # here &package_tab_default() will fetch those
                   11239: 			    if ($subp eq 'default') { next; }
1.736     albertel 11240: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11241: 			    my $unikey;
                   11242: 			    if ($pack =~ /_0$/) {
                   11243: 				$unikey='parameter_0_'.$name;
                   11244: 				$part=0;
                   11245: 			    } else {
                   11246: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11247: 			    }
1.339     albertel 11248: 			    if ($subp eq 'display') {
                   11249: 				$value.=' [Part: '.$part.']';
                   11250: 			    }
1.599     albertel 11251: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11252: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11253: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11254: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11255: 			    }
1.599     albertel 11256: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11257: 				$metaentry{':'.$unikey}=
                   11258: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11259: 			    }
1.339     albertel 11260: 			}
                   11261: 		    }
                   11262: 		} else {
1.172     www      11263: #
                   11264: # This is not a package - some other kind of start tag
1.339     albertel 11265: #
                   11266: 		    my $entry=$token->[1];
1.1068    www      11267: 		    my $unikey='';
1.175     www      11268: 
1.339     albertel 11269: 		    if ($entry eq 'import') {
1.175     www      11270: #
                   11271: # Importing a library here
1.339     albertel 11272: #
1.1067    www      11273:                         my $location=$parser->get_text('/import');
                   11274:                         my $dir=$filename;
                   11275:                         $dir=~s|[^/]*$||;
                   11276:                         $location=&filelocation($dir,$location);
1.1069    www      11277:                        
1.1068    www      11278:                         my $importmode=$token->[2]->{'importmode'};
                   11279:                         if ($importmode eq 'problem') {
1.1069    www      11280: # Import as problem/response
1.1068    www      11281:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11282:                         } elsif ($importmode eq 'part') {
                   11283: # Import as part(s)
1.1069    www      11284:                            $importedparts=1;
                   11285: # We need to get the original file and the imported file to get the part order correct
                   11286: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   11287: # Load and inspect original file
1.1070    www      11288:                            if ($#origfileimportpartids<0) {
                   11289:                               undef(%importedpartids);
                   11290:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11291:                               my $origfile=&getfile($origfilelocation);
                   11292:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11293:                            }
                   11294: 
1.1069    www      11295: # Load and inspect imported file
                   11296:                            my $impfile=&getfile($location);
                   11297:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11298:                            if ($#impfilepartids>=0) {
                   11299: # This problem had parts
1.1070    www      11300:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11301:                            } else {
                   11302: # Importing by turning a single problem into a problem part
                   11303: # It gets the import-tags ID as part-ID
                   11304:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11305:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11306:                            }
1.1068    www      11307:                         } else {
                   11308: # Normal import
                   11309:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11310:                            if (defined($token->[2]->{'id'})) {
                   11311:                               $unikey.='_'.$token->[2]->{'id'};
                   11312:                            }
1.1067    www      11313:                         }
                   11314: 
1.339     albertel 11315: 			if ($depthcount<20) {
1.736     albertel 11316: 			    my $metadata = 
                   11317: 				&metadata($uri,'keys', $location,$unikey,
                   11318: 					  $depthcount+1);
                   11319: 			    foreach my $meta (split(',',$metadata)) {
                   11320: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   11321: 				$metathesekeys{$meta}=1;
1.339     albertel 11322: 			    }
1.1068    www      11323: 			
                   11324:                         }
1.1067    www      11325: 		    } else {
                   11326: #
                   11327: # Not importing, some other kind of non-package, non-library start tag
                   11328: # 
                   11329:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11330:                         if (defined($token->[2]->{'id'})) {
                   11331:                             $unikey.='_'.$token->[2]->{'id'};
                   11332:                         }
1.339     albertel 11333: 			if (defined($token->[2]->{'name'})) { 
                   11334: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   11335: 			}
                   11336: 			$metathesekeys{$unikey}=1;
1.736     albertel 11337: 			foreach my $param (@{$token->[3]}) {
                   11338: 			    $metaentry{':'.$unikey.'.'.$param} =
                   11339: 				$token->[2]->{$param};
1.339     albertel 11340: 			}
                   11341: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 11342: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 11343: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   11344: 		 # only ws inside the tag, and not in default, so use default
                   11345: 		 # as value
1.599     albertel 11346: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 11347: 			} elsif ( $internaltext =~ /\S/ ) {
                   11348: 		  # something interesting inside the tag
                   11349: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 11350: 			} else {
1.908     albertel 11351: 		  # no interesting values, don't set a default
1.339     albertel 11352: 			}
1.172     www      11353: # end of not-a-package not-a-library import
1.339     albertel 11354: 		    }
1.172     www      11355: # end of not-a-package start tag
1.339     albertel 11356: 		}
1.172     www      11357: # the next is the end of "start tag"
1.339     albertel 11358: 	    }
                   11359: 	}
1.483     albertel 11360: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 11361: 	$extension = lc($extension);
                   11362: 	if ($extension eq 'htm') { $extension='html'; }
                   11363: 
1.737     albertel 11364: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 11365: 	    #no specific packages #how's our extension
                   11366: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 11367: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 11368: 					 \%metathesekeys);
                   11369: 	}
1.883     albertel 11370: 
                   11371: 	if (!exists($metaentry{':packages'})
                   11372: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 11373: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 11374: 		#no specific packages well let's get default then
                   11375: 		if ($key!~/^default&/) { next; }
1.488     albertel 11376: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 11377: 					     \%metathesekeys);
                   11378: 	    }
                   11379: 	}
1.338     www      11380: # are there custom rights to evaluate
1.599     albertel 11381: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 11382: 
1.338     www      11383:     #
                   11384:     # Importing a rights file here
1.339     albertel 11385:     #
                   11386: 	    unless ($depthcount) {
1.599     albertel 11387: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 11388: 		my $dir=$filename;
                   11389: 		$dir=~s|[^/]*$||;
                   11390: 		$location=&filelocation($dir,$location);
1.736     albertel 11391: 		my $rights_metadata =
                   11392: 		    &metadata($uri,'keys',$location,'_rights',
                   11393: 			      $depthcount+1);
                   11394: 		foreach my $rights (split(',',$rights_metadata)) {
                   11395: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   11396: 		    $metathesekeys{$rights}=1;
1.339     albertel 11397: 		}
                   11398: 	    }
                   11399: 	}
1.737     albertel 11400: 	# uniqifiy package listing
                   11401: 	my %seen;
                   11402: 	my @uniq_packages =
                   11403: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   11404: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   11405: 
1.1070    www      11406:         if ($importedparts) {
                   11407: # We had imported parts and need to rebuild partorder
                   11408:            $metaentry{':partorder'}='';
                   11409:            $metathesekeys{'partorder'}=1;
                   11410:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   11411:                if ($origfileimportpartids[$index] eq 'part') {
                   11412: # original part, part of the problem
                   11413:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   11414:                } else {
                   11415: # we have imported parts at this position
                   11416:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   11417:                }
                   11418:            }
                   11419:            $metaentry{':partorder'}=~s/^\,//;
                   11420:         }
                   11421: 
1.737     albertel 11422: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 11423: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  11424: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 11425: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      11426: # this is the end of "was not already recently cached
1.71      www      11427:     }
1.599     albertel 11428:     return $metaentry{':'.$what};
1.261     albertel 11429: }
                   11430: 
1.488     albertel 11431: sub metadata_create_package_def {
1.483     albertel 11432:     my ($uri,$key,$package,$metathesekeys)=@_;
                   11433:     my ($pack,$name,$subp)=split(/\&/,$key);
                   11434:     if ($subp eq 'default') { next; }
                   11435:     
1.599     albertel 11436:     if (defined($metaentry{':packages'})) {
                   11437: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 11438:     } else {
1.599     albertel 11439: 	$metaentry{':packages'}=$package;
1.483     albertel 11440:     }
                   11441:     my $value=$packagetab{$key};
                   11442:     my $unikey;
                   11443:     $unikey='parameter_0_'.$name;
1.599     albertel 11444:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 11445:     $$metathesekeys{$unikey}=1;
1.599     albertel 11446:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11447: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 11448:     }
1.599     albertel 11449:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   11450: 	$metaentry{':'.$unikey}=
                   11451: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 11452:     }
                   11453: }
                   11454: 
1.261     albertel 11455: sub metadata_generate_part0 {
                   11456:     my ($metadata,$metacache,$uri) = @_;
                   11457:     my %allnames;
1.737     albertel 11458:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 11459: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 11460: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   11461: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 11462: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 11463: 	    $allnames{$name}=$part;
                   11464: 	  }
                   11465: 	}
                   11466:     }
                   11467:     foreach my $name (keys(%allnames)) {
                   11468:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 11469:       my $key=":parameter_0_$name";
1.261     albertel 11470:       $$metacache{"$key.part"}='0';
                   11471:       $$metacache{"$key.name"}=$name;
1.428     albertel 11472:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 11473: 					   $allnames{$name}.'_'.$name.
                   11474: 					   '.type'};
1.428     albertel 11475:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 11476: 			     '.display'};
1.644     www      11477:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 11478:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 11479:       $$metacache{"$key.display"}=$olddis;
                   11480:     }
1.71      www      11481: }
                   11482: 
1.764     albertel 11483: # ------------------------------------------------------ Devalidate title cache
                   11484: 
                   11485: sub devalidate_title_cache {
                   11486:     my ($url)=@_;
                   11487:     if (!$env{'request.course.id'}) { return; }
                   11488:     my $symb=&symbread($url);
                   11489:     if (!$symb) { return; }
                   11490:     my $key=$env{'request.course.id'}."\0".$symb;
                   11491:     &devalidate_cache_new('title',$key);
                   11492: }
                   11493: 
1.1014    droeschl 11494: # ------------------------------------------------- Get the title of a course
                   11495: 
                   11496: sub current_course_title {
                   11497:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   11498: }
1.301     www      11499: # ------------------------------------------------- Get the title of a resource
                   11500: 
                   11501: sub gettitle {
                   11502:     my $urlsymb=shift;
                   11503:     my $symb=&symbread($urlsymb);
1.534     albertel 11504:     if ($symb) {
1.620     albertel 11505: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 11506: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 11507: 	if (defined($cached)) { 
                   11508: 	    return $result;
                   11509: 	}
1.534     albertel 11510: 	my ($map,$resid,$url)=&decode_symb($symb);
                   11511: 	my $title='';
1.907     albertel 11512: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   11513: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   11514: 	} else {
                   11515: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11516: 		    &GDBM_READER(),0640)) {
                   11517: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   11518: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   11519: 		untie(%bighash);
                   11520: 	    }
1.534     albertel 11521: 	}
                   11522: 	$title=~s/\&colon\;/\:/gs;
                   11523: 	if ($title) {
1.1159    www      11524: # Remember both $symb and $title for dynamic metadata
                   11525:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      11526:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      11527: # Cache this title and then return it
1.599     albertel 11528: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 11529: 	}
                   11530: 	$urlsymb=$url;
                   11531:     }
                   11532:     my $title=&metadata($urlsymb,'title');
                   11533:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   11534:     return $title;
1.301     www      11535: }
1.613     albertel 11536: 
1.614     albertel 11537: sub get_slot {
                   11538:     my ($which,$cnum,$cdom)=@_;
                   11539:     if (!$cnum || !$cdom) {
1.790     albertel 11540: 	(undef,my $courseid)=&whichuser();
1.620     albertel 11541: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   11542: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 11543:     }
1.703     albertel 11544:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   11545:     my %slotinfo;
                   11546:     if (exists($remembered{$key})) {
                   11547: 	$slotinfo{$which} = $remembered{$key};
                   11548:     } else {
                   11549: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   11550: 	&Apache::lonhomework::showhash(%slotinfo);
                   11551: 	my ($tmp)=keys(%slotinfo);
                   11552: 	if ($tmp=~/^error:/) { return (); }
                   11553: 	$remembered{$key} = $slotinfo{$which};
                   11554:     }
1.616     albertel 11555:     if (ref($slotinfo{$which}) eq 'HASH') {
                   11556: 	return %{$slotinfo{$which}};
                   11557:     }
                   11558:     return $slotinfo{$which};
1.614     albertel 11559: }
1.1150    raeburn  11560: 
                   11561: sub get_reservable_slots {
                   11562:     my ($cnum,$cdom,$uname,$udom) = @_;
                   11563:     my $now = time;
                   11564:     my $reservable_info;
                   11565:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   11566:     if (exists($remembered{$key})) {
                   11567:         $reservable_info = $remembered{$key};
                   11568:     } else {
                   11569:         my %resv;
                   11570:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   11571:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   11572:         $reservable_info = \%resv;
                   11573:         $remembered{$key} = $reservable_info;
                   11574:     }
                   11575:     return $reservable_info;
                   11576: }
                   11577: 
                   11578: sub get_course_slots {
                   11579:     my ($cnum,$cdom) = @_;
                   11580:     my $hashid=$cnum.':'.$cdom;
                   11581:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   11582:     if (defined($cached)) {
                   11583:         if (ref($result) eq 'HASH') {
                   11584:             return %{$result};
                   11585:         }
                   11586:     } else {
                   11587:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   11588:         my ($tmp) = keys(%slots);
                   11589:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  11590:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  11591:             return %slots;
                   11592:         }
                   11593:     }
                   11594:     return;
                   11595: }
                   11596: 
                   11597: sub devalidate_slots_cache {
                   11598:     my ($cnum,$cdom)=@_;
                   11599:     my $hashid=$cnum.':'.$cdom;
                   11600:     &devalidate_cache_new('allslots',$hashid);
                   11601: }
                   11602: 
1.1181    raeburn  11603: sub get_coursechange {
                   11604:     my ($cdom,$cnum) = @_;
                   11605:     if ($cdom eq '' || $cnum eq '') {
                   11606:         return unless ($env{'request.course.id'});
                   11607:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   11608:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11609:     }
                   11610:     my $hashid=$cdom.'_'.$cnum;
                   11611:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   11612:     if ((defined($cached)) && ($change ne '')) {
                   11613:         return $change;
                   11614:     } else {
                   11615:         my %crshash;
                   11616:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   11617:         if ($crshash{'internal.contentchange'} eq '') {
                   11618:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   11619:             if ($change eq '') {
                   11620:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   11621:                 $change = $crshash{'internal.created'};
                   11622:             }
                   11623:         } else {
                   11624:             $change = $crshash{'internal.contentchange'};
                   11625:         }
                   11626:         my $cachetime = 600;
                   11627:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   11628:     }
                   11629:     return $change;
                   11630: }
                   11631: 
                   11632: sub devalidate_coursechange_cache {
                   11633:     my ($cnum,$cdom)=@_;
                   11634:     my $hashid=$cnum.':'.$cdom;
                   11635:     &devalidate_cache_new('crschange',$hashid);
                   11636: }
                   11637: 
1.31      www      11638: # ------------------------------------------------- Update symbolic store links
                   11639: 
                   11640: sub symblist {
                   11641:     my ($mapname,%newhash)=@_;
1.438     www      11642:     $mapname=&deversion(&declutter($mapname));
1.31      www      11643:     my %hash;
1.620     albertel 11644:     if (($env{'request.course.fn'}) && (%newhash)) {
                   11645:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11646:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  11647: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 11648: 		next if ($url eq 'last_known'
                   11649: 			 && $env{'form.no_update_last_known'});
                   11650: 		$hash{declutter($url)}=&encode_symb($mapname,
                   11651: 						    $newhash{$url}->[1],
                   11652: 						    $newhash{$url}->[0]);
1.191     harris41 11653:             }
1.31      www      11654:             if (untie(%hash)) {
                   11655: 		return 'ok';
                   11656:             }
                   11657:         }
                   11658:     }
                   11659:     return 'error';
1.212     www      11660: }
                   11661: 
                   11662: # --------------------------------------------------------------- Verify a symb
                   11663: 
                   11664: sub symbverify {
1.1190    raeburn  11665:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      11666:     my $thisfn=$thisurl;
1.439     www      11667:     $thisfn=&declutter($thisfn);
1.215     www      11668: # direct jump to resource in page or to a sequence - will construct own symbs
                   11669:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   11670: # check URL part
1.409     www      11671:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      11672: 
1.431     www      11673:     unless ($url eq $thisfn) { return 0; }
1.213     www      11674: 
1.216     www      11675:     $symb=&symbclean($symb);
1.510     www      11676:     $thisurl=&deversion($thisurl);
1.439     www      11677:     $thisfn=&deversion($thisfn);
1.213     www      11678: 
                   11679:     my %bighash;
                   11680:     my $okay=0;
1.431     www      11681: 
1.620     albertel 11682:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11683:                             &GDBM_READER(),0640)) {
1.1204    raeburn  11684:         my $noclutter;
1.1032    raeburn  11685:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   11686:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  11687:             if ($map =~ m{^uploaded/.+\.page$}) {
                   11688:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   11689:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   11690:                 $noclutter = 1;
                   11691:             }
                   11692:         }
                   11693:         my $ids;
                   11694:         if ($noclutter) {
                   11695:             $ids=$bighash{'ids_'.$thisurl};
                   11696:         } else {
                   11697:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  11698:         }
1.1102    raeburn  11699:         unless ($ids) {
                   11700:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   11701:             $ids=$bighash{$idkey};
1.216     www      11702:         }
                   11703:         if ($ids) {
                   11704: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  11705:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  11706:                 $symb =~ s/\?.+$//;
1.1202    raeburn  11707:             }
1.800     albertel 11708: 	    foreach my $id (split(/\,/,$ids)) {
                   11709: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      11710:                if (
                   11711:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  11712:    eq $symb) {
                   11713:                    if (ref($encstate)) {
                   11714:                        $$encstate = $bighash{'encrypted_'.$id};
                   11715:                    }
1.620     albertel 11716: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  11717: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   11718:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  11719: 		       $okay=1;
1.1202    raeburn  11720:                        last;
1.582     albertel 11721: 		   }
                   11722: 	       }
1.216     www      11723: 	   }
                   11724:         }
1.213     www      11725: 	untie(%bighash);
                   11726:     }
                   11727:     return $okay;
1.31      www      11728: }
                   11729: 
1.210     www      11730: # --------------------------------------------------------------- Clean-up symb
                   11731: 
                   11732: sub symbclean {
                   11733:     my $symb=shift;
1.568     albertel 11734:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      11735: # remove version from map
                   11736:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      11737: 
1.210     www      11738: # remove version from URL
                   11739:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      11740: 
1.507     www      11741: # remove wrapper
                   11742: 
1.510     www      11743:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 11744:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      11745:     return $symb;
1.409     www      11746: }
                   11747: 
                   11748: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 11749: 
                   11750: sub encode_symb {
                   11751:     my ($map,$resid,$url)=@_;
                   11752:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   11753: }
1.409     www      11754: 
                   11755: sub decode_symb {
1.568     albertel 11756:     my $symb=shift;
                   11757:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   11758:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      11759:     return (&fixversion($map),$resid,&fixversion($url));
                   11760: }
                   11761: 
                   11762: sub fixversion {
                   11763:     my $fn=shift;
1.609     banghart 11764:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      11765:     my %bighash;
                   11766:     my $uri=&clutter($fn);
1.620     albertel 11767:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      11768: # is this cached?
1.599     albertel 11769:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      11770:     if (defined($cached)) { return $result; }
                   11771: # unfortunately not cached, or expired
1.620     albertel 11772:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      11773: 	    &GDBM_READER(),0640)) {
                   11774:  	if ($bighash{'version_'.$uri}) {
                   11775:  	    my $version=$bighash{'version_'.$uri};
1.444     www      11776:  	    unless (($version eq 'mostrecent') || 
                   11777: 		    ($version==&getversion($uri))) {
1.440     www      11778:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   11779:  	    }
                   11780:  	}
                   11781:  	untie %bighash;
1.413     www      11782:     }
1.599     albertel 11783:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      11784: }
                   11785: 
                   11786: sub deversion {
                   11787:     my $url=shift;
                   11788:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   11789:     return $url;
1.210     www      11790: }
                   11791: 
1.31      www      11792: # ------------------------------------------------------ Return symb list entry
                   11793: 
                   11794: sub symbread {
1.1282    raeburn  11795:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265    raeburn  11796:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1282    raeburn  11797:     if (defined($env{$cache_str})) {
                   11798:         if ($ignorecachednull) {
                   11799:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   11800:         } else {
                   11801:             return $env{$cache_str};
                   11802:         }
                   11803:     }
1.242     www      11804: # no filename provided? try from environment
1.1265    raeburn  11805:     unless ($thisfn) {
1.620     albertel 11806:         if ($env{'request.symb'}) {
                   11807: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 11808: 	}
1.620     albertel 11809: 	$thisfn=$env{'request.filename'};
1.44      www      11810:     }
1.569     albertel 11811:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      11812: # is that filename actually a symb? Verify, clean, and return
                   11813:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 11814: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 11815: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 11816: 	}
1.242     www      11817:     }
1.44      www      11818:     $thisfn=declutter($thisfn);
1.31      www      11819:     my %hash;
1.37      www      11820:     my %bighash;
                   11821:     my $syval='';
1.620     albertel 11822:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  11823:         my $targetfn = $thisfn;
1.609     banghart 11824:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  11825:             $targetfn = 'adm/wrapper/'.$thisfn;
                   11826:         }
1.687     albertel 11827: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   11828: 	    $targetfn=$1;
                   11829: 	}
1.620     albertel 11830:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11831:                       &GDBM_READER(),0640)) {
1.481     raeburn  11832: 	    $syval=$hash{$targetfn};
1.37      www      11833:             untie(%hash);
                   11834:         }
                   11835: # ---------------------------------------------------------- There was an entry
                   11836:         if ($syval) {
1.601     albertel 11837: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 11838: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  11839: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11840: 		    #return $env{$cache_str}='';
1.601     albertel 11841: 		#}    
                   11842: 		#$syval.=$1;
                   11843: 	    #}
1.37      www      11844:         } else {
                   11845: # ------------------------------------------------------- Was not in symb table
1.620     albertel 11846:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11847:                             &GDBM_READER(),0640)) {
1.37      www      11848: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      11849:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      11850:               unless ($ids) { 
                   11851:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      11852:               }
                   11853:               unless ($ids) {
                   11854: # alias?
                   11855: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      11856:               }
1.37      www      11857:               if ($ids) {
                   11858: # ------------------------------------------------------------------- Has ID(s)
                   11859:                  my @possibilities=split(/\,/,$ids);
1.39      www      11860:                  if ($#possibilities==0) {
                   11861: # ----------------------------------------------- There is only one possibility
1.37      www      11862: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 11863: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11864: 						    $resid,$thisfn);
1.1282    raeburn  11865:                      if (ref($possibles) eq 'HASH') {
                   11866:                          $possibles->{$syval} = 1;    
                   11867:                      }
                   11868:                      if ($checkforblock) {
                   11869:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   11870:                          if (@blockers) {
                   11871:                              $syval = '';
                   11872:                              return;
                   11873:                          }
                   11874:                      }
                   11875:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      11876: # ------------------------------------------ There is more than one possibility
                   11877:                      my $realpossible=0;
1.800     albertel 11878:                      foreach my $id (@possibilities) {
                   11879: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  11880:                          my $canaccess;
                   11881:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   11882:                              $canaccess = 1;
                   11883:                          } else { 
                   11884:                              $canaccess = &allowed('bre',$file);
                   11885:                          }
                   11886:                          if ($canaccess) {
                   11887:          		     my ($mapid,$resid)=split(/\./,$id);
                   11888:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   11889:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11890: 						             $resid,$thisfn);
                   11891:                                  if (ref($possibles) eq 'HASH') {
                   11892:                                      $possibles->{$syval} = 1;
                   11893:                                  }
                   11894:                                  if ($checkforblock) {
                   11895:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   11896:                                      unless (@blockers > 0) {
                   11897:                                          $syval = $poss_syval;
                   11898:                                          $realpossible++;
                   11899:                                      }
                   11900:                                  } else {
                   11901:                                      $syval = $poss_syval;
                   11902:                                      $realpossible++;
                   11903:                                  }
                   11904:                              }
1.39      www      11905: 			 }
1.191     harris41 11906:                      }
1.39      www      11907: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      11908:                  } else {
                   11909:                      $syval='';
1.37      www      11910:                  }
                   11911: 	      }
1.1282    raeburn  11912:               untie(%bighash);
1.481     raeburn  11913:            }
1.31      www      11914:         }
1.62      www      11915:         if ($syval) {
1.620     albertel 11916: 	    return $env{$cache_str}=$syval;
1.62      www      11917:         }
1.31      www      11918:     }
1.949     raeburn  11919:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11920:     return $env{$cache_str}='';
1.31      www      11921: }
                   11922: 
                   11923: # ---------------------------------------------------------- Return random seed
                   11924: 
1.32      www      11925: sub numval {
                   11926:     my $txt=shift;
                   11927:     $txt=~tr/A-J/0-9/;
                   11928:     $txt=~tr/a-j/0-9/;
                   11929:     $txt=~tr/K-T/0-9/;
                   11930:     $txt=~tr/k-t/0-9/;
                   11931:     $txt=~tr/U-Z/0-5/;
                   11932:     $txt=~tr/u-z/0-5/;
                   11933:     $txt=~s/\D//g;
1.564     albertel 11934:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      11935:     return int($txt);
1.368     albertel 11936: }
                   11937: 
1.484     albertel 11938: sub numval2 {
                   11939:     my $txt=shift;
                   11940:     $txt=~tr/A-J/0-9/;
                   11941:     $txt=~tr/a-j/0-9/;
                   11942:     $txt=~tr/K-T/0-9/;
                   11943:     $txt=~tr/k-t/0-9/;
                   11944:     $txt=~tr/U-Z/0-5/;
                   11945:     $txt=~tr/u-z/0-5/;
                   11946:     $txt=~s/\D//g;
                   11947:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11948:     my $total;
                   11949:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 11950:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 11951:     return int($total);
                   11952: }
                   11953: 
1.575     albertel 11954: sub numval3 {
                   11955:     use integer;
                   11956:     my $txt=shift;
                   11957:     $txt=~tr/A-J/0-9/;
                   11958:     $txt=~tr/a-j/0-9/;
                   11959:     $txt=~tr/K-T/0-9/;
                   11960:     $txt=~tr/k-t/0-9/;
                   11961:     $txt=~tr/U-Z/0-5/;
                   11962:     $txt=~tr/u-z/0-5/;
                   11963:     $txt=~s/\D//g;
                   11964:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11965:     my $total;
                   11966:     foreach my $val (@txts) { $total+=$val; }
                   11967:     if ($_64bit) { $total=(($total<<32)>>32); }
                   11968:     return $total;
                   11969: }
                   11970: 
1.675     albertel 11971: sub digest {
                   11972:     my ($data)=@_;
                   11973:     my $digest=&Digest::MD5::md5($data);
                   11974:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   11975:     my ($e,$f);
                   11976:     {
                   11977:         use integer;
                   11978:         $e=($a+$b);
                   11979:         $f=($c+$d);
                   11980:         if ($_64bit) {
                   11981:             $e=(($e<<32)>>32);
                   11982:             $f=(($f<<32)>>32);
                   11983:         }
                   11984:     }
                   11985:     if (wantarray) {
                   11986: 	return ($e,$f);
                   11987:     } else {
                   11988: 	my $g;
                   11989: 	{
                   11990: 	    use integer;
                   11991: 	    $g=($e+$f);
                   11992: 	    if ($_64bit) {
                   11993: 		$g=(($g<<32)>>32);
                   11994: 	    }
                   11995: 	}
                   11996: 	return $g;
                   11997:     }
                   11998: }
                   11999: 
1.368     albertel 12000: sub latest_rnd_algorithm_id {
1.675     albertel 12001:     return '64bit5';
1.366     albertel 12002: }
1.32      www      12003: 
1.503     albertel 12004: sub get_rand_alg {
                   12005:     my ($courseid)=@_;
1.790     albertel 12006:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12007:     if ($courseid) {
1.620     albertel 12008: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12009:     }
                   12010:     return &latest_rnd_algorithm_id();
                   12011: }
                   12012: 
1.562     albertel 12013: sub validCODE {
                   12014:     my ($CODE)=@_;
                   12015:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12016:     return 0;
                   12017: }
                   12018: 
1.491     albertel 12019: sub getCODE {
1.620     albertel 12020:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12021:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12022: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12023: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12024: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12025:     }
                   12026:     return undef;
                   12027: }
1.1133    foxr     12028: #
                   12029: #  Determines the random seed for a specific context:
                   12030: #
                   12031: # parameters:
                   12032: #   symb      - in course context the symb for the seed.
                   12033: #   course_id - The course id of the form domain_coursenum.
                   12034: #   domain    - Domain for the user.
                   12035: #   course    - Course for the user.
                   12036: #   cenv      - environment of the course.
                   12037: #
                   12038: # NOTE:
                   12039: #   All parameters are picked out of the environment if missing
                   12040: #   or not defined.
                   12041: #   If a symb cannot be determined the current time is used instead.
                   12042: #
                   12043: #  For a given well defined symb, courside, domain, username,
                   12044: #  and course environment, the seed is reproducible.
                   12045: #
1.31      www      12046: sub rndseed {
1.1133    foxr     12047:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12048:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12049:     if (!defined($symb)) {
1.366     albertel 12050: 	unless ($symb=$wsymb) { return time; }
                   12051:     }
1.1146    foxr     12052:     if (!defined $courseid) { 
                   12053: 	$courseid=$wcourseid; 
                   12054:     }
                   12055:     if (!defined $domain) { $domain=$wdomain; }
                   12056:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12057: 
                   12058:     my $which;
                   12059:     if (defined($cenv->{'rndseed'})) {
                   12060: 	$which = $cenv->{'rndseed'};
                   12061:     } else {
                   12062: 	$which =&get_rand_alg($courseid);
                   12063:     }
1.491     albertel 12064:     if (defined(&getCODE())) {
1.1133    foxr     12065: 
1.675     albertel 12066: 	if ($which eq '64bit5') {
                   12067: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12068: 	} elsif ($which eq '64bit4') {
1.575     albertel 12069: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12070: 	} else {
                   12071: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12072: 	}
1.675     albertel 12073:     } elsif ($which eq '64bit5') {
                   12074: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12075:     } elsif ($which eq '64bit4') {
                   12076: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12077:     } elsif ($which eq '64bit3') {
                   12078: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12079:     } elsif ($which eq '64bit2') {
                   12080: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12081:     } elsif ($which eq '64bit') {
                   12082: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12083:     }
                   12084:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12085: }
                   12086: 
                   12087: sub rndseed_32bit {
                   12088:     my ($symb,$courseid,$domain,$username)=@_;
                   12089:     {
                   12090: 	use integer;
                   12091: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12092: 	my $symbseed=numval($symb) << 22;
                   12093: 	my $namechck=unpack("%32C*",$username) << 17;
                   12094: 	my $nameseed=numval($username) << 12;
                   12095: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12096: 	my $courseseed=unpack("%32C*",$courseid);
                   12097: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12098: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12099: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12100: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12101: 	return $num;
                   12102:     }
                   12103: }
                   12104: 
                   12105: sub rndseed_64bit {
                   12106:     my ($symb,$courseid,$domain,$username)=@_;
                   12107:     {
                   12108: 	use integer;
                   12109: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12110: 	my $symbseed=numval($symb) << 10;
                   12111: 	my $namechck=unpack("%32S*",$username);
                   12112: 	
                   12113: 	my $nameseed=numval($username) << 21;
                   12114: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12115: 	my $courseseed=unpack("%32S*",$courseid);
                   12116: 	
                   12117: 	my $num1=$symbchck+$symbseed+$namechck;
                   12118: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12119: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12120: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12121: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12122: 	return "$num1,$num2";
1.155     albertel 12123:     }
1.366     albertel 12124: }
                   12125: 
1.443     albertel 12126: sub rndseed_64bit2 {
                   12127:     my ($symb,$courseid,$domain,$username)=@_;
                   12128:     {
                   12129: 	use integer;
                   12130: 	# strings need to be an even # of cahracters long, it it is odd the
                   12131:         # last characters gets thrown away
                   12132: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12133: 	my $symbseed=numval($symb) << 10;
                   12134: 	my $namechck=unpack("%32S*",$username.' ');
                   12135: 	
                   12136: 	my $nameseed=numval($username) << 21;
1.501     albertel 12137: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12138: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12139: 	
                   12140: 	my $num1=$symbchck+$symbseed+$namechck;
                   12141: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12142: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12143: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12144: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12145: 	return "$num1,$num2";
                   12146:     }
                   12147: }
                   12148: 
                   12149: sub rndseed_64bit3 {
                   12150:     my ($symb,$courseid,$domain,$username)=@_;
                   12151:     {
                   12152: 	use integer;
                   12153: 	# strings need to be an even # of cahracters long, it it is odd the
                   12154:         # last characters gets thrown away
                   12155: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12156: 	my $symbseed=numval2($symb) << 10;
                   12157: 	my $namechck=unpack("%32S*",$username.' ');
                   12158: 	
                   12159: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12160: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12161: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12162: 	
                   12163: 	my $num1=$symbchck+$symbseed+$namechck;
                   12164: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12165: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12166: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12167: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12168: 	
1.503     albertel 12169: 	return "$num1:$num2";
1.443     albertel 12170:     }
                   12171: }
                   12172: 
1.575     albertel 12173: sub rndseed_64bit4 {
                   12174:     my ($symb,$courseid,$domain,$username)=@_;
                   12175:     {
                   12176: 	use integer;
                   12177: 	# strings need to be an even # of cahracters long, it it is odd the
                   12178:         # last characters gets thrown away
                   12179: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12180: 	my $symbseed=numval3($symb) << 10;
                   12181: 	my $namechck=unpack("%32S*",$username.' ');
                   12182: 	
                   12183: 	my $nameseed=numval3($username) << 21;
                   12184: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12185: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12186: 	
                   12187: 	my $num1=$symbchck+$symbseed+$namechck;
                   12188: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12189: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12190: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12191: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12192: 	
1.575     albertel 12193: 	return "$num1:$num2";
                   12194:     }
                   12195: }
                   12196: 
1.675     albertel 12197: sub rndseed_64bit5 {
                   12198:     my ($symb,$courseid,$domain,$username)=@_;
                   12199:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12200:     return "$num1:$num2";
                   12201: }
                   12202: 
1.366     albertel 12203: sub rndseed_CODE_64bit {
                   12204:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12205:     {
1.366     albertel 12206: 	use integer;
1.443     albertel 12207: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12208: 	my $symbseed=numval2($symb);
1.491     albertel 12209: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12210: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12211: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12212: 	my $num1=$symbseed+$CODEchck;
                   12213: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12214: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12215: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12216: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12217: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12218: 	return "$num1:$num2";
1.366     albertel 12219:     }
                   12220: }
                   12221: 
1.575     albertel 12222: sub rndseed_CODE_64bit4 {
                   12223:     my ($symb,$courseid,$domain,$username)=@_;
                   12224:     {
                   12225: 	use integer;
                   12226: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12227: 	my $symbseed=numval3($symb);
                   12228: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12229: 	my $CODEseed=numval3(&getCODE());
                   12230: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12231: 	my $num1=$symbseed+$CODEchck;
                   12232: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12233: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12234: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12235: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12236: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12237: 	return "$num1:$num2";
                   12238:     }
                   12239: }
                   12240: 
1.675     albertel 12241: sub rndseed_CODE_64bit5 {
                   12242:     my ($symb,$courseid,$domain,$username)=@_;
                   12243:     my $code = &getCODE();
                   12244:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12245:     return "$num1:$num2";
                   12246: }
                   12247: 
1.366     albertel 12248: sub setup_random_from_rndseed {
                   12249:     my ($rndseed)=@_;
1.503     albertel 12250:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  12251:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12252:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12253:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   12254:         } else {
                   12255:             &Math::Random::random_set_seed($num1,$num2);
                   12256:         }
1.366     albertel 12257:     } else {
                   12258: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12259:     }
1.36      albertel 12260: }
                   12261: 
1.474     albertel 12262: sub latest_receipt_algorithm_id {
1.835     albertel 12263:     return 'receipt3';
1.474     albertel 12264: }
                   12265: 
1.480     www      12266: sub recunique {
                   12267:     my $fucourseid=shift;
                   12268:     my $unique;
1.835     albertel 12269:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   12270: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12271: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      12272:     } else {
                   12273: 	$unique=$perlvar{'lonReceipt'};
                   12274:     }
                   12275:     return unpack("%32C*",$unique);
                   12276: }
                   12277: 
                   12278: sub recprefix {
                   12279:     my $fucourseid=shift;
                   12280:     my $prefix;
1.835     albertel 12281:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   12282: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12283: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      12284:     } else {
                   12285: 	$prefix=$perlvar{'lonHostID'};
                   12286:     }
                   12287:     return unpack("%32C*",$prefix);
                   12288: }
                   12289: 
1.76      www      12290: sub ireceipt {
1.474     albertel 12291:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 12292: 
                   12293:     my $return =&recprefix($fucourseid).'-';
                   12294: 
                   12295:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   12296: 	$env{'request.state'} eq 'construct') {
                   12297: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   12298: 	return $return;
                   12299:     }
                   12300: 
1.76      www      12301:     my $cuname=unpack("%32C*",$funame);
                   12302:     my $cudom=unpack("%32C*",$fudom);
                   12303:     my $cucourseid=unpack("%32C*",$fucourseid);
                   12304:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      12305:     my $cunique=&recunique($fucourseid);
1.474     albertel 12306:     my $cpart=unpack("%32S*",$part);
1.835     albertel 12307:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   12308: 
1.790     albertel 12309: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 12310: 			       
                   12311: 	$return.= ($cunique%$cuname+
                   12312: 		   $cunique%$cudom+
                   12313: 		   $cusymb%$cuname+
                   12314: 		   $cusymb%$cudom+
                   12315: 		   $cucourseid%$cuname+
                   12316: 		   $cucourseid%$cudom+
                   12317: 		   $cpart%$cuname+
                   12318: 		   $cpart%$cudom);
                   12319:     } else {
                   12320: 	$return.= ($cunique%$cuname+
                   12321: 		   $cunique%$cudom+
                   12322: 		   $cusymb%$cuname+
                   12323: 		   $cusymb%$cudom+
                   12324: 		   $cucourseid%$cuname+
                   12325: 		   $cucourseid%$cudom);
                   12326:     }
                   12327:     return $return;
1.76      www      12328: }
                   12329: 
                   12330: sub receipt {
1.474     albertel 12331:     my ($part)=@_;
1.790     albertel 12332:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 12333:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      12334: }
1.260     ng       12335: 
1.790     albertel 12336: sub whichuser {
                   12337:     my ($passedsymb)=@_;
                   12338:     my ($symb,$courseid,$domain,$name,$publicuser);
                   12339:     if (defined($env{'form.grade_symb'})) {
                   12340: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   12341: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   12342: 	if (!$allowed &&
                   12343: 	    exists($env{'request.course.sec'}) &&
                   12344: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   12345: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   12346: 			      '/'.$env{'request.course.sec'});
                   12347: 	}
                   12348: 	if ($allowed) {
                   12349: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   12350: 	    $courseid=$tmp_courseid;
                   12351: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   12352: 	    ($name)=&get_env_multiple('form.grade_username');
                   12353: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   12354: 	}
                   12355:     }
                   12356:     if (!$passedsymb) {
                   12357: 	$symb=&symbread();
                   12358:     } else {
                   12359: 	$symb=$passedsymb;
                   12360:     }
                   12361:     $courseid=$env{'request.course.id'};
                   12362:     $domain=$env{'user.domain'};
                   12363:     $name=$env{'user.name'};
                   12364:     if ($name eq 'public' && $domain eq 'public') {
                   12365: 	if (!defined($env{'form.username'})) {
                   12366: 	    $env{'form.username'}.=time.rand(10000000);
                   12367: 	}
                   12368: 	$name.=$env{'form.username'};
                   12369:     }
                   12370:     return ($symb,$courseid,$domain,$name,$publicuser);
                   12371: 
                   12372: }
                   12373: 
1.36      albertel 12374: # ------------------------------------------------------------ Serves up a file
1.472     albertel 12375: # returns either the contents of the file or 
                   12376: # -1 if the file doesn't exist
1.481     raeburn  12377: #
                   12378: # if the target is a file that was uploaded via DOCS, 
                   12379: # a check will be made to see if a current copy exists on the local server,
                   12380: # if it does this will be served, otherwise a copy will be retrieved from
                   12381: # the home server for the course and stored in /home/httpd/html/userfiles on
                   12382: # the local server.   
1.472     albertel 12383: 
1.36      albertel 12384: sub getfile {
1.538     albertel 12385:     my ($file) = @_;
1.609     banghart 12386:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 12387:     &repcopy($file);
                   12388:     return &readfile($file);
                   12389: }
                   12390: 
                   12391: sub repcopy_userfile {
                   12392:     my ($file)=@_;
1.1142    raeburn  12393:     my $londocroot = $perlvar{'lonDocRoot'};
                   12394:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  12395:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 12396:     my ($cdom,$cnum,$filename) = 
1.811     albertel 12397: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 12398:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   12399:     if (-e "$file") {
1.828     www      12400: # we already have a local copy, check it out
1.538     albertel 12401: 	my @fileinfo = stat($file);
1.828     www      12402: 	my $rtncode;
                   12403: 	my $info;
1.538     albertel 12404: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 12405: 	if ($lwpresp ne 'ok') {
1.828     www      12406: # there is no such file anymore, even though we had a local copy
1.482     albertel 12407: 	    if ($rtncode eq '404') {
1.538     albertel 12408: 		unlink($file);
1.482     albertel 12409: 	    }
                   12410: 	    return -1;
                   12411: 	}
                   12412: 	if ($info < $fileinfo[9]) {
1.828     www      12413: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  12414: 	    return 'ok';
1.828     www      12415: 	} else {
                   12416: # the file is outdated, get rid of it
                   12417: 	    unlink($file);
1.482     albertel 12418: 	}
1.828     www      12419:     }
                   12420: # one way or the other, at this point, we don't have the file
                   12421: # construct the correct path for the file
                   12422:     my @parts = ($cdom,$cnum); 
                   12423:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   12424: 	push @parts, split(/\//,$1);
                   12425:     }
                   12426:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   12427:     foreach my $part (@parts) {
                   12428: 	$path .= '/'.$part;
                   12429: 	if (!-e $path) {
                   12430: 	    mkdir($path,0770);
1.482     albertel 12431: 	}
                   12432:     }
1.828     www      12433: # now the path exists for sure
                   12434: # get a user agent
                   12435:     my $ua=new LWP::UserAgent;
                   12436:     my $transferfile=$file.'.in.transfer';
                   12437: # FIXME: this should flock
                   12438:     if (-e $transferfile) { return 'ok'; }
                   12439:     my $request;
                   12440:     $uri=~s/^\///;
1.980     raeburn  12441:     my $homeserver = &homeserver($cnum,$cdom);
                   12442:     my $protocol = $protocol{$homeserver};
                   12443:     $protocol = 'http' if ($protocol ne 'https');
                   12444:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      12445:     my $response=$ua->request($request,$transferfile);
                   12446: # did it work?
                   12447:     if ($response->is_error()) {
                   12448: 	unlink($transferfile);
                   12449: 	&logthis("Userfile repcopy failed for $uri");
                   12450: 	return -1;
                   12451:     }
                   12452: # worked, rename the transfer file
                   12453:     rename($transferfile,$file);
1.607     raeburn  12454:     return 'ok';
1.481     raeburn  12455: }
                   12456: 
1.517     albertel 12457: sub tokenwrapper {
                   12458:     my $uri=shift;
1.980     raeburn  12459:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 12460:     $uri=~s|^/||;
1.620     albertel 12461:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 12462:     my $token=$1;
1.552     albertel 12463:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   12464:     if ($udom && $uname && $file) {
                   12465: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  12466:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  12467:         my $homeserver = &homeserver($uname,$udom);
                   12468:         my $protocol = $protocol{$homeserver};
                   12469:         $protocol = 'http' if ($protocol ne 'https');
                   12470:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 12471:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   12472:                                '&tokenissued='.$perlvar{'lonHostID'};
                   12473:     } else {
                   12474:         return '/adm/notfound.html';
                   12475:     }
                   12476: }
                   12477: 
1.828     www      12478: # call with reqtype HEAD: get last modification time
                   12479: # call with reqtype GET: get the file contents
                   12480: # Do not call this with reqtype GET for large files! It loads everything into memory
                   12481: #
1.481     raeburn  12482: sub getuploaded {
                   12483:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   12484:     $uri=~s/^\///;
1.980     raeburn  12485:     my $homeserver = &homeserver($cnum,$cdom);
                   12486:     my $protocol = $protocol{$homeserver};
                   12487:     $protocol = 'http' if ($protocol ne 'https');
                   12488:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  12489:     my $ua=new LWP::UserAgent;
                   12490:     my $request=new HTTP::Request($reqtype,$uri);
                   12491:     my $response=$ua->request($request);
                   12492:     $$rtncode = $response->code;
1.482     albertel 12493:     if (! $response->is_success()) {
                   12494: 	return 'failed';
                   12495:     }      
                   12496:     if ($reqtype eq 'HEAD') {
1.486     www      12497: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 12498:     } elsif ($reqtype eq 'GET') {
                   12499: 	$$info = $response->content;
1.472     albertel 12500:     }
1.482     albertel 12501:     return 'ok';
1.36      albertel 12502: }
                   12503: 
1.481     raeburn  12504: sub readfile {
                   12505:     my $file = shift;
                   12506:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   12507:     my $fh;
                   12508:     open($fh,"<$file");
                   12509:     my $a='';
1.800     albertel 12510:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  12511:     return $a;
                   12512: }
                   12513: 
1.36      albertel 12514: sub filelocation {
1.590     banghart 12515:     my ($dir,$file) = @_;
                   12516:     my $location;
                   12517:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 12518: 
                   12519:     if ($file =~ m-^/adm/-) {
                   12520: 	$file=~s-^/adm/wrapper/-/-;
                   12521: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   12522:     }
1.882     albertel 12523: 
1.1139    www      12524:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  12525:         $location = $file;
1.609     banghart 12526:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 12527:         my ($udom,$uname,$filename)=
1.811     albertel 12528:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 12529:         my $home=&homeserver($uname,$udom);
                   12530:         my $is_me=0;
                   12531:         my @ids=&current_machine_ids();
                   12532:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   12533:         if ($is_me) {
1.1117    foxr     12534:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 12535:         } else {
                   12536:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   12537:   	      $udom.'/'.$uname.'/'.$filename;
                   12538:         }
1.882     albertel 12539:     } elsif ($file =~ m-^/adm/-) {
                   12540: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 12541:     } else {
                   12542:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      12543:         $file=~s:^/(res|priv)/:/:;
                   12544:         my $space=$1;
1.590     banghart 12545:         if ( !( $file =~ m:^/:) ) {
                   12546:             $location = $dir. '/'.$file;
                   12547:         } else {
1.1142    raeburn  12548:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 12549:         }
1.59      albertel 12550:     }
1.590     banghart 12551:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 12552:     while ($location=~m{/\.\./}) {
                   12553: 	if ($location =~ m{/[^/]+/\.\./}) {
                   12554: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   12555: 	} else {
                   12556: 	    $location=~ s{/\.\./}{/}g;
                   12557: 	}
                   12558:     } #remove dir/..
1.590     banghart 12559:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   12560:     return $location;
1.46      www      12561: }
1.36      albertel 12562: 
1.46      www      12563: sub hreflocation {
                   12564:     my ($dir,$file)=@_;
1.980     raeburn  12565:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 12566: 	$file=filelocation($dir,$file);
1.700     albertel 12567:     } elsif ($file=~m-^/adm/-) {
                   12568: 	$file=~s-^/adm/wrapper/-/-;
                   12569: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 12570:     }
                   12571:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   12572: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   12573:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  12574: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   12575: 	        {/uploaded/$1/$2/}x;
1.46      www      12576:     }
1.913     albertel 12577:     if ($file=~ m{^/userfiles/}) {
                   12578: 	$file =~ s{^/userfiles/}{/uploaded/};
                   12579:     }
1.462     albertel 12580:     return $file;
1.465     albertel 12581: }
                   12582: 
1.1139    www      12583: 
                   12584: 
                   12585: 
                   12586: 
1.465     albertel 12587: sub current_machine_domains {
1.853     albertel 12588:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   12589: }
                   12590: 
                   12591: sub machine_domains {
                   12592:     my ($hostname) = @_;
1.465     albertel 12593:     my @domains;
1.838     albertel 12594:     my %hostname = &all_hostnames();
1.465     albertel 12595:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  12596: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 12597: 	if ($hostname eq $name) {
1.844     albertel 12598: 	    push(@domains,&host_domain($id));
1.465     albertel 12599: 	}
                   12600:     }
                   12601:     return @domains;
                   12602: }
                   12603: 
                   12604: sub current_machine_ids {
1.853     albertel 12605:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   12606: }
                   12607: 
                   12608: sub machine_ids {
                   12609:     my ($hostname) = @_;
                   12610:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 12611:     my @ids;
1.888     albertel 12612:     my %name_to_host = &all_names();
1.889     albertel 12613:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   12614: 	return @{ $name_to_host{$hostname} };
                   12615:     }
                   12616:     return;
1.31      www      12617: }
                   12618: 
1.824     raeburn  12619: sub additional_machine_domains {
                   12620:     my @domains;
                   12621:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   12622:     while( my $line = <$fh>) {
                   12623:         $line =~ s/\s//g;
                   12624:         push(@domains,$line);
                   12625:     }
                   12626:     return @domains;
                   12627: }
                   12628: 
                   12629: sub default_login_domain {
                   12630:     my $domain = $perlvar{'lonDefDomain'};
                   12631:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   12632:     foreach my $posdom (&current_machine_domains(),
                   12633:                         &additional_machine_domains()) {
                   12634:         if (lc($posdom) eq lc($testdomain)) {
                   12635:             $domain=$posdom;
                   12636:             last;
                   12637:         }
                   12638:     }
                   12639:     return $domain;
                   12640: }
                   12641: 
1.31      www      12642: # ------------------------------------------------------------- Declutters URLs
                   12643: 
                   12644: sub declutter {
                   12645:     my $thisfn=shift;
1.569     albertel 12646:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  12647:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   12648:         $thisfn=~s{^/home/httpd/html}{};
                   12649:     }
1.31      www      12650:     $thisfn=~s/^\///;
1.697     albertel 12651:     $thisfn=~s|^adm/wrapper/||;
                   12652:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      12653:     $thisfn=~s/^res\///;
1.1172    bisitz   12654:     $thisfn=~s/^priv\///;
1.1032    raeburn  12655:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   12656:         $thisfn=~s/\?.+$//;
                   12657:     }
1.268     www      12658:     return $thisfn;
                   12659: }
                   12660: 
                   12661: # ------------------------------------------------------------- Clutter up URLs
                   12662: 
                   12663: sub clutter {
                   12664:     my $thisfn='/'.&declutter(shift);
1.887     albertel 12665:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 12666: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      12667:        $thisfn='/res'.$thisfn; 
                   12668:     }
1.1031    raeburn  12669:     if ($thisfn !~m|^/adm|) {
                   12670: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 12671: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 12672: 	} else {
                   12673: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   12674: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 12675: 	    if ($embstyle eq 'ssi'
                   12676: 		|| ($embstyle eq 'hdn')
                   12677: 		|| ($embstyle eq 'rat')
                   12678: 		|| ($embstyle eq 'prv')
                   12679: 		|| ($embstyle eq 'ign')) {
                   12680: 		#do nothing with these
                   12681: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 12682: 		|| ($embstyle eq 'emb')
                   12683: 		|| ($embstyle eq 'wrp')) {
                   12684: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 12685: 	    } elsif ($embstyle eq 'unk'
                   12686: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 12687: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 12688: 	    } else {
1.718     www      12689: #		&logthis("Got a blank emb style");
1.695     albertel 12690: 	    }
1.694     albertel 12691: 	}
1.1298    raeburn  12692:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/exttools?$}) {
                   12693:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 12694:     }
1.31      www      12695:     return $thisfn;
1.12      www      12696: }
                   12697: 
1.787     albertel 12698: sub clutter_with_no_wrapper {
                   12699:     my $uri = &clutter(shift);
                   12700:     if ($uri =~ m-^/adm/-) {
                   12701: 	$uri =~ s-^/adm/wrapper/-/-;
                   12702: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   12703:     }
                   12704:     return $uri;
                   12705: }
                   12706: 
1.557     albertel 12707: sub freeze_escape {
                   12708:     my ($value)=@_;
                   12709:     if (ref($value)) {
                   12710: 	$value=&nfreeze($value);
                   12711: 	return '__FROZEN__'.&escape($value);
                   12712:     }
                   12713:     return &escape($value);
                   12714: }
                   12715: 
1.11      www      12716: 
1.557     albertel 12717: sub thaw_unescape {
                   12718:     my ($value)=@_;
                   12719:     if ($value =~ /^__FROZEN__/) {
                   12720: 	substr($value,0,10,undef);
                   12721: 	$value=&unescape($value);
                   12722: 	return &thaw($value);
                   12723:     }
                   12724:     return &unescape($value);
                   12725: }
                   12726: 
1.436     albertel 12727: sub correct_line_ends {
                   12728:     my ($result)=@_;
                   12729:     $$result =~s/\r\n/\n/mg;
                   12730:     $$result =~s/\r/\n/mg;
1.415     albertel 12731: }
1.1       albertel 12732: # ================================================================ Main Program
                   12733: 
1.184     www      12734: sub goodbye {
1.204     albertel 12735:    &logthis("Starting Shut down");
1.443     albertel 12736: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 12737:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 12738: #converted
1.599     albertel 12739: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 12740:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   12741: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   12742: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 12743: #1.1 only
1.870     albertel 12744: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   12745: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   12746: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   12747: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   12748:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 12749:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   12750:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      12751:    &flushcourselogs();
                   12752:    &logthis("Shutting down");
                   12753: }
                   12754: 
1.852     albertel 12755: sub get_dns {
1.1210    raeburn  12756:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 12757:     if (!$ignore_cache) {
                   12758: 	my ($content,$cached)=
                   12759: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   12760: 	if ($cached) {
1.1210    raeburn  12761: 	    &$func($content,$hashref);
1.869     albertel 12762: 	    return;
                   12763: 	}
                   12764:     }
                   12765: 
                   12766:     my %alldns;
1.852     albertel 12767:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12768:     foreach my $dns (<$config>) {
                   12769: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  12770:         my $line = $1;
                   12771:         my ($host,$protocol) = split(/:/,$line);
                   12772:         if ($protocol ne 'https') {
                   12773:             $protocol = 'http';
                   12774:         }
                   12775: 	$alldns{$host} = $protocol;
1.869     albertel 12776:     }
                   12777:     while (%alldns) {
1.1263    raeburn  12778: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 12779: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  12780:         $ua->timeout(30);
1.979     raeburn  12781: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 12782: 	my $response=$ua->request($request);
1.979     raeburn  12783:         delete($alldns{$dns});
1.852     albertel 12784: 	next if ($response->is_error());
                   12785: 	my @content = split("\n",$response->content);
1.1210    raeburn  12786: 	unless ($nocache) {
1.1219    raeburn  12787: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210    raeburn  12788: 	}
                   12789: 	&$func(\@content,$hashref);
1.869     albertel 12790: 	return;
1.852     albertel 12791:     }
                   12792:     close($config);
1.871     albertel 12793:     my $which = (split('/',$url))[3];
                   12794:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   12795:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 12796:     my @content = <$config>;
1.1210    raeburn  12797:     &$func(\@content,$hashref);
                   12798:     return;
                   12799: }
                   12800: 
                   12801: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  12802: sub parse_dns_checksums_tab {
1.1210    raeburn  12803:     my ($lines,$hashref) = @_;
1.1264    raeburn  12804:     my $lonhost = $perlvar{'lonHostID'};
                   12805:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  12806:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  12807:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   12808:     my $webconfdir = '/etc/httpd/conf';
                   12809:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   12810:         $webconfdir = '/etc/apache2';
                   12811:     } elsif ($distro =~ /^sles(\d+)$/) {
                   12812:         if ($1 >= 10) {
                   12813:             $webconfdir = '/etc/apache2';
                   12814:         }
                   12815:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   12816:         if ($1 >= 10.0) {
                   12817:             $webconfdir = '/etc/apache2';
                   12818:         }
                   12819:     }
1.1210    raeburn  12820:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12821:     my (%chksum,%revnum);
                   12822:     if (ref($lines) eq 'ARRAY') {
                   12823:         chomp(@{$lines});
1.1238    raeburn  12824:         my $version = shift(@{$lines});
                   12825:         if ($version eq $release) {  
1.1210    raeburn  12826:             foreach my $line (@{$lines}) {
1.1238    raeburn  12827:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  12828:                 if ($file =~ m{^/etc/httpd/conf}) {
                   12829:                     if ($webconfdir eq '/etc/apache2') {
                   12830:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   12831:                     }
                   12832:                 }
1.1238    raeburn  12833:                 $chksum{$file} = $shasum;
                   12834:                 $revnum{$file} = $version;
1.1210    raeburn  12835:             }
                   12836:             if (ref($hashref) eq 'HASH') {
                   12837:                 %{$hashref} = (
                   12838:                                 sums     => \%chksum,
                   12839:                                 versions => \%revnum,
                   12840:                               );
                   12841:             }
                   12842:         }
                   12843:     }
1.869     albertel 12844:     return;
1.852     albertel 12845: }
1.1210    raeburn  12846: 
                   12847: sub fetch_dns_checksums {
1.1238    raeburn  12848:     my %checksums;
                   12849:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  12850:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  12851:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12852:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  12853:              \%checksums);
1.1210    raeburn  12854:     return \%checksums;
                   12855: }
                   12856: 
1.327     albertel 12857: # ------------------------------------------------------------ Read domain file
                   12858: {
1.852     albertel 12859:     my $loaded;
1.846     albertel 12860:     my %domain;
                   12861: 
1.852     albertel 12862:     sub parse_domain_tab {
                   12863: 	my ($lines) = @_;
                   12864: 	foreach my $line (@$lines) {
                   12865: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      12866: 
1.846     albertel 12867: 	    chomp($line);
1.852     albertel 12868: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 12869: 	    my %this_domain;
                   12870: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   12871: 			       'lang_def', 'city', 'longi', 'lati',
                   12872: 			       'primary') {
                   12873: 		$this_domain{$field} = shift(@elements);
                   12874: 	    }
                   12875: 	    $domain{$name} = \%this_domain;
1.852     albertel 12876: 	}
                   12877:     }
1.864     albertel 12878: 
                   12879:     sub reset_domain_info {
                   12880: 	undef($loaded);
                   12881: 	undef(%domain);
                   12882:     }
                   12883: 
1.852     albertel 12884:     sub load_domain_tab {
1.1293    raeburn  12885: 	my ($ignore_cache,$nocache) = @_;
                   12886: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 12887: 	my $fh;
                   12888: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   12889: 	    my @lines = <$fh>;
                   12890: 	    &parse_domain_tab(\@lines);
1.448     albertel 12891: 	}
1.852     albertel 12892: 	close($fh);
                   12893: 	$loaded = 1;
1.327     albertel 12894:     }
1.846     albertel 12895: 
                   12896:     sub domain {
1.852     albertel 12897: 	&load_domain_tab() if (!$loaded);
                   12898: 
1.846     albertel 12899: 	my ($name,$what) = @_;
                   12900: 	return if ( !exists($domain{$name}) );
                   12901: 
                   12902: 	if (!$what) {
                   12903: 	    return $domain{$name}{'description'};
                   12904: 	}
                   12905: 	return $domain{$name}{$what};
                   12906:     }
1.974     raeburn  12907: 
                   12908:     sub domain_info {
                   12909:         &load_domain_tab() if (!$loaded);
                   12910:         return %domain;
                   12911:     }
                   12912: 
1.327     albertel 12913: }
                   12914: 
                   12915: 
1.1       albertel 12916: # ------------------------------------------------------------- Read hosts file
                   12917: {
1.838     albertel 12918:     my %hostname;
1.844     albertel 12919:     my %hostdom;
1.845     albertel 12920:     my %libserv;
1.852     albertel 12921:     my $loaded;
1.888     albertel 12922:     my %name_to_host;
1.1074    raeburn  12923:     my %internetdom;
1.1107    raeburn  12924:     my %LC_dns_serv;
1.852     albertel 12925: 
                   12926:     sub parse_hosts_tab {
                   12927: 	my ($file) = @_;
                   12928: 	foreach my $configline (@$file) {
                   12929: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  12930:             chomp($configline);
                   12931: 	    if ($configline =~ /^\^/) {
                   12932:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   12933:                     $LC_dns_serv{$1} = 1;
                   12934:                 }
                   12935:                 next;
                   12936:             }
1.1074    raeburn  12937: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 12938: 	    $name=~s/\s//g;
                   12939: 	    if ($id && $domain && $role && $name) {
                   12940: 		$hostname{$id}=$name;
1.888     albertel 12941: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 12942: 		$hostdom{$id}=$domain;
                   12943: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  12944:                 if (defined($protocol)) {
                   12945:                     if ($protocol eq 'https') {
                   12946:                         $protocol{$id} = $protocol;
                   12947:                     } else {
                   12948:                         $protocol{$id} = 'http'; 
                   12949:                     }
1.968     raeburn  12950:                 } else {
1.969     raeburn  12951:                     $protocol{$id} = 'http';
1.968     raeburn  12952:                 }
1.1074    raeburn  12953:                 if (defined($intdom)) {
                   12954:                     $internetdom{$id} = $intdom;
                   12955:                 }
1.852     albertel 12956: 	    }
                   12957: 	}
                   12958:     }
1.864     albertel 12959:     
                   12960:     sub reset_hosts_info {
1.897     albertel 12961: 	&purge_remembered();
1.864     albertel 12962: 	&reset_domain_info();
                   12963: 	&reset_hosts_ip_info();
1.892     albertel 12964: 	undef(%name_to_host);
1.864     albertel 12965: 	undef(%hostname);
                   12966: 	undef(%hostdom);
                   12967: 	undef(%libserv);
                   12968: 	undef($loaded);
                   12969:     }
1.1       albertel 12970: 
1.852     albertel 12971:     sub load_hosts_tab {
1.1293    raeburn  12972: 	my ($ignore_cache,$nocache) = @_;
                   12973: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852     albertel 12974: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12975: 	my @config = <$config>;
                   12976: 	&parse_hosts_tab(\@config);
                   12977: 	close($config);
                   12978: 	$loaded=1;
1.1       albertel 12979:     }
1.852     albertel 12980: 
1.838     albertel 12981:     sub hostname {
1.852     albertel 12982: 	&load_hosts_tab() if (!$loaded);
                   12983: 
1.838     albertel 12984: 	my ($lonid) = @_;
                   12985: 	return $hostname{$lonid};
                   12986:     }
1.845     albertel 12987: 
1.838     albertel 12988:     sub all_hostnames {
1.852     albertel 12989: 	&load_hosts_tab() if (!$loaded);
                   12990: 
1.838     albertel 12991: 	return %hostname;
                   12992:     }
1.845     albertel 12993: 
1.888     albertel 12994:     sub all_names {
1.1293    raeburn  12995:         my ($ignore_cache,$nocache) = @_;
                   12996: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 12997: 
                   12998: 	return %name_to_host;
                   12999:     }
                   13000: 
1.974     raeburn  13001:     sub all_host_domain {
                   13002:         &load_hosts_tab() if (!$loaded);
                   13003:         return %hostdom;
                   13004:     }
                   13005: 
1.845     albertel 13006:     sub is_library {
1.852     albertel 13007: 	&load_hosts_tab() if (!$loaded);
                   13008: 
1.845     albertel 13009: 	return exists($libserv{$_[0]});
                   13010:     }
                   13011: 
                   13012:     sub all_library {
1.852     albertel 13013: 	&load_hosts_tab() if (!$loaded);
                   13014: 
1.845     albertel 13015: 	return %libserv;
                   13016:     }
                   13017: 
1.1062    droeschl 13018:     sub unique_library {
                   13019: 	#2x reverse removes all hostnames that appear more than once
                   13020:         my %unique = reverse &all_library();
                   13021:         return reverse %unique;
                   13022:     }
                   13023: 
1.841     albertel 13024:     sub get_servers {
1.852     albertel 13025: 	&load_hosts_tab() if (!$loaded);
                   13026: 
1.841     albertel 13027: 	my ($domain,$type) = @_;
                   13028: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13029: 	                                          : %hostname;
                   13030: 	my %result;
1.842     albertel 13031: 	if (ref($domain) eq 'ARRAY') {
                   13032: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13033: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13034: 		    $result{$host} = $hostname;
                   13035: 		}
                   13036: 	    }
                   13037: 	} else {
                   13038: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13039: 		if ($hostdom{$host} eq $domain) {
                   13040: 		    $result{$host} = $hostname;
                   13041: 		}
1.841     albertel 13042: 	    }
                   13043: 	}
                   13044: 	return %result;
                   13045:     }
1.845     albertel 13046: 
1.1062    droeschl 13047:     sub get_unique_servers {
                   13048:         my %unique = reverse &get_servers(@_);
                   13049: 	return reverse %unique;
                   13050:     }
                   13051: 
1.844     albertel 13052:     sub host_domain {
1.852     albertel 13053: 	&load_hosts_tab() if (!$loaded);
                   13054: 
1.844     albertel 13055: 	my ($lonid) = @_;
                   13056: 	return $hostdom{$lonid};
                   13057:     }
                   13058: 
1.841     albertel 13059:     sub all_domains {
1.852     albertel 13060: 	&load_hosts_tab() if (!$loaded);
                   13061: 
1.841     albertel 13062: 	my %seen;
                   13063: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13064: 	return @uniq;
                   13065:     }
1.1074    raeburn  13066: 
                   13067:     sub internet_dom {
                   13068:         &load_hosts_tab() if (!$loaded);
                   13069: 
                   13070:         my ($lonid) = @_;
                   13071:         return $internetdom{$lonid};
                   13072:     }
1.1107    raeburn  13073: 
                   13074:     sub is_LC_dns {
                   13075:         &load_hosts_tab() if (!$loaded);
                   13076: 
                   13077:         my ($hostname) = @_;
                   13078:         return exists($LC_dns_serv{$hostname});
                   13079:     }
                   13080: 
1.1       albertel 13081: }
                   13082: 
1.847     albertel 13083: { 
                   13084:     my %iphost;
1.856     albertel 13085:     my %name_to_ip;
                   13086:     my %lonid_to_ip;
1.869     albertel 13087: 
1.847     albertel 13088:     sub get_hosts_from_ip {
                   13089: 	my ($ip) = @_;
                   13090: 	my %iphosts = &get_iphost();
                   13091: 	if (ref($iphosts{$ip})) {
                   13092: 	    return @{$iphosts{$ip}};
                   13093: 	}
                   13094: 	return;
1.839     albertel 13095:     }
1.864     albertel 13096:     
                   13097:     sub reset_hosts_ip_info {
                   13098: 	undef(%iphost);
                   13099: 	undef(%name_to_ip);
                   13100: 	undef(%lonid_to_ip);
                   13101:     }
1.856     albertel 13102: 
                   13103:     sub get_host_ip {
                   13104: 	my ($lonid) = @_;
                   13105: 	if (exists($lonid_to_ip{$lonid})) {
                   13106: 	    return $lonid_to_ip{$lonid};
                   13107: 	}
                   13108: 	my $name=&hostname($lonid);
                   13109:    	my $ip = gethostbyname($name);
                   13110: 	return if (!$ip || length($ip) ne 4);
                   13111: 	$ip=inet_ntoa($ip);
                   13112: 	$name_to_ip{$name}   = $ip;
                   13113: 	$lonid_to_ip{$lonid} = $ip;
                   13114: 	return $ip;
                   13115:     }
1.847     albertel 13116:     
                   13117:     sub get_iphost {
1.1293    raeburn  13118: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13119: 
1.869     albertel 13120: 	if (!$ignore_cache) {
                   13121: 	    if (%iphost) {
                   13122: 		return %iphost;
                   13123: 	    }
                   13124: 	    my ($ip_info,$cached)=
                   13125: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13126: 	    if ($cached) {
                   13127: 		%iphost      = %{$ip_info->[0]};
                   13128: 		%name_to_ip  = %{$ip_info->[1]};
                   13129: 		%lonid_to_ip = %{$ip_info->[2]};
                   13130: 		return %iphost;
                   13131: 	    }
                   13132: 	}
1.894     albertel 13133: 
                   13134: 	# get yesterday's info for fallback
                   13135: 	my %old_name_to_ip;
                   13136: 	my ($ip_info,$cached)=
                   13137: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13138: 	if ($cached) {
                   13139: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13140: 	}
                   13141: 
1.1293    raeburn  13142: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13143: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13144: 	    my $ip;
                   13145: 	    if (!exists($name_to_ip{$name})) {
                   13146: 		$ip = gethostbyname($name);
                   13147: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13148: 		    if (defined($old_name_to_ip{$name})) {
                   13149: 			$ip = $old_name_to_ip{$name};
                   13150: 			&logthis("Can't find $name defaulting to old $ip");
                   13151: 		    } else {
                   13152: 			&logthis("Name $name no IP found");
                   13153: 			next;
                   13154: 		    }
                   13155: 		} else {
                   13156: 		    $ip=inet_ntoa($ip);
1.847     albertel 13157: 		}
                   13158: 		$name_to_ip{$name} = $ip;
                   13159: 	    } else {
                   13160: 		$ip = $name_to_ip{$name};
1.653     albertel 13161: 	    }
1.888     albertel 13162: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13163: 		$lonid_to_ip{$id} = $ip;
                   13164: 	    }
                   13165: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13166: 	}
1.1293    raeburn  13167:         unless ($nocache) {
                   13168: 	    &do_cache_new('iphost','iphost',
                   13169: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   13170: 		          48*60*60);
                   13171:         }
1.869     albertel 13172: 
1.847     albertel 13173: 	return %iphost;
1.598     albertel 13174:     }
                   13175: 
1.992     raeburn  13176:     #
                   13177:     #  Given a DNS returns the loncapa host name for that DNS 
                   13178:     # 
                   13179:     sub host_from_dns {
                   13180:         my ($dns) = @_;
                   13181:         my @hosts;
                   13182:         my $ip;
                   13183: 
1.993     raeburn  13184:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  13185:             $ip = $name_to_ip{$dns};
                   13186:         }
                   13187:         if (!$ip) {
                   13188:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   13189:             if (length($ip) == 4) { 
                   13190: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   13191:             }
                   13192:         }
                   13193:         if ($ip) {
                   13194: 	    @hosts = get_hosts_from_ip($ip);
                   13195: 	    return $hosts[0];
                   13196:         }
                   13197:         return undef;
1.986     foxr     13198:     }
1.992     raeburn  13199: 
1.1074    raeburn  13200:     sub get_internet_names {
                   13201:         my ($lonid) = @_;
                   13202:         return if ($lonid eq '');
                   13203:         my ($idnref,$cached)=
                   13204:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   13205:         if ($cached) {
                   13206:             return $idnref;
                   13207:         }
                   13208:         my $ip = &get_host_ip($lonid);
                   13209:         my @hosts = &get_hosts_from_ip($ip);
                   13210:         my %iphost = &get_iphost();
                   13211:         my (@idns,%seen);
                   13212:         foreach my $id (@hosts) {
                   13213:             my $dom = &host_domain($id);
                   13214:             my $prim_id = &domain($dom,'primary');
                   13215:             my $prim_ip = &get_host_ip($prim_id);
                   13216:             next if ($seen{$prim_ip});
                   13217:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   13218:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   13219:                     my $intdom = &internet_dom($id);
                   13220:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   13221:                         push(@idns,$intdom);
                   13222:                     }
                   13223:                 }
                   13224:             }
                   13225:             $seen{$prim_ip} = 1;
                   13226:         }
1.1219    raeburn  13227:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  13228:     }
                   13229: 
1.986     foxr     13230: }
                   13231: 
1.1079    raeburn  13232: sub all_loncaparevs {
1.1249    raeburn  13233:     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  13234: }
                   13235: 
1.1227    raeburn  13236: # ---------------------------------------------------------- Read loncaparev table
                   13237: {
                   13238:     sub load_loncaparevs { 
                   13239:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   13240:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   13241:                 while (my $configline=<$config>) {
                   13242:                     chomp($configline);
                   13243:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   13244:                     $loncaparevs{$hostid}=$loncaparev;
                   13245:                 }
                   13246:                 close($config);
                   13247:             }
                   13248:         }
                   13249:     }
                   13250: }
                   13251: 
                   13252: # ---------------------------------------------------------- Read serverhostID table
                   13253: {
                   13254:     sub load_serverhomeIDs {
                   13255:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   13256:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   13257:                 while (my $configline=<$config>) {
                   13258:                     chomp($configline);
                   13259:                     my ($name,$id)=split(/:/,$configline);
                   13260:                     $serverhomeIDs{$name}=$id;
                   13261:                 }
                   13262:                 close($config);
                   13263:             }
                   13264:         }
                   13265:     }
                   13266: }
                   13267: 
                   13268: 
1.862     albertel 13269: BEGIN {
                   13270: 
                   13271: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   13272:     unless ($readit) {
                   13273: {
                   13274:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   13275:     %perlvar = (%perlvar,%{$configvars});
                   13276: }
                   13277: 
                   13278: 
1.1       albertel 13279: # ------------------------------------------------------ Read spare server file
                   13280: {
1.448     albertel 13281:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 13282: 
                   13283:     while (my $configline=<$config>) {
                   13284:        chomp($configline);
1.284     matthew  13285:        if ($configline) {
1.784     albertel 13286: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 13287: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 13288: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 13289:        }
                   13290:     }
1.448     albertel 13291:     close($config);
1.1       albertel 13292: }
1.11      www      13293: # ------------------------------------------------------------ Read permissions
                   13294: {
1.448     albertel 13295:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      13296: 
                   13297:     while (my $configline=<$config>) {
1.448     albertel 13298: 	chomp($configline);
                   13299: 	if ($configline) {
                   13300: 	    my ($role,$perm)=split(/ /,$configline);
                   13301: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   13302: 	}
1.11      www      13303:     }
1.448     albertel 13304:     close($config);
1.11      www      13305: }
                   13306: 
                   13307: # -------------------------------------------- Read plain texts for permissions
                   13308: {
1.448     albertel 13309:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      13310: 
                   13311:     while (my $configline=<$config>) {
1.448     albertel 13312: 	chomp($configline);
                   13313: 	if ($configline) {
1.742     raeburn  13314: 	    my ($short,@plain)=split(/:/,$configline);
                   13315:             %{$prp{$short}} = ();
                   13316: 	    if (@plain > 0) {
                   13317:                 $prp{$short}{'std'} = $plain[0];
                   13318:                 for (my $i=1; $i<@plain; $i++) {
                   13319:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   13320:                 }
                   13321:             }
1.448     albertel 13322: 	}
1.135     www      13323:     }
1.448     albertel 13324:     close($config);
1.135     www      13325: }
                   13326: 
                   13327: # ---------------------------------------------------------- Read package table
                   13328: {
1.448     albertel 13329:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      13330: 
                   13331:     while (my $configline=<$config>) {
1.483     albertel 13332: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 13333: 	chomp($configline);
                   13334: 	my ($short,$plain)=split(/:/,$configline);
                   13335: 	my ($pack,$name)=split(/\&/,$short);
                   13336: 	if ($plain ne '') {
                   13337: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   13338: 	    $packagetab{$short}=$plain; 
                   13339: 	}
1.11      www      13340:     }
1.448     albertel 13341:     close($config);
1.329     matthew  13342: }
                   13343: 
1.1073    raeburn  13344: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  13345: 
                   13346: &load_loncaparevs();
1.1073    raeburn  13347: 
1.1074    raeburn  13348: # ---------------------------------------------------------- Read serverhostID table
                   13349: 
1.1227    raeburn  13350: &load_serverhomeIDs();
                   13351: 
                   13352: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  13353: {
                   13354:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   13355:     if (-e $file) {
                   13356:         my $parser = HTML::LCParser->new($file);
                   13357:         while (my $token = $parser->get_token()) {
                   13358:             if ($token->[0] eq 'S') {
                   13359:                 my $item = $token->[1];
                   13360:                 my $name = $token->[2]{'name'};
                   13361:                 my $value = $token->[2]{'value'};
1.1285    raeburn  13362:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  13363:                 my $namematch = $token->[2]{'namematch'};
                   13364:                 if ($item eq 'parameter') {
                   13365:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   13366:                         my $release = $parser->get_text();
                   13367:                         $release =~ s/(^\s*|\s*$ )//gx;
                   13368:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   13369:                     }
                   13370:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  13371:                     my $release = $parser->get_text();
                   13372:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  13373:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  13374:                 }
                   13375:             }
                   13376:         }
                   13377:     }
1.1073    raeburn  13378: }
                   13379: 
1.1138    raeburn  13380: # ---------------------------------------------------------- Read managers table
                   13381: {
                   13382:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   13383:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   13384:             while (my $configline=<$config>) {
                   13385:                 chomp($configline);
                   13386:                 next if ($configline =~ /^\#/);
                   13387:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   13388:                     $managerstab{$configline} = 1;
                   13389:                 }
                   13390:             }
                   13391:             close($config);
                   13392:         }
                   13393:     }
                   13394: }
                   13395: 
1.329     matthew  13396: # ------------- set up temporary directory
                   13397: {
1.1117    foxr     13398:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  13399: 
1.11      www      13400: }
                   13401: 
1.794     albertel 13402: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   13403: 				'compress_threshold'=> 20_000,
                   13404:  			        });
1.185     www      13405: 
1.281     www      13406: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      13407: $dumpcount=0;
1.958     www      13408: $locknum=0;
1.22      www      13409: 
1.163     harris41 13410: &logtouch();
1.672     albertel 13411: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      13412: $readit=1;
1.564     albertel 13413:     {
                   13414: 	use integer;
                   13415: 	my $test=(2**32)+1;
1.568     albertel 13416: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 13417: 	&logthis(" Detected 64bit platform ($_64bit)");
                   13418:     }
1.195     www      13419: }
1.1       albertel 13420: }
1.179     www      13421: 
1.1       albertel 13422: 1;
1.191     harris41 13423: __END__
                   13424: 
1.243     albertel 13425: =pod
                   13426: 
1.191     harris41 13427: =head1 NAME
                   13428: 
1.243     albertel 13429: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 13430: 
                   13431: =head1 SYNOPSIS
                   13432: 
1.243     albertel 13433: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 13434: 
                   13435:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   13436: 
1.243     albertel 13437: Common parameters:
                   13438: 
                   13439: =over 4
                   13440: 
                   13441: =item *
                   13442: 
                   13443: $uname : an internal username (if $cname expecting a course Id specifically)
                   13444: 
                   13445: =item *
                   13446: 
                   13447: $udom : a domain (if $cdom expecting a course's domain specifically)
                   13448: 
                   13449: =item *
                   13450: 
                   13451: $symb : a resource instance identifier
                   13452: 
                   13453: =item *
                   13454: 
                   13455: $namespace : the name of a .db file that contains the data needed or
                   13456: being set.
                   13457: 
                   13458: =back
                   13459: 
1.394     bowersj2 13460: =head1 OVERVIEW
1.191     harris41 13461: 
1.394     bowersj2 13462: lonnet provides subroutines which interact with the
                   13463: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   13464: about classes, users, and resources.
1.243     albertel 13465: 
                   13466: For many of these objects you can also use this to store data about
                   13467: them or modify them in various ways.
1.191     harris41 13468: 
1.394     bowersj2 13469: =head2 Symbs
1.191     harris41 13470: 
1.394     bowersj2 13471: To identify a specific instance of a resource, LON-CAPA uses symbols
                   13472: or "symbs"X<symb>. These identifiers are built from the URL of the
                   13473: map, the resource number of the resource in the map, and the URL of
                   13474: the resource itself. The latter is somewhat redundant, but might help
                   13475: if maps change.
                   13476: 
                   13477: An example is
                   13478: 
                   13479:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   13480: 
                   13481: The respective map entry is
                   13482: 
                   13483:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   13484:   title="Problem 2">
                   13485:  </resource>
                   13486: 
                   13487: Symbs are used by the random number generator, as well as to store and
                   13488: restore data specific to a certain instance of for example a problem.
                   13489: 
                   13490: =head2 Storing And Retrieving Data
                   13491: 
                   13492: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   13493: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   13494: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   13495: is is the non-critical message twin of cstore. These functions are for
                   13496: handlers to store a perl hash to a user's permanent data space in an
                   13497: easy manner, and to retrieve it again on another call. It is expected
                   13498: that a handler would use this once at the beginning to retrieve data,
                   13499: and then again once at the end to send only the new data back.
                   13500: 
                   13501: The data is stored in the user's data directory on the user's
                   13502: homeserver under the ID of the course.
                   13503: 
                   13504: The hash that is returned by restore will have all of the previous
                   13505: value for all of the elements of the hash.
                   13506: 
                   13507: Example:
                   13508: 
                   13509:  #creating a hash
                   13510:  my %hash;
                   13511:  $hash{'foo'}='bar';
                   13512: 
                   13513:  #storing it
                   13514:  &Apache::lonnet::cstore(\%hash);
                   13515: 
                   13516:  #changing a value
                   13517:  $hash{'foo'}='notbar';
                   13518: 
                   13519:  #adding a new value
                   13520:  $hash{'bar'}='foo';
                   13521:  &Apache::lonnet::cstore(\%hash);
                   13522: 
                   13523:  #retrieving the hash
                   13524:  my %history=&Apache::lonnet::restore();
                   13525: 
                   13526:  #print the hash
                   13527:  foreach my $key (sort(keys(%history))) {
                   13528:    print("\%history{$key} = $history{$key}");
                   13529:  }
                   13530: 
                   13531: Will print out:
1.191     harris41 13532: 
1.394     bowersj2 13533:  %history{1:foo} = bar
                   13534:  %history{1:keys} = foo:timestamp
                   13535:  %history{1:timestamp} = 990455579
                   13536:  %history{2:bar} = foo
                   13537:  %history{2:foo} = notbar
                   13538:  %history{2:keys} = foo:bar:timestamp
                   13539:  %history{2:timestamp} = 990455580
                   13540:  %history{bar} = foo
                   13541:  %history{foo} = notbar
                   13542:  %history{timestamp} = 990455580
                   13543:  %history{version} = 2
                   13544: 
                   13545: Note that the special hash entries C<keys>, C<version> and
                   13546: C<timestamp> were added to the hash. C<version> will be equal to the
                   13547: total number of versions of the data that have been stored. The
                   13548: C<timestamp> attribute will be the UNIX time the hash was
                   13549: stored. C<keys> is available in every historical section to list which
                   13550: keys were added or changed at a specific historical revision of a
                   13551: hash.
                   13552: 
                   13553: B<Warning>: do not store the hash that restore returns directly. This
                   13554: will cause a mess since it will restore the historical keys as if the
                   13555: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 13556: 
1.394     bowersj2 13557: Calling convention:
1.191     harris41 13558: 
1.1225    raeburn  13559:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  13560:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 13561: 
1.394     bowersj2 13562: For more detailed information, see lonnet specific documentation.
1.191     harris41 13563: 
1.394     bowersj2 13564: =head1 RETURN MESSAGES
1.191     harris41 13565: 
1.394     bowersj2 13566: =over 4
1.191     harris41 13567: 
1.394     bowersj2 13568: =item * B<con_lost>: unable to contact remote host
1.191     harris41 13569: 
1.394     bowersj2 13570: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   13571: when the connection is brought back up
1.191     harris41 13572: 
1.394     bowersj2 13573: =item * B<con_failed>: unable to contact remote host and unable to save message
                   13574: for later delivery
1.191     harris41 13575: 
1.967     bisitz   13576: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 13577: 
1.394     bowersj2 13578: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 13579: that was requested
1.191     harris41 13580: 
1.243     albertel 13581: =back
1.191     harris41 13582: 
1.243     albertel 13583: =head1 PUBLIC SUBROUTINES
1.191     harris41 13584: 
1.243     albertel 13585: =head2 Session Environment Functions
1.191     harris41 13586: 
1.243     albertel 13587: =over 4
1.191     harris41 13588: 
1.394     bowersj2 13589: =item * 
                   13590: X<appenv()>
1.949     raeburn  13591: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 13592: the user envirnoment file, and will be restored for each access this
1.620     albertel 13593: user makes during this session, also modifies the %env for the current
1.949     raeburn  13594: process. Optional rolesarrayref - if defined contains a reference to an array
                   13595: of roles which are exempt from the restriction on modifying user.role entries 
                   13596: in the user's environment.db and in %env.    
1.191     harris41 13597: 
                   13598: =item *
1.394     bowersj2 13599: X<delenv()>
1.987     raeburn  13600: B<delenv($delthis,$regexp)>: removes all items from the session
                   13601: environment file that begin with $delthis. If the 
                   13602: optional second arg - $regexp - is true, $delthis is treated as a 
                   13603: regular expression, otherwise \Q$delthis\E is used. 
                   13604: The values are also deleted from the current processes %env.
1.191     harris41 13605: 
1.795     albertel 13606: =item * get_env_multiple($name) 
                   13607: 
                   13608: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   13609: values may be defined and end up as an array ref.
                   13610: 
                   13611: returns an array of values
                   13612: 
1.243     albertel 13613: =back
                   13614: 
                   13615: =head2 User Information
1.191     harris41 13616: 
1.243     albertel 13617: =over 4
1.191     harris41 13618: 
                   13619: =item *
1.394     bowersj2 13620: X<queryauthenticate()>
                   13621: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 13622: authentication scheme
                   13623: 
                   13624: =item *
1.394     bowersj2 13625: X<authenticate()>
1.1073    raeburn  13626: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 13627: authenticate user from domain's lib servers (first use the current
                   13628: one). C<$upass> should be the users password.
1.1073    raeburn  13629: $checkdefauth is optional (value is 1 if a check should be made to
                   13630:    authenticate user using default authentication method, and allow
                   13631:    account creation if username does not have account in the domain).
                   13632: $clientcancheckhost is optional (value is 1 if checking whether the
                   13633:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 13634: 
                   13635: =item *
1.394     bowersj2 13636: X<homeserver()>
                   13637: B<homeserver($uname,$udom)>: find the server which has
                   13638: the user's directory and files (there must be only one), this caches
                   13639: the answer, and also caches if there is a borken connection.
1.191     harris41 13640: 
                   13641: =item *
1.394     bowersj2 13642: X<idget()>
1.1300    raeburn  13643: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   13644: a list of student/employee IDs or clicker IDs
                   13645: (student/employee IDs are a unique resource in a domain, there must be 
                   13646: only 1 ID per username, and only 1 username per ID in a specific domain).
                   13647: clickerIDs are not necessarily unique, as students might share clickers.
                   13648: (returns hash: id=>name,id=>name)
1.191     harris41 13649: 
                   13650: =item *
1.394     bowersj2 13651: X<idrget()>
                   13652: B<idrget($udom,@unames)>: find the IDs behind a list of
                   13653: usernames (returns hash: name=>id,name=>id)
1.191     harris41 13654: 
                   13655: =item *
1.394     bowersj2 13656: X<idput()>
1.1300    raeburn  13657: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   13658: names and associated student/employee IDs or clicker IDs.
                   13659: 
                   13660: =item *
                   13661: X<iddel()>
                   13662: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   13663: student/employee ID or clicker ID username look-ups from domain.
                   13664: The homeserver ($uhome) and namespace ($namespace) are optional.
                   13665: If no $uhome is provided, it will be determined usig &homeserver()
                   13666: for each user.  If no $namespace is provided, the default is ids.
                   13667: 
                   13668: =item *
                   13669: X<updateclickers()>
                   13670: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   13671: clicker ID-to-username look-ups in clickers.db on library server.
                   13672: Permitted actions are add or del (i.e., add or delete). The 
                   13673: clickers.db contains clickerID as keys (escaped), and each corresponding
                   13674: value is an escaped comma-separated list of usernames (for whom the
                   13675: library server is the homeserver), who registered that particular ID.
                   13676: If $critical is true, the update will be sent via &critical, otherwise
                   13677: &reply() will be used.
1.191     harris41 13678: 
                   13679: =item *
1.394     bowersj2 13680: X<rolesinit()>
1.1169    droeschl 13681: B<rolesinit($udom,$username)>: get user privileges.
                   13682: returns user role, first access and timer interval hashes
1.243     albertel 13683: 
                   13684: =item *
1.1171    droeschl 13685: X<privileged()>
                   13686: B<privileged($username,$domain)>: returns a true if user has a
                   13687: privileged and active role (i.e. su or dc), false otherwise.
                   13688: 
                   13689: =item *
1.551     albertel 13690: X<getsection()>
                   13691: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 13692: course $cname, return section name/number or '' for "not in course"
                   13693: and '-1' for "no section"
                   13694: 
                   13695: =item *
1.394     bowersj2 13696: X<userenvironment()>
                   13697: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 13698: passed in @what from the requested user's environment, returns a hash
                   13699: 
1.858     raeburn  13700: =item * 
                   13701: X<userlog_query()>
1.859     albertel 13702: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   13703: activity.log file. %filters defines filters applied when parsing the
                   13704: log file. These can be start or end timestamps, or the type of action
                   13705: - log to look for Login or Logout events, check for Checkin or
                   13706: Checkout, role for role selection. The response is in the form
                   13707: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   13708: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  13709: 
1.243     albertel 13710: =back
                   13711: 
                   13712: =head2 User Roles
                   13713: 
                   13714: =over 4
                   13715: 
                   13716: =item *
                   13717: 
1.1284    raeburn  13718: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   13719: returns codes for allowed actions.
                   13720: 
                   13721: The first argument is required, all others are optional.
                   13722: 
                   13723: $priv is the privilege being checked.
                   13724: $uri contains additional information about what is being checked for access (e.g.,
                   13725: URL, course ID etc.). 
                   13726: $symb is the unique resource instance identifier in a course; if needed,
                   13727: but not provided, it will be retrieved via a call to &symbread(). 
                   13728: $role is the role for which a priv is being checked (only used if priv is evb). 
                   13729: $clientip is the user's IP address (only used when checking for access to portfolio 
                   13730: files).
                   13731: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   13732: prevents recursive calls to &allowed.
                   13733: 
1.243     albertel 13734:  F: full access
                   13735:  U,I,K: authentication modes (cxx only)
                   13736:  '': forbidden
                   13737:  1: user needs to choose course
                   13738:  2: browse allowed
1.766     albertel 13739:  A: passphrase authentication needed
1.1284    raeburn  13740:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 13741: 
                   13742: =item *
                   13743: 
1.1192    raeburn  13744: constructaccess($url,$setpriv) : check for access to construction space URL
                   13745: 
                   13746: See if the owner domain and name in the URL match those in the
                   13747: expected environment.  If so, return three element list
                   13748: ($ownername,$ownerdomain,$ownerhome).
                   13749: 
                   13750: Otherwise return the null string.
                   13751: 
                   13752: If second argument 'setpriv' is true, it assigns the privileges,
                   13753: and returns the same three element list, unless the owner has
                   13754: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   13755: in which case the null string is returned.
                   13756: 
                   13757: =item *
                   13758: 
1.243     albertel 13759: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   13760: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   13761: and course level
                   13762: 
                   13763: =item *
                   13764: 
1.988     raeburn  13765: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   13766: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  13767: $type is Course (default) or Community.
1.988     raeburn  13768: If $forcedefault evaluates to true, text returned will be default 
                   13769: text for $type. Otherwise, if this is a course, the text returned 
                   13770: will be a custom name for the role (if defined in the course's 
                   13771: environment).  If no custom name is defined the default is returned.
                   13772:    
1.832     raeburn  13773: =item *
                   13774: 
1.1219    raeburn  13775: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  13776: All arguments are optional. Returns a hash of a roles, either for
                   13777: co-author/assistant author roles for a user's Construction Space
1.906     albertel 13778: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  13779: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   13780: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   13781: For each key, value is set to colon-separated start and end times for
                   13782: the role.  If no username and domain are specified, will default to
1.934     raeburn  13783: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  13784: of role statuses (active, future or previous), roles 
                   13785: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   13786: to restrict the list of roles reported. If no array ref is 
                   13787: provided for types, will default to return only active roles.
1.834     albertel 13788: 
1.1195    raeburn  13789: =item *
                   13790: 
                   13791: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  13792: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   13793: 
                   13794: Additional optional arguments are: $type (if role checking is to be restricted 
                   13795: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  13796: available roles) or future (roles available in the future), and
                   13797: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  13798: have active Domain Coordinator role in course's domain or in additional
                   13799: domains (specified in 'Domains to check for privileged users' in course
                   13800: environment -- set via:  Course Settings -> Classlists and staff listing).
                   13801: 
                   13802: =item *
                   13803: 
                   13804: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   13805: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   13806: $possdomains and $possroles are optional array refs -- to domains to check and
                   13807: roles to check.  If $possdomains is not specified, a dump will be done of the
                   13808: users' roles.db to check for a dc or su role in any domain. This can be
                   13809: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   13810: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   13811: this then allows &privileged_by_domain() to be used, which caches the identity
                   13812: of privileged users, eliminating the need for repeated calls to &dump().
                   13813: 
                   13814: =item *
                   13815: 
                   13816: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   13817: where the outer hash keys are domains specified in the $possdomains array ref,
                   13818: next inner hash keys are privileged roles specified in the $roles array ref,
                   13819: and the innermost hash contains key = value pairs for username:domain = end:start
                   13820: for active or future "privileged" users with that role in that domain. To avoid
                   13821: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   13822: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  13823: 
1.243     albertel 13824: =back
                   13825: 
                   13826: =head2 User Modification
                   13827: 
                   13828: =over 4
                   13829: 
                   13830: =item *
                   13831: 
1.957     raeburn  13832: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 13833: user for the level given by URL.  Optional start and end dates (leave empty
                   13834: string or zero for "no date")
1.191     harris41 13835: 
                   13836: =item *
                   13837: 
1.243     albertel 13838: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   13839: change a users, password, possible return values are: ok,
                   13840: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   13841: refused
1.191     harris41 13842: 
                   13843: =item *
                   13844: 
1.243     albertel 13845: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 13846: 
                   13847: =item *
                   13848: 
1.1058    raeburn  13849: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   13850:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   13851: 
                   13852: will update user information (firstname,middlename,lastname,generation,
                   13853: permanentemail), and if forceid is true, student/employee ID also.
                   13854: A user's institutional affiliation(s) can also be updated.
                   13855: User information fields will not be overwritten with empty entries 
                   13856: unless the field is included in the $candelete array reference.
                   13857: This array is included when a single user is modified via "Manage Users",
                   13858: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 13859: 
                   13860: =item *
                   13861: 
1.286     matthew  13862: modifystudent
                   13863: 
1.957     raeburn  13864: modify a student's enrollment and identification information.
1.1235    raeburn  13865: The course id is resolved based on the current user's environment.  
                   13866: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  13867: associated with a course.
                   13868: 
1.297     matthew  13869: This call is essentially a wrapper for lonnet::modifyuser and
                   13870: lonnet::modify_student_enrollment
1.286     matthew  13871: 
                   13872: Inputs: 
                   13873: 
                   13874: =over 4
                   13875: 
1.957     raeburn  13876: =item B<$udom> Student's loncapa domain
1.286     matthew  13877: 
1.957     raeburn  13878: =item B<$uname> Student's loncapa login name
1.286     matthew  13879: 
1.964     bisitz   13880: =item B<$uid> Student/Employee ID
1.286     matthew  13881: 
1.957     raeburn  13882: =item B<$umode> Student's authentication mode
1.286     matthew  13883: 
1.957     raeburn  13884: =item B<$upass> Student's password
1.286     matthew  13885: 
1.957     raeburn  13886: =item B<$first> Student's first name
1.286     matthew  13887: 
1.957     raeburn  13888: =item B<$middle> Student's middle name
1.286     matthew  13889: 
1.957     raeburn  13890: =item B<$last> Student's last name
1.286     matthew  13891: 
1.957     raeburn  13892: =item B<$gene> Student's generation
1.286     matthew  13893: 
1.957     raeburn  13894: =item B<$usec> Student's section in course
1.286     matthew  13895: 
                   13896: =item B<$end> Unix time of the roles expiration
                   13897: 
                   13898: =item B<$start> Unix time of the roles start date
                   13899: 
                   13900: =item B<$forceid> If defined, allow $uid to be changed
                   13901: 
                   13902: =item B<$desiredhome> server to use as home server for student
                   13903: 
1.957     raeburn  13904: =item B<$email> Student's permanent e-mail address
                   13905: 
                   13906: =item B<$type> Type of enrollment (auto or manual)
                   13907: 
1.963     raeburn  13908: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   13909: 
                   13910: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  13911: 
1.963     raeburn  13912: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  13913: 
1.963     raeburn  13914: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  13915: 
1.1216    raeburn  13916: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   13917: 
                   13918: =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  13919: 
1.286     matthew  13920: =back
1.297     matthew  13921: 
                   13922: =item *
                   13923: 
                   13924: modify_student_enrollment
                   13925: 
1.1235    raeburn  13926: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  13927: 'role.request.course' must be defined for this function to proceed.
                   13928: 
                   13929: Inputs:
                   13930: 
                   13931: =over 4
                   13932: 
1.1235    raeburn  13933: =item $udom, student's domain
1.297     matthew  13934: 
1.1235    raeburn  13935: =item $uname, student's name
1.297     matthew  13936: 
1.1235    raeburn  13937: =item $uid, student's user id
1.297     matthew  13938: 
1.1235    raeburn  13939: =item $first, student's first name
1.297     matthew  13940: 
                   13941: =item $middle
                   13942: 
                   13943: =item $last
                   13944: 
                   13945: =item $gene
                   13946: 
                   13947: =item $usec
                   13948: 
                   13949: =item $end
                   13950: 
                   13951: =item $start
                   13952: 
1.957     raeburn  13953: =item $type
                   13954: 
                   13955: =item $locktype
                   13956: 
                   13957: =item $cid
                   13958: 
                   13959: =item $selfenroll
                   13960: 
                   13961: =item $context
                   13962: 
1.1216    raeburn  13963: =item $credits, number of credits student will earn from this class
                   13964: 
1.1314    raeburn  13965: =item $instsec, institutional course section code for student
                   13966: 
1.297     matthew  13967: =back
                   13968: 
1.191     harris41 13969: 
                   13970: =item *
                   13971: 
1.243     albertel 13972: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   13973: custom role; give a custom role to a user for the level given by URL.  Specify
                   13974: name and domain of role author, and role name
1.191     harris41 13975: 
                   13976: =item *
                   13977: 
1.243     albertel 13978: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 13979: 
                   13980: =item *
                   13981: 
1.243     albertel 13982: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   13983: 
                   13984: =back
                   13985: 
                   13986: =head2 Course Infomation
                   13987: 
                   13988: =over 4
1.191     harris41 13989: 
                   13990: =item *
                   13991: 
1.1118    foxr     13992: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 13993: specified course id, including all environment settings for the
                   13994: course, the description of the course will be in the hash under the
                   13995: key 'description'
1.191     harris41 13996: 
1.1118    foxr     13997: $options is an optional parameter that if supplied is a hash reference that controls
                   13998: what how this function works.  It has the following key/values:
                   13999: 
                   14000: =over 4
                   14001: 
                   14002: =item freshen_cache
                   14003: 
                   14004: If defined, and the environment cache for the course is valid, it is 
                   14005: returned in the returned hash.
                   14006: 
                   14007: =item one_time
                   14008: 
                   14009: If defined, the last cache time is set to _now_
                   14010: 
                   14011: =item user
                   14012: 
                   14013: If defined, the supplied username is used instead of the current user.
                   14014: 
                   14015: 
                   14016: =back
                   14017: 
1.191     harris41 14018: =item *
                   14019: 
1.624     albertel 14020: resdata($name,$domain,$type,@which) : request for current parameter
                   14021: setting for a specific $type, where $type is either 'course' or 'user',
                   14022: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  14023: answers for 10 minutes.
1.243     albertel 14024: 
1.877     foxr     14025: =item *
                   14026: 
                   14027: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14028: data base, returning a hash that is keyed by the resource name and has
                   14029: values that are the resource value.  I believe that the timestamps and
                   14030: versions are also returned.
                   14031: 
1.1236    raeburn  14032: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14033: supplemental content area. This routine caches the number of files for 
                   14034: 10 minutes.
                   14035: 
1.243     albertel 14036: =back
                   14037: 
                   14038: =head2 Course Modification
                   14039: 
                   14040: =over 4
1.191     harris41 14041: 
                   14042: =item *
                   14043: 
1.243     albertel 14044: writecoursepref($courseid,%prefs) : write preferences (environment
                   14045: database) for a course
1.191     harris41 14046: 
                   14047: =item *
                   14048: 
1.1011    raeburn  14049: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14050: 
                   14051: =item *
                   14052: 
1.1038    raeburn  14053: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14054: 
1.1167    droeschl 14055: =item *
                   14056: 
                   14057: is_course($courseid), is_course($cdom, $cnum)
                   14058: 
                   14059: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14060: two component version $cdom, $cnum. It checks if the specified course exists.
                   14061: 
                   14062: Returns:
                   14063:     undef if the course doesn't exist, otherwise
                   14064:     in scalar context the combined courseid.
                   14065:     in list context the two components of the course identifier, domain and 
                   14066:     courseid.    
                   14067: 
1.243     albertel 14068: =back
                   14069: 
                   14070: =head2 Resource Subroutines
                   14071: 
                   14072: =over 4
1.191     harris41 14073: 
                   14074: =item *
                   14075: 
1.243     albertel 14076: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 14077: 
                   14078: =item *
                   14079: 
1.243     albertel 14080: repcopy($filename) : subscribes to the requested file, and attempts to
                   14081: replicate from the owning library server, Might return
1.607     raeburn  14082: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   14083: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 14084: resource. Expects the local filesystem pathname
                   14085: (/home/httpd/html/res/....)
                   14086: 
                   14087: =back
                   14088: 
                   14089: =head2 Resource Information
                   14090: 
                   14091: =over 4
1.191     harris41 14092: 
                   14093: =item *
                   14094: 
1.1228    raeburn  14095: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   14096: and returns the value of a variety of different possible values,
                   14097: $varname should be a request string, and the other parameters can be
                   14098: used to specify who and what one is asking about. Ordinarily, $cid 
                   14099: does not need to be specified, as it is retrived from 
                   14100: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14101: within lonuserstate::loadmap() when initializing a course, before
                   14102: $env{'request.course.id'} has been set, so it needs to be provided
                   14103: in that one case.
1.243     albertel 14104: 
                   14105: Possible values for $varname are environment.lastname (or other item
                   14106: from the envirnment hash), user.name (or someother aspect about the
                   14107: user), resource.0.maxtries (or some other part and parameter of a
                   14108: resource)
1.204     albertel 14109: 
                   14110: =item *
                   14111: 
1.243     albertel 14112: directcondval($number) : get current value of a condition; reads from a state
                   14113: string
1.204     albertel 14114: 
                   14115: =item *
                   14116: 
1.243     albertel 14117: condval($condidx) : value of condition index based on state
1.204     albertel 14118: 
                   14119: =item *
                   14120: 
1.243     albertel 14121: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   14122: resource's metadata, $what should be either a specific key, or either
                   14123: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   14124: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   14125: 
                   14126: this function automatically caches all requests
1.191     harris41 14127: 
                   14128: =item *
                   14129: 
1.243     albertel 14130: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   14131: network of library servers; returns file handle of where SQL and regex results
                   14132: will be stored for query
1.191     harris41 14133: 
                   14134: =item *
                   14135: 
1.1282    raeburn  14136: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   14137: return symbolic list entry (all arguments optional). 
                   14138: 
                   14139: Args: filename is the filename (including path) for the file for which a symb 
                   14140: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   14141: to check access status if more than one resource was found in the bighash 
                   14142: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   14143: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   14144: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   14145: cause possible symbs to be checked to determine if they are subject to content
                   14146: blocking, if so they will not be included as possible symbs; possibles is a
                   14147: ref to a hash, which, as a side effect, will be populated with all possible 
                   14148: symbs (content blocking not tested).
                   14149:  
1.243     albertel 14150: returns the data handle
1.191     harris41 14151: 
                   14152: =item *
                   14153: 
1.1190    raeburn  14154: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   14155: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 14156: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  14157: on failure, user must be in a course, as it assumes the existence of
                   14158: the course initial hash, and uses $env('request.course.id'}.  The third
                   14159: arg is an optional reference to a scalar.  If this arg is passed in the 
                   14160: call to symbverify, it will be set to 1 if the symb has been set to be 
                   14161: encrypted; otherwise it will be null.  
1.191     harris41 14162: 
                   14163: =item *
                   14164: 
1.243     albertel 14165: symbclean($symb) : removes versions numbers from a symb, returns the
                   14166: cleaned symb
1.191     harris41 14167: 
                   14168: =item *
                   14169: 
1.243     albertel 14170: is_on_map($uri) : checks if the $uri is somewhere on the current
                   14171: course map, user must be in a course for it to work.
1.191     harris41 14172: 
                   14173: =item *
                   14174: 
1.243     albertel 14175: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 14176: 
                   14177: =item *
                   14178: 
1.243     albertel 14179: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   14180: a random seed, all arguments are optional, if they aren't sent it uses the
                   14181: environment to derive them. Note: if symb isn't sent and it can't get one
                   14182: from &symbread it will use the current time as its return value
1.191     harris41 14183: 
                   14184: =item *
                   14185: 
1.243     albertel 14186: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   14187: unfakeable, receipt
1.191     harris41 14188: 
                   14189: =item *
                   14190: 
1.620     albertel 14191: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 14192: 
                   14193: =item *
                   14194: 
1.243     albertel 14195: countacc($url) : count the number of accesses to a given URL
1.191     harris41 14196: 
                   14197: =item *
                   14198: 
1.243     albertel 14199: 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 14200: 
                   14201: =item *
                   14202: 
1.243     albertel 14203: 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 14204: 
                   14205: =item *
                   14206: 
1.243     albertel 14207: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 14208: 
                   14209: =item *
                   14210: 
1.243     albertel 14211: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   14212: forcing spreadsheet to reevaluate the resource scores next time.
                   14213: 
1.1195    raeburn  14214: =item * 
                   14215: 
1.1196    raeburn  14216: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   14217: when viewing in course context.
1.1195    raeburn  14218: 
1.1196    raeburn  14219:  input: six args -- filename (decluttered), course number, course domain,
                   14220:                     url, symb (if registered) and group (if this is a 
                   14221:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  14222: 
1.1196    raeburn  14223:  output: array of five scalars --
1.1195    raeburn  14224:          $cfile -- url for file editing if editable on current server
                   14225:          $home -- homeserver of resource (i.e., for author if published,
                   14226:                                           or course if uploaded.).
                   14227:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  14228:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   14229:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  14230: 
                   14231: =item *
                   14232: 
                   14233: is_course_upload($file,$cnum,$cdom)
                   14234: 
                   14235: Used in course context to determine if current file was uploaded to 
                   14236: the course (i.e., would be found in /userfiles/docs on the course's 
                   14237: homeserver.
                   14238: 
                   14239:   input: 3 args -- filename (decluttered), course number and course domain.
                   14240:   output: boolean -- 1 if file was uploaded.
                   14241: 
1.243     albertel 14242: =back
                   14243: 
                   14244: =head2 Storing/Retreiving Data
                   14245: 
                   14246: =over 4
1.191     harris41 14247: 
                   14248: =item *
                   14249: 
1.1269    raeburn  14250: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   14251: permanently for this url; hashref needs to be given and should be a \%hashname;
                   14252: the remaining args aren't required and if they aren't passed or are '' they will
                   14253: be derived from the env (with the exception of $laststore, which is an 
                   14254: optional arg used when a user's submission is stored in grading).
                   14255: $laststore is $version=$timestamp, where $version is the most recent version
                   14256: number retrieved for the corresponding $symb in the $namespace db file, and
                   14257: $timestamp is the timestamp for that transaction (UNIX time).
                   14258: $laststore is currently only passed when cstore() is called by 
                   14259: structuretags::finalize_storage().
1.191     harris41 14260: 
                   14261: =item *
                   14262: 
1.1269    raeburn  14263: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   14264: but uses critical subroutine
1.191     harris41 14265: 
                   14266: =item *
                   14267: 
1.243     albertel 14268: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   14269: all args are optional
1.191     harris41 14270: 
                   14271: =item *
                   14272: 
1.717     albertel 14273: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   14274: dumps the complete (or key matching regexp) namespace into a hash
                   14275: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   14276: normally &store()ed into
                   14277: 
                   14278: $range should be either an integer '100' (give me the first 100
                   14279:                                            matching records)
                   14280:               or be  two integers sperated by a - with no spaces
                   14281:                  '30-50' (give me the 30th through the 50th matching
                   14282:                           records)
                   14283: 
                   14284: 
                   14285: =item *
                   14286: 
1.1269    raeburn  14287: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 14288: replaces a &store() version of data with a replacement set of data
                   14289: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  14290: reference. If $tolog is true, the transaction is logged in the courselog
                   14291: with an action=PUTSTORE.
1.717     albertel 14292: 
                   14293: =item *
                   14294: 
1.243     albertel 14295: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   14296: works very similar to store/cstore, but all data is stored in a
                   14297: temporary location and can be reset using tmpreset, $storehash should
                   14298: be a hash reference, returns nothing on success
1.191     harris41 14299: 
                   14300: =item *
                   14301: 
1.243     albertel 14302: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   14303: similar to restore, but all data is stored in a temporary location and
                   14304: can be reset using tmpreset. Returns a hash of values on success,
                   14305: error string otherwise.
1.191     harris41 14306: 
                   14307: =item *
                   14308: 
1.243     albertel 14309: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   14310: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 14311: 
                   14312: =item *
                   14313: 
1.243     albertel 14314: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14315: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 14316: 
                   14317: =item *
                   14318: 
1.243     albertel 14319: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   14320: namesp ($udom and $uname are optional)
1.191     harris41 14321: 
                   14322: =item *
                   14323: 
1.702     albertel 14324: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 14325: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 14326: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  14327: 
1.702     albertel 14328: $range should be either an integer '100' (give me the first 100
                   14329:                                            matching records)
                   14330:               or be  two integers sperated by a - with no spaces
                   14331:                  '30-50' (give me the 30th through the 50th matching
                   14332:                           records)
1.449     matthew  14333: =item *
                   14334: 
                   14335: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   14336: $store can be a scalar, an array reference, or if the amount to be 
                   14337: incremented is > 1, a hash reference.
                   14338: 
                   14339: ($udom and $uname are optional)
1.191     harris41 14340: 
                   14341: =item *
                   14342: 
1.243     albertel 14343: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   14344: ($udom and $uname are optional)
1.191     harris41 14345: 
                   14346: =item *
                   14347: 
1.243     albertel 14348: cput($namespace,$storehash,$udom,$uname) : critical put
                   14349: ($udom and $uname are optional)
1.191     harris41 14350: 
                   14351: =item *
                   14352: 
1.748     albertel 14353: newput($namespace,$storehash,$udom,$uname) :
                   14354: 
                   14355: Attempts to store the items in the $storehash, but only if they don't
                   14356: currently exist, if this succeeds you can be certain that you have 
                   14357: successfully created a new key value pair in the $namespace db.
                   14358: 
                   14359: 
                   14360: Args:
                   14361:  $namespace: name of database to store values to
                   14362:  $storehash: hashref to store to the db
                   14363:  $udom: (optional) domain of user containing the db
                   14364:  $uname: (optional) name of user caontaining the db
                   14365: 
                   14366: Returns:
                   14367:  'ok' -> succeeded in storing all keys of $storehash
                   14368:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   14369:                         least <key> already existed in the db (other
                   14370:                         requested keys may also already exist)
1.967     bisitz   14371:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 14372:  'con_lost' -> unable to contact request server
                   14373:  'refused' -> action was not allowed by remote machine
                   14374: 
                   14375: 
                   14376: =item *
                   14377: 
1.243     albertel 14378: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14379: reference filled in from namesp (encrypts the return communication)
                   14380: ($udom and $uname are optional)
1.191     harris41 14381: 
                   14382: =item *
                   14383: 
1.243     albertel 14384: log($udom,$name,$home,$message) : write to permanent log for user; use
                   14385: critical subroutine
                   14386: 
1.806     raeburn  14387: =item *
                   14388: 
1.860     raeburn  14389: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   14390: array reference filled in from namespace found in domain level on either
                   14391: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  14392: 
                   14393: =item *
                   14394: 
1.860     raeburn  14395: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   14396: domain level either on specified domain server ($uhome) or primary domain 
                   14397: server ($udom and $uhome are optional)
1.806     raeburn  14398: 
1.943     raeburn  14399: =item * 
                   14400: 
1.1240    raeburn  14401: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   14402: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   14403: the target domain.
                   14404: 
                   14405: May also include additional key => value pairs for the following groups:
                   14406: 
                   14407: =over
                   14408: 
                   14409: =item
                   14410: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   14411: 
                   14412: =over
                   14413: 
                   14414: =item defaultquota, authorquota
                   14415: 
                   14416: =back
                   14417: 
                   14418: =item
                   14419: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   14420: portfolio for users).
                   14421: 
                   14422: =over
                   14423: 
                   14424: =item
                   14425: aboutme, blog, webdav, portfolio
                   14426: 
                   14427: =back
                   14428: 
                   14429: =item
                   14430: requestcourses: ability to request courses, and how requests are processed.
                   14431: 
                   14432: =over
                   14433: 
                   14434: =item
1.1305    raeburn  14435: official, unofficial, community, textbook, placement
1.1240    raeburn  14436: 
                   14437: =back
                   14438: 
                   14439: =item
                   14440: inststatus: types of institutional affiliation, and order in which they are displayed.
                   14441: 
                   14442: =over
                   14443: 
                   14444: =item
1.1256    raeburn  14445: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  14446: 
                   14447: =back
                   14448: 
                   14449: =item
                   14450: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   14451: for course's uploaded content.
                   14452: 
                   14453: =over
                   14454: 
                   14455: =item
1.1246    raeburn  14456: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  14457: communityquota, textbookquota, placementquota
1.1240    raeburn  14458: 
                   14459: =back
                   14460: 
                   14461: =item
                   14462: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   14463: on your servers.
                   14464: 
                   14465: =over
                   14466: 
                   14467: =item 
                   14468: remotesessions, hostedsessions
                   14469: 
                   14470: =back
                   14471: 
                   14472: =back
                   14473: 
                   14474: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   14475: utility to create a configuration.db file on a domain's primary library server 
                   14476: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   14477: -- corresponding values are authentication type (internal, krb4, krb5,
                   14478: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   14479: will be available. Values are retrieved from cache (if current), unless the
                   14480: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   14481: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   14482: 
                   14483: Typical usage:
1.943     raeburn  14484: 
1.1240    raeburn  14485: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  14486: 
1.243     albertel 14487: =back
                   14488: 
                   14489: =head2 Network Status Functions
                   14490: 
                   14491: =over 4
1.191     harris41 14492: 
                   14493: =item *
                   14494: 
1.1137    raeburn  14495: dirlist() : return directory list based on URI (first arg).
                   14496: 
                   14497: Inputs: 1 required, 5 optional.
                   14498: 
                   14499: =over
                   14500: 
                   14501: =item 
                   14502: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   14503: 
                   14504: =item
                   14505: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   14506: 
                   14507: =item
                   14508: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   14509: 
                   14510: =item
                   14511: $getpropath - boolean: 1 if prepend path using &propath(). 
                   14512: 
                   14513: =item
                   14514: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   14515: 
                   14516: =item 
                   14517: $alternateRoot - path to prepend in place of path from $uri.
                   14518: 
                   14519: =back
                   14520: 
                   14521: Returns: Array of up to two items.
                   14522: 
                   14523: =over
                   14524: 
                   14525: a reference to an array of files/subdirectories
                   14526: 
                   14527: =over
                   14528: 
                   14529: Each element in the array of files/subdirectories is a & separated list of
                   14530: item name and the result of running stat on the item.  If dirlist was requested
                   14531: for a file instead of a directory, the item name will be ''. For a directory 
                   14532: listing, if the item is a metadata file, the element will end &N&M 
                   14533: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   14534: default copyright set (1).  
                   14535: 
                   14536: =back
                   14537: 
                   14538: a scalar containing error condition (if encountered).
                   14539: 
                   14540: =over
                   14541: 
                   14542: =item 
                   14543: no_host (no homeserver identified for $username:$domain).
                   14544: 
                   14545: =item 
                   14546: no_such_host (server contacted for listing not identified as valid host).
                   14547: 
                   14548: =item 
                   14549: con_lost (connection to remote server failed).
                   14550: 
                   14551: =item 
                   14552: refused (invalid $username:$domain received on lond side).
                   14553: 
                   14554: =item 
                   14555: no_such_dir (directory at specified path on lond side does not exist). 
                   14556: 
                   14557: =item 
                   14558: empty (directory at specified path on lond side is empty).
                   14559: 
                   14560: =over
                   14561: 
                   14562: This is currently not encountered because the &ls3, &ls2, 
                   14563: &ls (_handler) routines on the lond side do not filter out
                   14564: . and .. from a directory listing. 
                   14565: 
                   14566: =back
                   14567: 
                   14568: =back
                   14569: 
                   14570: =back
1.191     harris41 14571: 
                   14572: =item *
                   14573: 
1.243     albertel 14574: spareserver() : find server with least workload from spare.tab
                   14575: 
1.986     foxr     14576: 
                   14577: =item *
                   14578: 
                   14579: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   14580: if there is no corresponding loncapa host.
                   14581: 
1.243     albertel 14582: =back
                   14583: 
1.986     foxr     14584: 
1.243     albertel 14585: =head2 Apache Request
                   14586: 
                   14587: =over 4
1.191     harris41 14588: 
                   14589: =item *
                   14590: 
1.243     albertel 14591: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   14592: localhost, posts hash
                   14593: 
                   14594: =back
                   14595: 
                   14596: =head2 Data to String to Data
                   14597: 
                   14598: =over 4
1.191     harris41 14599: 
                   14600: =item *
                   14601: 
1.243     albertel 14602: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   14603: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 14604: 
                   14605: =item *
                   14606: 
1.243     albertel 14607: hashref2str($hashref) : convert a hashref into a string complete with
                   14608: escaping and '=' and '&' separators, supports elements that are
                   14609: arrayrefs and hashrefs
1.191     harris41 14610: 
                   14611: =item *
                   14612: 
1.243     albertel 14613: arrayref2str($arrayref) : convert an arrayref into a string complete
                   14614: with escaping and '&' separators, supports elements that are arrayrefs
                   14615: and hashrefs
1.191     harris41 14616: 
                   14617: =item *
                   14618: 
1.243     albertel 14619: str2hash($string) : convert string to hash using unescaping and
                   14620: splitting on '=' and '&', supports elements that are arrayrefs and
                   14621: hashrefs
1.191     harris41 14622: 
                   14623: =item *
                   14624: 
1.243     albertel 14625: str2array($string) : convert string to hash using unescaping and
                   14626: splitting on '&', supports elements that are arrayrefs and hashrefs
                   14627: 
                   14628: =back
                   14629: 
                   14630: =head2 Logging Routines
                   14631: 
                   14632: 
                   14633: These routines allow one to make log messages in the lonnet.log and
                   14634: lonnet.perm logfiles.
1.191     harris41 14635: 
1.1119    foxr     14636: =over 4
                   14637: 
1.191     harris41 14638: =item *
                   14639: 
1.243     albertel 14640: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 14641: 
                   14642: =item *
                   14643: 
1.243     albertel 14644: logthis() : append message to the normal lonnet.log file, it gets
                   14645: preiodically rolled over and deleted.
1.191     harris41 14646: 
                   14647: =item *
                   14648: 
1.243     albertel 14649: logperm() : append a permanent message to lonnet.perm.log, this log
                   14650: file never gets deleted by any automated portion of the system, only
                   14651: messages of critical importance should go in here.
                   14652: 
1.1119    foxr     14653: 
1.243     albertel 14654: =back
                   14655: 
                   14656: =head2 General File Helper Routines
                   14657: 
                   14658: =over 4
1.191     harris41 14659: 
                   14660: =item *
                   14661: 
1.481     raeburn  14662: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   14663: (a) files in /uploaded
                   14664:   (i) If a local copy of the file exists - 
                   14665:       compares modification date of local copy with last-modified date for 
                   14666:       definitive version stored on home server for course. If local copy is 
                   14667:       stale, requests a new version from the home server and stores it. 
                   14668:       If the original has been removed from the home server, then local copy 
                   14669:       is unlinked.
                   14670:   (ii) If local copy does not exist -
                   14671:       requests the file from the home server and stores it. 
                   14672:   
                   14673:   If $caller is 'uploadrep':  
                   14674:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   14675:     for request for files originally uploaded via DOCS. 
                   14676:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   14677:   
                   14678:   Otherwise:
                   14679:      This indicates a call from the content generation phase of the request.
                   14680:      -  returns the entire contents of the file or -1.
                   14681:      
                   14682: (b) files in /res
                   14683:    - returns the entire contents of a file or -1; 
                   14684:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 14685: 
1.712     albertel 14686: 
                   14687: =item *
                   14688: 
                   14689: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   14690:                   reference
                   14691: 
                   14692: returns either a stat() list of data about the file or an empty list
                   14693: if the file doesn't exist or couldn't find out about it (connection
                   14694: problems or user unknown)
                   14695: 
1.191     harris41 14696: =item *
                   14697: 
1.243     albertel 14698: filelocation($dir,$file) : returns file system location of a file
                   14699: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   14700: directory that relative $file lookups are to looked in ($dir of /a/dir
                   14701: and a file of ../bob will become /a/bob)
1.191     harris41 14702: 
                   14703: =item *
                   14704: 
                   14705: hreflocation($dir,$file) : returns file system location or a URL; same as
                   14706: filelocation except for hrefs
                   14707: 
                   14708: =item *
                   14709: 
1.1261    raeburn  14710: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   14711: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 14712: 
1.243     albertel 14713: =back
                   14714: 
1.608     albertel 14715: =head2 Usererfile file routines (/uploaded*)
                   14716: 
                   14717: =over 4
                   14718: 
                   14719: =item *
                   14720: 
                   14721: userfileupload(): main rotine for putting a file in a user or course's
                   14722:                   filespace, arguments are,
                   14723: 
1.620     albertel 14724:  formname - required - this is the name of the element in $env where the
1.608     albertel 14725:            filename, and the contents of the file to create/modifed exist
1.620     albertel 14726:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   14727:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  14728:  context - if coursedoc, store the file in the course of the active role
                   14729:              of the current user; 
                   14730:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   14731:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 14732:  subdir - required - subdirectory to put the file in under ../userfiles/
                   14733:          if undefined, it will be placed in "unknown"
                   14734: 
                   14735:  (This routine calls clean_filename() to remove any dangerous
                   14736:  characters from the filename, and then calls finuserfileupload() to
                   14737:  complete the transaction)
                   14738: 
                   14739:  returns either the url of the uploaded file (/uploaded/....) if successful
                   14740:  and /adm/notfound.html if unsuccessful
                   14741: 
                   14742: =item *
                   14743: 
                   14744: clean_filename(): routine for cleaing a filename up for storage in
                   14745:                  userfile space, argument is:
                   14746: 
                   14747:  filename - proposed filename
                   14748: 
                   14749: returns: the new clean filename
                   14750: 
                   14751: =item *
                   14752: 
1.1090    raeburn  14753: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 14754: userspace, probably shouldn't be called directly
                   14755: 
                   14756:   docuname: username or courseid of destination for the file
                   14757:   docudom: domain of user/course of destination for the file
                   14758:   formname: same as for userfileupload()
1.1090    raeburn  14759:   fname: filename (including subdirectories) for the file
                   14760:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   14761:   allfiles: reference to hash used to store objects found by parser
                   14762:   codebase: reference to hash used for codebases of java objects found by parser
                   14763:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   14764:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   14765:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   14766:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   14767:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   14768:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  14769:   mimetype: reference to scalar to accommodate mime type determined
                   14770:             from File::MMagic if $parser = parse.
1.608     albertel 14771: 
                   14772:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  14773:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   14774:  was 'overwrite').
                   14775:  
1.608     albertel 14776: 
                   14777: =item *
                   14778: 
                   14779: renameuserfile(): renames an existing userfile to a new name
                   14780: 
                   14781:   Args:
                   14782:    docuname: username or courseid of destination for the file
                   14783:    docudom: domain of user/course of destination for the file
                   14784:    old: current file name (including any subdirs under userfiles)
                   14785:    new: desired file name (including any subdirs under userfiles)
                   14786: 
                   14787: =item *
                   14788: 
                   14789: mkdiruserfile(): creates a directory is a userfiles dir
                   14790: 
                   14791:   Args:
                   14792:    docuname: username or courseid of destination for the file
                   14793:    docudom: domain of user/course of destination for the file
                   14794:    dir: dir to create (including any subdirs under userfiles)
                   14795: 
                   14796: =item *
                   14797: 
                   14798: removeuserfile(): removes a file that exists in userfiles
                   14799: 
                   14800:   Args:
                   14801:    docuname: username or courseid of destination for the file
                   14802:    docudom: domain of user/course of destination for the file
                   14803:    fname: filname to delete (including any subdirs under userfiles)
                   14804: 
                   14805: =item *
                   14806: 
                   14807: removeuploadedurl(): convience function for removeuserfile()
                   14808: 
                   14809:   Args:
                   14810:    url:  a full /uploaded/... url to delete
                   14811: 
1.747     albertel 14812: =item * 
                   14813: 
                   14814: get_portfile_permissions():
                   14815:   Args:
                   14816:     domain: domain of user or course contain the portfolio files
                   14817:     user: name of user or num of course contain the portfolio files
                   14818:   Returns:
                   14819:     hashref of a dump of the proper file_permissions.db
                   14820:    
                   14821: 
                   14822: =item * 
                   14823: 
                   14824: get_access_controls():
                   14825: 
                   14826: Args:
                   14827:   current_permissions: the hash ref returned from get_portfile_permissions()
                   14828:   group: (optional) the group you want the files associated with
                   14829:   file: (optional) the file you want access info on
                   14830: 
                   14831: Returns:
1.749     raeburn  14832:     a hash (keys are file names) of hashes containing
                   14833:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   14834:         values are XML containing access control settings (see below) 
1.747     albertel 14835: 
                   14836: Internal notes:
                   14837: 
1.749     raeburn  14838:  access controls are stored in file_permissions.db as key=value pairs.
                   14839:     key -> path to file/file_name\0uniqueID:scope_end_start
                   14840:         where scope -> public,guest,course,group,domains or users.
                   14841:               end -> UNIX time for end of access (0 -> no end date)
                   14842:               start -> UNIX time for start of access
                   14843: 
                   14844:     value -> XML description of access control
                   14845:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   14846:             <start></start>
                   14847:             <end></end>
                   14848: 
                   14849:             <password></password>  for scope type = guest
                   14850: 
                   14851:             <domain></domain>     for scope type = course or group
                   14852:             <number></number>
                   14853:             <roles id="">
                   14854:              <role></role>
                   14855:              <access></access>
                   14856:              <section></section>
                   14857:              <group></group>
                   14858:             </roles>
                   14859: 
                   14860:             <dom></dom>         for scope type = domains
                   14861: 
                   14862:             <users>             for scope type = users
                   14863:              <user>
                   14864:               <uname></uname>
                   14865:               <udom></udom>
                   14866:              </user>
                   14867:             </users>
                   14868:            </scope> 
                   14869:               
                   14870:  Access data is also aggregated for each file in an additional key=value pair:
                   14871:  key -> path to file/file_name\0accesscontrol 
                   14872:  value -> reference to hash
                   14873:           hash contains key = value pairs
                   14874:           where key = uniqueID:scope_end_start
                   14875:                 value = UNIX time record was last updated
                   14876: 
                   14877:           Used to improve speed of look-ups of access controls for each file.  
                   14878:  
                   14879:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   14880: 
1.1198    raeburn  14881: =item *
                   14882: 
1.749     raeburn  14883: modify_access_controls():
                   14884: 
                   14885: Modifies access controls for a portfolio file
                   14886: Args
                   14887: 1. file name
                   14888: 2. reference to hash of required changes,
                   14889: 3. domain
                   14890: 4. username
                   14891:   where domain,username are the domain of the portfolio owner 
                   14892:   (either a user or a course) 
                   14893: 
                   14894: Returns:
                   14895: 1. result of additions or updates ('ok' or 'error', with error message). 
                   14896: 2. result of deletions ('ok' or 'error', with error message).
                   14897: 3. reference to hash of any new or updated access controls.
                   14898: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   14899:    key = integer (inbound ID)
1.1198    raeburn  14900:    value = uniqueID
                   14901: 
                   14902: =item *
                   14903: 
                   14904: get_timebased_id():
                   14905: 
                   14906: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   14907: course via the Course Editor (e.g., folders, composite pages, 
                   14908: group bulletin boards).
                   14909: 
                   14910: Args: (first three required; six others optional)
                   14911: 
                   14912: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   14913:    docssequence, or name of group
                   14914: 
                   14915: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   14916:    e.g., num, boardids
                   14917: 
                   14918: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   14919:    file will be named nohist_namespace.db
                   14920: 
                   14921: 4. cdom: domain of course; default is current course domain from %env
                   14922: 
                   14923: 5. cnum: course number; default is current course number from %env
                   14924: 
                   14925: 6. idtype: set to concat if an additional digit is to be appended to the 
                   14926:    unix timestamp to form the suffix, if the plain timestamp is already
                   14927:    in use.  Default is to not do this, but simply increment the unix 
                   14928:    timestamp by 1 until a unique key is obtained.
                   14929: 
                   14930: 7. who: holder of locking key; defaults to user:domain for user.
                   14931: 
                   14932: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   14933:    retrying); default is 3.
                   14934: 
                   14935: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   14936: 
                   14937: Returns:
                   14938: 
                   14939: 1. suffix obtained (numeric)
                   14940: 
                   14941: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   14942: 
                   14943: 3. error: contains (localized) error message if an error occurred.
                   14944: 
1.747     albertel 14945: 
1.608     albertel 14946: =back
                   14947: 
1.243     albertel 14948: =head2 HTTP Helper Routines
                   14949: 
                   14950: =over 4
                   14951: 
1.191     harris41 14952: =item *
                   14953: 
                   14954: escape() : unpack non-word characters into CGI-compatible hex codes
                   14955: 
                   14956: =item *
                   14957: 
                   14958: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   14959: 
1.243     albertel 14960: =back
                   14961: 
                   14962: =head1 PRIVATE SUBROUTINES
                   14963: 
                   14964: =head2 Underlying communication routines (Shouldn't call)
                   14965: 
                   14966: =over 4
                   14967: 
                   14968: =item *
                   14969: 
                   14970: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   14971: 
                   14972: =item *
                   14973: 
                   14974: reply() : uses subreply to send a message to remote machine, logs all failures
                   14975: 
                   14976: =item *
                   14977: 
                   14978: critical() : passes a critical message to another server; if cannot
                   14979: get through then place message in connection buffer directory and
                   14980: returns con_delayed, if incapable of saving message, returns
                   14981: con_failed
                   14982: 
                   14983: =item *
                   14984: 
                   14985: reconlonc() : tries to reconnect lonc client processes.
                   14986: 
                   14987: =back
                   14988: 
                   14989: =head2 Resource Access Logging
                   14990: 
                   14991: =over 4
                   14992: 
                   14993: =item *
                   14994: 
                   14995: flushcourselogs() : flush (save) buffer logs and access logs
                   14996: 
                   14997: =item *
                   14998: 
                   14999: courselog($what) : save message for course in hash
                   15000: 
                   15001: =item *
                   15002: 
                   15003: courseacclog($what) : save message for course using &courselog().  Perform
                   15004: special processing for specific resource types (problems, exams, quizzes, etc).
                   15005: 
1.191     harris41 15006: =item *
                   15007: 
                   15008: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15009: as a PerlChildExitHandler
1.243     albertel 15010: 
                   15011: =back
                   15012: 
                   15013: =head2 Other
                   15014: 
                   15015: =over 4
                   15016: 
                   15017: =item *
                   15018: 
                   15019: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15020: 
                   15021: =back
                   15022: 
                   15023: =cut
1.877     foxr     15024: 

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