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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1323  ! raeburn     4: # $Id: lonnet.pm,v 1.1322 2016/09/21 04:47:57 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.841     albertel 4126: 	my %servers = &get_servers($dom,'library');
                   4127: 	foreach my $tryserver (keys(%servers)) {
                   4128: 	    unless (&reply('domroleput:'.$dom.':'.
                   4129: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4130: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4131: 	    }
1.662     raeburn  4132:         }
                   4133:     }
1.186     www      4134:     $dumpcount++;
1.157     www      4135: }
                   4136: 
                   4137: sub courselog {
                   4138:     my $what=shift;
1.158     www      4139:     $what=time.':'.$what;
1.620     albertel 4140:     unless ($env{'request.course.id'}) { return ''; }
                   4141:     $coursedombuf{$env{'request.course.id'}}=
                   4142:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4143:     $coursenumbuf{$env{'request.course.id'}}=
                   4144:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4145:     $coursehombuf{$env{'request.course.id'}}=
                   4146:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4147:     $coursedescrbuf{$env{'request.course.id'}}=
                   4148:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4149:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4150:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4151:     $courseownerbuf{$env{'request.course.id'}}=
                   4152:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4153:     $coursetypebuf{$env{'request.course.id'}}=
                   4154:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4155:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4156: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4157:     } else {
1.620     albertel 4158: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4159:     }
1.620     albertel 4160:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4161: 	&flushcourselogs();
                   4162:     }
1.158     www      4163: }
                   4164: 
                   4165: sub courseacclog {
                   4166:     my $fnsymb=shift;
1.620     albertel 4167:     unless ($env{'request.course.id'}) { return ''; }
                   4168:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4169:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4170:         $what.=':POST';
1.583     matthew  4171:         # FIXME: Probably ought to escape things....
1.800     albertel 4172: 	foreach my $key (keys(%env)) {
                   4173:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4174:                 my $formitem = $1;
                   4175:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4176:                     $what.=':'.$formitem.'='.$env{$key};
                   4177:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4178:                     $what.=':'.$formitem.'='.$env{$key};
                   4179:                 }
1.158     www      4180:             }
1.191     harris41 4181:         }
1.583     matthew  4182:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4183:         # FIXME: We should not be depending on a form parameter that someone
                   4184:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4185:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4186:             $what.= ':POST';
                   4187:             # FIXME: Probably ought to escape things....
                   4188:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4189:                                  'crsdiscuss') {
1.620     albertel 4190:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4191:             }
                   4192:         }
1.158     www      4193:     }
                   4194:     &courselog($what);
1.149     www      4195: }
                   4196: 
1.185     www      4197: sub countacc {
                   4198:     my $url=&declutter(shift);
1.458     matthew  4199:     return if (! defined($url) || $url eq '');
1.620     albertel 4200:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4201: #
                   4202: # Mark that this url was used in this course
                   4203: #
1.620     albertel 4204:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4205: #
                   4206: # Increase the access count for this resource in this child process
                   4207: #
1.281     www      4208:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4209:     $accesshash{$key}++;
1.185     www      4210: }
1.349     www      4211: 
1.361     www      4212: sub linklog {
                   4213:     my ($from,$to)=@_;
                   4214:     $from=&declutter($from);
                   4215:     $to=&declutter($to);
                   4216:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4217:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4218: }
1.1160    www      4219: 
                   4220: sub statslog {
                   4221:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4222:     if ($users<2) { return; }
                   4223:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4224:             'course'       => $env{'request.course.id'},
                   4225:             'sections'     => '"all"',
                   4226:             'num_students' => $users,
                   4227:             'part'         => $part,
                   4228:             'symb'         => $symb,
                   4229:             'mean_tries'   => $av_attempts,
                   4230:             'deg_of_diff'  => $degdiff});
                   4231:     foreach my $key (keys(%dynstore)) {
                   4232:         $accesshash{$key}=$dynstore{$key};
                   4233:     }
                   4234: }
1.361     www      4235:   
1.349     www      4236: sub userrolelog {
                   4237:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4238:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4239:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4240:        $userrolehash
                   4241:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4242:                     =$tend.':'.$tstart;
1.662     raeburn  4243:     }
1.1169    droeschl 4244:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4245:        $userrolehash
                   4246:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4247:                     =$tend.':'.$tstart;
                   4248:     }
1.1169    droeschl 4249:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  4250:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4251:        $domainrolehash
                   4252:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4253:                     = $tend.':'.$tstart;
                   4254:     }
1.351     www      4255: }
                   4256: 
1.957     raeburn  4257: sub courserolelog {
                   4258:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  4259:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4260:         my $cdom = $1;
                   4261:         my $cnum = $2;
                   4262:         my $sec = $3;
                   4263:         my $namespace = 'rolelog';
                   4264:         my %storehash = (
                   4265:                            role    => $trole,
                   4266:                            start   => $tstart,
                   4267:                            end     => $tend,
                   4268:                            selfenroll => $selfenroll,
                   4269:                            context    => $context,
                   4270:                         );
                   4271:         if ($trole eq 'gr') {
                   4272:             $namespace = 'groupslog';
                   4273:             $storehash{'group'} = $sec;
                   4274:         } else {
                   4275:             $storehash{'section'} = $sec;
                   4276:         }
1.1188    raeburn  4277:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4278:                    $domain,$cnum,$cdom);
1.1184    raeburn  4279:         if (($trole ne 'st') || ($sec ne '')) {
                   4280:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4281:         }
                   4282:     }
                   4283:     return;
                   4284: }
                   4285: 
1.1184    raeburn  4286: sub domainrolelog {
                   4287:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4288:     if ($area =~ m{^/($match_domain)/$}) {
                   4289:         my $cdom = $1;
                   4290:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4291:         my $namespace = 'rolelog';
                   4292:         my %storehash = (
                   4293:                            role    => $trole,
                   4294:                            start   => $tstart,
                   4295:                            end     => $tend,
                   4296:                            context => $context,
                   4297:                         );
1.1188    raeburn  4298:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4299:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  4300:     }
                   4301:     return;
                   4302: 
                   4303: }
                   4304: 
                   4305: sub coauthorrolelog {
                   4306:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4307:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4308:         my $audom = $1;
                   4309:         my $auname = $2;
                   4310:         my $namespace = 'rolelog';
                   4311:         my %storehash = (
                   4312:                            role    => $trole,
                   4313:                            start   => $tstart,
                   4314:                            end     => $tend,
                   4315:                            context => $context,
                   4316:                         );
1.1188    raeburn  4317:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4318:                    $domain,$auname,$audom);
1.1184    raeburn  4319:     }
                   4320:     return;
                   4321: }
                   4322: 
1.351     www      4323: sub get_course_adv_roles {
1.948     raeburn  4324:     my ($cid,$codes) = @_;
1.620     albertel 4325:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4326:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4327:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4328:     my %nothide=();
1.800     albertel 4329:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4330:         if ($user !~ /:/) {
                   4331: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4332:         } else {
                   4333:             $nothide{$user}=1;
                   4334:         }
1.470     www      4335:     }
1.1219    raeburn  4336:     my @possdoms = ($coursehash{'domain'});
                   4337:     if ($coursehash{'checkforpriv'}) {
                   4338:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4339:     }
1.351     www      4340:     my %returnhash=();
                   4341:     my %dumphash=
                   4342:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4343:     my $now=time;
1.997     raeburn  4344:     my %privileged;
1.1000    raeburn  4345:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4346: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4347:         if (($tstart) && ($tstart<0)) { next; }
                   4348:         if (($tend) && ($tend<$now)) { next; }
                   4349:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4350:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4351: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  4352:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4353:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4354: 	if ($role eq 'cr') { next; }
1.948     raeburn  4355:         if ($codes) {
                   4356:             if ($section) { $role .= ':'.$section; }
                   4357:             if ($returnhash{$role}) {
                   4358:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4359:             } else {
                   4360:                 $returnhash{$role}=$username.':'.$domain;
                   4361:             }
1.351     www      4362:         } else {
1.988     raeburn  4363:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4364:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4365:             if ($returnhash{$key}) {
                   4366: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4367:             } else {
                   4368:                 $returnhash{$key}=$username.':'.$domain;
                   4369:             }
1.351     www      4370:         }
1.948     raeburn  4371:     }
1.400     www      4372:     return %returnhash;
                   4373: }
                   4374: 
                   4375: sub get_my_roles {
1.937     raeburn  4376:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4377:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4378:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4379:     my (%dumphash,%nothide);
1.1086    raeburn  4380:     if ($context eq 'userroles') {
1.1166    raeburn  4381:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4382:     } else {
1.1219    raeburn  4383:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4384:         if ($hidepriv) {
                   4385:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4386:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4387:                 if ($user !~ /:/) {
                   4388:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4389:                 } else {
                   4390:                     $nothide{$user} = 1;
                   4391:                 }
                   4392:             }
                   4393:         }
1.858     raeburn  4394:     }
1.400     www      4395:     my %returnhash=();
                   4396:     my $now=time;
1.999     raeburn  4397:     my %privileged;
1.800     albertel 4398:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4399:         my ($role,$tend,$tstart);
                   4400:         if ($context eq 'userroles') {
1.1149    raeburn  4401:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4402: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4403:         } else {
                   4404:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4405:         }
1.400     www      4406:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4407:         my $status = 'active';
1.939     raeburn  4408:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4409:             $status = 'previous';
                   4410:         } 
                   4411:         if (($tstart) && ($now<$tstart)) {
                   4412:             $status = 'future';
                   4413:         }
                   4414:         if (ref($types) eq 'ARRAY') {
                   4415:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4416:                 next;
                   4417:             } 
                   4418:         } else {
                   4419:             if ($status ne 'active') {
                   4420:                 next;
                   4421:             }
                   4422:         }
1.867     raeburn  4423:         my ($rolecode,$username,$domain,$section,$area);
                   4424:         if ($context eq 'userroles') {
1.1186    raeburn  4425:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4426:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4427:         } else {
                   4428:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4429:         }
1.832     raeburn  4430:         if (ref($roledoms) eq 'ARRAY') {
                   4431:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4432:                 next;
                   4433:             }
                   4434:         }
                   4435:         if (ref($roles) eq 'ARRAY') {
                   4436:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4437:                 if ($role =~ /^cr\//) {
                   4438:                     if (!grep(/^cr$/,@{$roles})) {
                   4439:                         next;
                   4440:                     }
1.1104    raeburn  4441:                 } elsif ($role =~ /^gr\//) {
                   4442:                     if (!grep(/^gr$/,@{$roles})) {
                   4443:                         next;
                   4444:                     }
1.922     raeburn  4445:                 } else {
                   4446:                     next;
                   4447:                 }
1.832     raeburn  4448:             }
1.867     raeburn  4449:         }
1.937     raeburn  4450:         if ($hidepriv) {
1.1219    raeburn  4451:             my @privroles = ('dc','su');
1.999     raeburn  4452:             if ($context eq 'userroles') {
1.1219    raeburn  4453:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4454:             } else {
1.1219    raeburn  4455:                 my $possdoms = [$domain];
                   4456:                 if (ref($roledoms) eq 'ARRAY') {
                   4457:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  4458:                 }
1.1219    raeburn  4459:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4460:                     if (!$nothide{$username.':'.$domain}) {
                   4461:                         next;
                   4462:                     }
                   4463:                 }
1.937     raeburn  4464:             }
                   4465:         }
1.933     raeburn  4466:         if ($withsec) {
                   4467:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4468:                 $tstart.':'.$tend;
                   4469:         } else {
                   4470:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4471:         }
1.832     raeburn  4472:     }
1.373     www      4473:     return %returnhash;
1.399     www      4474: }
                   4475: 
                   4476: # ----------------------------------------------------- Frontpage Announcements
                   4477: #
                   4478: #
                   4479: 
                   4480: sub postannounce {
                   4481:     my ($server,$text)=@_;
1.844     albertel 4482:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4483:     unless ($text=~/\w/) { $text=''; }
                   4484:     return &reply('setannounce:'.&escape($text),$server);
                   4485: }
                   4486: 
                   4487: sub getannounce {
1.448     albertel 4488: 
                   4489:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4490: 	my $announcement='';
1.800     albertel 4491: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4492: 	close($fh);
1.399     www      4493: 	if ($announcement=~/\w/) { 
                   4494: 	    return 
                   4495:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4496:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4497: 	} else {
                   4498: 	    return '';
                   4499: 	}
                   4500:     } else {
                   4501: 	return '';
                   4502:     }
1.351     www      4503: }
1.353     www      4504: 
                   4505: # ---------------------------------------------------------- Course ID routines
                   4506: # Deal with domain's nohist_courseid.db files
                   4507: #
                   4508: 
                   4509: sub courseidput {
1.921     raeburn  4510:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4511:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4512:     my $outcome;
                   4513:     if ($caller eq 'timeonly') {
                   4514:         my $cids = '';
                   4515:         foreach my $item (keys(%$storehash)) {
                   4516:             $cids.=&escape($item).'&';
                   4517:         }
                   4518:         $cids=~s/\&$//;
                   4519:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4520:                           $coursehome);       
                   4521:     } else {
                   4522:         my $items = '';
                   4523:         foreach my $item (keys(%$storehash)) {
                   4524:             $items.= &escape($item).'='.
                   4525:                      &freeze_escape($$storehash{$item}).'&';
                   4526:         }
                   4527:         $items=~s/\&$//;
                   4528:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4529:                           $coursehome);
1.918     raeburn  4530:     }
                   4531:     if ($outcome eq 'unknown_cmd') {
                   4532:         my $what;
                   4533:         foreach my $cid (keys(%$storehash)) {
                   4534:             $what .= &escape($cid).'=';
1.921     raeburn  4535:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4536:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4537:             }
                   4538:             $what =~ s/\:$/&/;
                   4539:         }
                   4540:         $what =~ s/\&$//;  
                   4541:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4542:     } else {
                   4543:         return $outcome;
                   4544:     }
1.353     www      4545: }
                   4546: 
                   4547: sub courseiddump {
1.921     raeburn  4548:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4549:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4550:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  4551:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  4552:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  4553:     my $as_hash = 1;
                   4554:     my %returnhash;
                   4555:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4556:     my %libserv = &all_library();
                   4557:     foreach my $tryserver (keys(%libserv)) {
                   4558:         if ( (  $hostidflag == 1 
                   4559: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4560: 	     || (!defined($hostidflag)) ) {
                   4561: 
1.918     raeburn  4562: 	    if (($domfilter eq '') ||
                   4563: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 4564:                 my $rep;
                   4565:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   4566:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   4567:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   4568:                                 &escape($descfilter), &escape($instcodefilter), 
                   4569:                                 &escape($ownerfilter), &escape($coursefilter),
                   4570:                                 &escape($typefilter), &escape($regexp_ok), 
                   4571:                                 $as_hash, &escape($selfenrollonly), 
                   4572:                                 &escape($catfilter), $showhidden, $caller, 
                   4573:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   4574:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  4575:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   4576:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 4577:                 } else {
                   4578:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4579:                              $sincefilter.':'.&escape($descfilter).':'.
                   4580:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4581:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4582:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4583:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4584:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4585:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4586:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  4587:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   4588:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 4589:                 }
                   4590:                      
1.918     raeburn  4591:                 my @pairs=split(/\&/,$rep);
                   4592:                 foreach my $item (@pairs) {
                   4593:                     my ($key,$value)=split(/\=/,$item,2);
                   4594:                     $key = &unescape($key);
                   4595:                     next if ($key =~ /^error: 2 /);
                   4596:                     my $result = &thaw_unescape($value);
                   4597:                     if (ref($result) eq 'HASH') {
                   4598:                         $returnhash{$key}=$result;
                   4599:                     } else {
1.921     raeburn  4600:                         my @responses = split(/:/,$value);
                   4601:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4602:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4603:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4604:                         }
1.1008    raeburn  4605:                     }
1.353     www      4606:                 }
                   4607:             }
                   4608:         }
                   4609:     }
                   4610:     return %returnhash;
                   4611: }
                   4612: 
1.1055    raeburn  4613: sub courselastaccess {
                   4614:     my ($cdom,$cnum,$hostidref) = @_;
                   4615:     my %returnhash;
                   4616:     if ($cdom && $cnum) {
                   4617:         my $chome = &homeserver($cnum,$cdom);
                   4618:         if ($chome ne 'no_host') {
                   4619:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4620:             &extract_lastaccess(\%returnhash,$rep);
                   4621:         }
                   4622:     } else {
                   4623:         if (!$cdom) { $cdom=''; }
                   4624:         my %libserv = &all_library();
                   4625:         foreach my $tryserver (keys(%libserv)) {
                   4626:             if (ref($hostidref) eq 'ARRAY') {
                   4627:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4628:             } 
                   4629:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4630:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4631:                 &extract_lastaccess(\%returnhash,$rep);
                   4632:             }
                   4633:         }
                   4634:     }
                   4635:     return %returnhash;
                   4636: }
                   4637: 
                   4638: sub extract_lastaccess {
                   4639:     my ($returnhash,$rep) = @_;
                   4640:     if (ref($returnhash) eq 'HASH') {
                   4641:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4642:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4643:                  $rep eq '') {
                   4644:             my @pairs=split(/\&/,$rep);
                   4645:             foreach my $item (@pairs) {
                   4646:                 my ($key,$value)=split(/\=/,$item,2);
                   4647:                 $key = &unescape($key);
                   4648:                 next if ($key =~ /^error: 2 /);
                   4649:                 $returnhash->{$key} = &thaw_unescape($value);
                   4650:             }
                   4651:         }
                   4652:     }
                   4653:     return;
                   4654: }
                   4655: 
1.658     raeburn  4656: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4657: 
                   4658: sub dcmailput {
1.685     raeburn  4659:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4660:     my $status = &Apache::lonnet::critical(
1.740     www      4661:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4662:        &escape($message),$server);
1.662     raeburn  4663:     return $status;
                   4664: }
                   4665: 
1.658     raeburn  4666: sub dcmaildump {
                   4667:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4668:     my %returnhash=();
1.846     albertel 4669: 
                   4670:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4671:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4672:                                                          &escape($enddate).':';
                   4673: 	my @esc_senders=map { &escape($_)} @$senders;
                   4674: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4675: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4676:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4677:             if (($key) && ($value)) {
                   4678:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4679:             }
                   4680:         }
                   4681:     }
                   4682:     return %returnhash;
                   4683: }
1.662     raeburn  4684: # ---------------------------------------------------------- Domain roles
                   4685: 
                   4686: sub get_domain_roles {
                   4687:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4688:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4689:         $startdate = '.';
                   4690:     }
1.1018    raeburn  4691:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4692:         $enddate = '.';
                   4693:     }
1.922     raeburn  4694:     my $rolelist;
                   4695:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  4696:         $rolelist = join('&',@{$roles});
1.922     raeburn  4697:     }
1.662     raeburn  4698:     my %personnel = ();
1.841     albertel 4699: 
                   4700:     my %servers = &get_servers($dom,'library');
                   4701:     foreach my $tryserver (keys(%servers)) {
                   4702: 	%{$personnel{$tryserver}}=();
                   4703: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4704: 					    &escape($startdate).':'.
                   4705: 					    &escape($enddate).':'.
                   4706: 					    &escape($rolelist), $tryserver))) {
                   4707: 	    my ($key,$value) = split(/\=/,$line,2);
                   4708: 	    if (($key) && ($value)) {
                   4709: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4710: 	    }
                   4711: 	}
1.662     raeburn  4712:     }
                   4713:     return %personnel;
                   4714: }
1.658     raeburn  4715: 
1.1057    www      4716: # ----------------------------------------------------------- Interval timing 
1.149     www      4717: 
1.1153    www      4718: {
                   4719: # Caches needed for speedup of navmaps
                   4720: # We don't want to cache this for very long at all (5 seconds at most)
                   4721: # 
                   4722: # The user for whom we cache
                   4723: my $cachedkey='';
                   4724: # The cached times for this user
                   4725: my %cachedtimes=();
                   4726: # When this was last done
1.1282    raeburn  4727: my $cachedtime='';
1.1153    www      4728: 
                   4729: sub load_all_first_access {
1.1308    raeburn  4730:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      4731:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  4732:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   4733:         (!$ignorecache)) {
1.1154    raeburn  4734:         return;
                   4735:     }
                   4736:     $cachedtime=time;
                   4737:     $cachedkey=$uname.':'.$udom;
                   4738:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4739: }
                   4740: 
1.504     albertel 4741: sub get_first_access {
1.1308    raeburn  4742:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 4743:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4744:     if ($argsymb) { $symb=$argsymb; }
                   4745:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4746:     if ($argmap) { $map = $argmap; }
1.926     albertel 4747:     if ($type eq 'course') {
                   4748: 	$res='course';
                   4749:     } elsif ($type eq 'map') {
1.588     albertel 4750: 	$res=&symbread($map);
                   4751:     } else {
                   4752: 	$res=$symb;
                   4753:     }
1.1308    raeburn  4754:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      4755:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4756: }
                   4757: 
                   4758: sub set_first_access {
1.1162    raeburn  4759:     my ($type,$interval)=@_;
1.790     albertel 4760:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4761:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4762:     if ($type eq 'course') {
                   4763: 	$res='course';
                   4764:     } elsif ($type eq 'map') {
1.588     albertel 4765: 	$res=&symbread($map);
                   4766:     } else {
                   4767: 	$res=$symb;
                   4768:     }
1.1153    www      4769:     $cachedkey='';
1.1162    raeburn  4770:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4771:     if (!$firstaccess) {
1.1162    raeburn  4772:         my $start = time;
                   4773: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4774:                           $udom,$uname);
                   4775:         if ($putres eq 'ok') {
                   4776:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4777:                  $udom,$uname); 
                   4778:             &appenv(
                   4779:                      {
                   4780:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4781:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4782:                      }
                   4783:                   );
                   4784:         }
                   4785:         return $putres;
1.505     albertel 4786:     }
                   4787:     return 'already_set';
1.504     albertel 4788: }
1.1153    www      4789: }
1.1282    raeburn  4790: 
1.110     www      4791: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4792: 
                   4793: sub expirespread {
                   4794:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4795:     my $cid=$env{'request.course.id'}; 
1.110     www      4796:     if ($cid) {
                   4797:        my $now=time;
                   4798:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4799:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4800:                             $env{'course.'.$cid.'.num'}.
1.110     www      4801: 	        	    ':nohist_expirationdates:'.
                   4802:                             &escape($key).'='.$now,
1.620     albertel 4803:                             $env{'course.'.$cid.'.home'})
1.110     www      4804:     }
                   4805:     return 'ok';
1.14      www      4806: }
                   4807: 
1.109     www      4808: # ----------------------------------------------------- Devalidate Spreadsheets
                   4809: 
                   4810: sub devalidate {
1.325     www      4811:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4812:     my $cid=$env{'request.course.id'}; 
1.109     www      4813:     if ($cid) {
1.391     matthew  4814:         # delete the stored spreadsheets for
                   4815:         # - the student level sheet of this user in course's homespace
                   4816:         # - the assessment level sheet for this resource 
                   4817:         #   for this user in user's homespace
1.553     albertel 4818: 	# - current conditional state info
1.325     www      4819: 	my $key=$uname.':'.$udom.':';
1.109     www      4820:         my $status=
1.299     matthew  4821: 	    &del('nohist_calculatedsheets',
1.391     matthew  4822: 		 [$key.'studentcalc:'],
1.620     albertel 4823: 		 $env{'course.'.$cid.'.domain'},
                   4824: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4825: 		.' '.
                   4826: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4827: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4828:         unless ($status eq 'ok ok') {
                   4829:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4830:                     $uname.' at '.$udom.' for '.
1.109     www      4831: 		    $symb.': '.$status);
1.133     albertel 4832:         }
1.553     albertel 4833: 	&delenv('user.state.'.$cid);
1.109     www      4834:     }
                   4835: }
                   4836: 
1.265     albertel 4837: sub get_scalar {
                   4838:     my ($string,$end) = @_;
                   4839:     my $value;
                   4840:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4841: 	$value = $1;
                   4842:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4843: 	$value = $1;
                   4844:     }
                   4845:     return &unescape($value);
                   4846: }
                   4847: 
                   4848: sub array2str {
                   4849:   my (@array) = @_;
                   4850:   my $result=&arrayref2str(\@array);
                   4851:   $result=~s/^__ARRAY_REF__//;
                   4852:   $result=~s/__END_ARRAY_REF__$//;
                   4853:   return $result;
                   4854: }
                   4855: 
1.204     albertel 4856: sub arrayref2str {
                   4857:   my ($arrayref) = @_;
1.265     albertel 4858:   my $result='__ARRAY_REF__';
1.204     albertel 4859:   foreach my $elem (@$arrayref) {
1.265     albertel 4860:     if(ref($elem) eq 'ARRAY') {
                   4861:       $result.=&arrayref2str($elem).'&';
                   4862:     } elsif(ref($elem) eq 'HASH') {
                   4863:       $result.=&hashref2str($elem).'&';
                   4864:     } elsif(ref($elem)) {
                   4865:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4866:     } else {
                   4867:       $result.=&escape($elem).'&';
                   4868:     }
                   4869:   }
                   4870:   $result=~s/\&$//;
1.265     albertel 4871:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4872:   return $result;
                   4873: }
                   4874: 
1.168     albertel 4875: sub hash2str {
1.204     albertel 4876:   my (%hash) = @_;
                   4877:   my $result=&hashref2str(\%hash);
1.265     albertel 4878:   $result=~s/^__HASH_REF__//;
                   4879:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4880:   return $result;
                   4881: }
                   4882: 
                   4883: sub hashref2str {
                   4884:   my ($hashref)=@_;
1.265     albertel 4885:   my $result='__HASH_REF__';
1.800     albertel 4886:   foreach my $key (sort(keys(%$hashref))) {
                   4887:     if (ref($key) eq 'ARRAY') {
                   4888:       $result.=&arrayref2str($key).'=';
                   4889:     } elsif (ref($key) eq 'HASH') {
                   4890:       $result.=&hashref2str($key).'=';
                   4891:     } elsif (ref($key)) {
1.265     albertel 4892:       $result.='=';
1.800     albertel 4893:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4894:     } else {
1.1132    raeburn  4895: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4896:     }
                   4897: 
1.800     albertel 4898:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4899:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4900:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4901:       $result.=&hashref2str($hashref->{$key}).'&';
                   4902:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4903:        $result.='&';
1.800     albertel 4904:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4905:     } else {
1.800     albertel 4906:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4907:     }
                   4908:   }
1.168     albertel 4909:   $result=~s/\&$//;
1.265     albertel 4910:   $result .= '__END_HASH_REF__';
1.168     albertel 4911:   return $result;
                   4912: }
                   4913: 
                   4914: sub str2hash {
1.265     albertel 4915:     my ($string)=@_;
                   4916:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4917:     return %$hash;
                   4918: }
                   4919: 
                   4920: sub str2hashref {
1.168     albertel 4921:   my ($string) = @_;
1.265     albertel 4922: 
                   4923:   my %hash;
                   4924: 
                   4925:   if($string !~ /^__HASH_REF__/) {
                   4926:       if (! ($string eq '' || !defined($string))) {
                   4927: 	  $hash{'error'}='Not hash reference';
                   4928:       }
                   4929:       return (\%hash, $string);
                   4930:   }
                   4931: 
                   4932:   $string =~ s/^__HASH_REF__//;
                   4933: 
                   4934:   while($string !~ /^__END_HASH_REF__/) {
                   4935:       #key
                   4936:       my $key='';
                   4937:       if($string =~ /^__HASH_REF__/) {
                   4938:           ($key, $string)=&str2hashref($string);
                   4939:           if(defined($key->{'error'})) {
                   4940:               $hash{'error'}='Bad data';
                   4941:               return (\%hash, $string);
                   4942:           }
                   4943:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4944:           ($key, $string)=&str2arrayref($string);
                   4945:           if($key->[0] eq 'Array reference error') {
                   4946:               $hash{'error'}='Bad data';
                   4947:               return (\%hash, $string);
                   4948:           }
                   4949:       } else {
                   4950:           $string =~ s/^(.*?)=//;
1.267     albertel 4951: 	  $key=&unescape($1);
1.265     albertel 4952:       }
                   4953:       $string =~ s/^=//;
                   4954: 
                   4955:       #value
                   4956:       my $value='';
                   4957:       if($string =~ /^__HASH_REF__/) {
                   4958:           ($value, $string)=&str2hashref($string);
                   4959:           if(defined($value->{'error'})) {
                   4960:               $hash{'error'}='Bad data';
                   4961:               return (\%hash, $string);
                   4962:           }
                   4963:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4964:           ($value, $string)=&str2arrayref($string);
                   4965:           if($value->[0] eq 'Array reference error') {
                   4966:               $hash{'error'}='Bad data';
                   4967:               return (\%hash, $string);
                   4968:           }
                   4969:       } else {
                   4970: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4971:       }
                   4972:       $string =~ s/^&//;
                   4973: 
                   4974:       $hash{$key}=$value;
1.204     albertel 4975:   }
1.265     albertel 4976: 
                   4977:   $string =~ s/^__END_HASH_REF__//;
                   4978: 
                   4979:   return (\%hash, $string);
1.204     albertel 4980: }
                   4981: 
                   4982: sub str2array {
1.265     albertel 4983:     my ($string)=@_;
                   4984:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4985:     return @$array;
                   4986: }
                   4987: 
                   4988: sub str2arrayref {
1.204     albertel 4989:   my ($string) = @_;
1.265     albertel 4990:   my @array;
                   4991: 
                   4992:   if($string !~ /^__ARRAY_REF__/) {
                   4993:       if (! ($string eq '' || !defined($string))) {
                   4994: 	  $array[0]='Array reference error';
                   4995:       }
                   4996:       return (\@array, $string);
                   4997:   }
                   4998: 
                   4999:   $string =~ s/^__ARRAY_REF__//;
                   5000: 
                   5001:   while($string !~ /^__END_ARRAY_REF__/) {
                   5002:       my $value='';
                   5003:       if($string =~ /^__HASH_REF__/) {
                   5004:           ($value, $string)=&str2hashref($string);
                   5005:           if(defined($value->{'error'})) {
                   5006:               $array[0] ='Array reference error';
                   5007:               return (\@array, $string);
                   5008:           }
                   5009:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5010:           ($value, $string)=&str2arrayref($string);
                   5011:           if($value->[0] eq 'Array reference error') {
                   5012:               $array[0] ='Array reference error';
                   5013:               return (\@array, $string);
                   5014:           }
                   5015:       } else {
                   5016: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5017:       }
                   5018:       $string =~ s/^&//;
                   5019: 
                   5020:       push(@array, $value);
1.191     harris41 5021:   }
1.265     albertel 5022: 
                   5023:   $string =~ s/^__END_ARRAY_REF__//;
                   5024: 
                   5025:   return (\@array, $string);
1.168     albertel 5026: }
                   5027: 
1.167     albertel 5028: # -------------------------------------------------------------------Temp Store
                   5029: 
1.168     albertel 5030: sub tmpreset {
                   5031:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5032:   if (!$symb) {
                   5033:     $symb=&symbread();
1.620     albertel 5034:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5035:   }
                   5036:   $symb=escape($symb);
                   5037: 
1.620     albertel 5038:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5039:   $namespace=~s/\//\_/g;
                   5040:   $namespace=~s/\W//g;
                   5041: 
1.620     albertel 5042:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5043:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5044:   if ($domain eq 'public' && $stuname eq 'public') {
                   5045:       $stuname=$ENV{'REMOTE_ADDR'};
                   5046:   }
1.1117    foxr     5047:   my $path=LONCAPA::tempdir();
1.168     albertel 5048:   my %hash;
                   5049:   if (tie(%hash,'GDBM_File',
                   5050: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5051: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5052:     foreach my $key (keys(%hash)) {
1.180     albertel 5053:       if ($key=~ /:$symb/) {
1.168     albertel 5054: 	delete($hash{$key});
                   5055:       }
                   5056:     }
                   5057:   }
                   5058: }
                   5059: 
1.167     albertel 5060: sub tmpstore {
1.168     albertel 5061:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5062: 
                   5063:   if (!$symb) {
                   5064:     $symb=&symbread();
1.620     albertel 5065:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5066:   }
                   5067:   $symb=escape($symb);
                   5068: 
                   5069:   if (!$namespace) {
                   5070:     # I don't think we would ever want to store this for a course.
                   5071:     # it seems this will only be used if we don't have a course.
1.620     albertel 5072:     #$namespace=$env{'request.course.id'};
1.168     albertel 5073:     #if (!$namespace) {
1.620     albertel 5074:       $namespace=$env{'request.state'};
1.168     albertel 5075:     #}
                   5076:   }
                   5077:   $namespace=~s/\//\_/g;
                   5078:   $namespace=~s/\W//g;
1.620     albertel 5079:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5080:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5081:   if ($domain eq 'public' && $stuname eq 'public') {
                   5082:       $stuname=$ENV{'REMOTE_ADDR'};
                   5083:   }
1.168     albertel 5084:   my $now=time;
                   5085:   my %hash;
1.1117    foxr     5086:   my $path=LONCAPA::tempdir();
1.168     albertel 5087:   if (tie(%hash,'GDBM_File',
                   5088: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5089: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5090:     $hash{"version:$symb"}++;
                   5091:     my $version=$hash{"version:$symb"};
                   5092:     my $allkeys=''; 
                   5093:     foreach my $key (keys(%$storehash)) {
                   5094:       $allkeys.=$key.':';
1.591     albertel 5095:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5096:     }
                   5097:     $hash{"$version:$symb:timestamp"}=$now;
                   5098:     $allkeys.='timestamp';
                   5099:     $hash{"$version:keys:$symb"}=$allkeys;
                   5100:     if (untie(%hash)) {
                   5101:       return 'ok';
                   5102:     } else {
                   5103:       return "error:$!";
                   5104:     }
                   5105:   } else {
                   5106:     return "error:$!";
                   5107:   }
                   5108: }
1.167     albertel 5109: 
1.168     albertel 5110: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5111: 
1.168     albertel 5112: sub tmprestore {
                   5113:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5114: 
1.168     albertel 5115:   if (!$symb) {
                   5116:     $symb=&symbread();
1.620     albertel 5117:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5118:   }
                   5119:   $symb=escape($symb);
                   5120: 
1.620     albertel 5121:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5122: 
1.620     albertel 5123:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5124:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5125:   if ($domain eq 'public' && $stuname eq 'public') {
                   5126:       $stuname=$ENV{'REMOTE_ADDR'};
                   5127:   }
1.168     albertel 5128:   my %returnhash;
                   5129:   $namespace=~s/\//\_/g;
                   5130:   $namespace=~s/\W//g;
                   5131:   my %hash;
1.1117    foxr     5132:   my $path=LONCAPA::tempdir();
1.168     albertel 5133:   if (tie(%hash,'GDBM_File',
                   5134: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5135: 	  &GDBM_READER(),0640)) {
1.168     albertel 5136:     my $version=$hash{"version:$symb"};
                   5137:     $returnhash{'version'}=$version;
                   5138:     my $scope;
                   5139:     for ($scope=1;$scope<=$version;$scope++) {
                   5140:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5141:       my @keys=split(/:/,$vkeys);
                   5142:       my $key;
                   5143:       $returnhash{"$scope:keys"}=$vkeys;
                   5144:       foreach $key (@keys) {
1.591     albertel 5145: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5146: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5147:       }
                   5148:     }
1.168     albertel 5149:     if (!(untie(%hash))) {
                   5150:       return "error:$!";
                   5151:     }
                   5152:   } else {
                   5153:     return "error:$!";
                   5154:   }
                   5155:   return %returnhash;
1.167     albertel 5156: }
                   5157: 
1.9       www      5158: # ----------------------------------------------------------------------- Store
                   5159: 
                   5160: sub store {
1.1269    raeburn  5161:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5162:     my $home='';
                   5163: 
1.168     albertel 5164:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5165: 
1.213     www      5166:     $symb=&symbclean($symb);
1.122     albertel 5167:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5168: 
1.620     albertel 5169:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5170:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5171: 
                   5172:     &devalidate($symb,$stuname,$domain);
1.109     www      5173: 
                   5174:     $symb=escape($symb);
1.187     www      5175:     if (!$namespace) { 
1.620     albertel 5176:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5177:           return ''; 
                   5178:        } 
                   5179:     }
1.620     albertel 5180:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5181: 
                   5182:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5183:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5184: 
1.12      www      5185:     my $namevalue='';
1.800     albertel 5186:     foreach my $key (keys(%$storehash)) {
                   5187:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5188:     }
1.12      www      5189:     $namevalue=~s/\&$//;
1.187     www      5190:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  5191:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5192: }
                   5193: 
1.47      www      5194: # -------------------------------------------------------------- Critical Store
                   5195: 
                   5196: sub cstore {
1.1269    raeburn  5197:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5198:     my $home='';
                   5199: 
1.168     albertel 5200:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5201: 
1.213     www      5202:     $symb=&symbclean($symb);
1.122     albertel 5203:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5204: 
1.620     albertel 5205:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5206:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5207: 
                   5208:     &devalidate($symb,$stuname,$domain);
1.109     www      5209: 
                   5210:     $symb=escape($symb);
1.187     www      5211:     if (!$namespace) { 
1.620     albertel 5212:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5213:           return ''; 
                   5214:        } 
                   5215:     }
1.620     albertel 5216:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5217: 
                   5218:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5219:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5220: 
1.47      www      5221:     my $namevalue='';
1.800     albertel 5222:     foreach my $key (keys(%$storehash)) {
                   5223:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5224:     }
1.47      www      5225:     $namevalue=~s/\&$//;
1.187     www      5226:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5227:     return critical
1.1269    raeburn  5228:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5229: }
                   5230: 
1.9       www      5231: # --------------------------------------------------------------------- Restore
                   5232: 
                   5233: sub restore {
1.124     www      5234:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5235:     my $home='';
                   5236: 
1.168     albertel 5237:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5238: 
1.122     albertel 5239:     if (!$symb) {
1.1224    raeburn  5240:         return if ($namespace eq 'courserequests');
                   5241:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5242:     } else {
1.1224    raeburn  5243:         unless ($namespace eq 'courserequests') {
                   5244:             $symb=&escape(&symbclean($symb));
                   5245:         }
1.122     albertel 5246:     }
1.188     www      5247:     if (!$namespace) { 
1.620     albertel 5248:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5249:           return ''; 
                   5250:        } 
                   5251:     }
1.620     albertel 5252:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5253:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5254:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5255:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5256: 
1.12      www      5257:     my %returnhash=();
1.800     albertel 5258:     foreach my $line (split(/\&/,$answer)) {
                   5259: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5260:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5261:     }
1.75      www      5262:     my $version;
                   5263:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5264:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5265:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5266:        }
1.75      www      5267:     }
1.13      www      5268:     return %returnhash;
1.34      www      5269: }
                   5270: 
                   5271: # ---------------------------------------------------------- Course Description
1.1118    foxr     5272: #
                   5273: #  
1.34      www      5274: 
                   5275: sub coursedescription {
1.731     albertel 5276:     my ($courseid,$args)=@_;
1.34      www      5277:     $courseid=~s/^\///;
1.49      www      5278:     $courseid=~s/\_/\//g;
1.34      www      5279:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5280:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5281:     my $normalid=$cdomain.'_'.$cnum;
                   5282:     # need to always cache even if we get errors otherwise we keep 
                   5283:     # trying and trying and trying to get the course description.
                   5284:     my %envhash=();
                   5285:     my %returnhash=();
1.731     albertel 5286:     
                   5287:     my $expiretime=600;
                   5288:     if ($env{'request.course.id'} eq $normalid) {
                   5289: 	$expiretime=120;
                   5290:     }
                   5291: 
                   5292:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5293:     if (!$args->{'freshen_cache'}
                   5294: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5295: 	foreach my $key (keys(%env)) {
                   5296: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5297: 	    my ($setting) = $1;
                   5298: 	    $returnhash{$setting} = $env{$key};
                   5299: 	}
                   5300: 	return %returnhash;
                   5301:     }
                   5302: 
1.1118    foxr     5303:     # get the data again
                   5304: 
1.731     albertel 5305:     if (!$args->{'one_time'}) {
                   5306: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5307:     }
1.811     albertel 5308: 
1.34      www      5309:     if ($chome ne 'no_host') {
1.302     albertel 5310:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5311:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5312: 	   my $username = $env{'user.name'}; # Defult username
                   5313: 	   if(defined $args->{'user'}) {
                   5314: 	       $username = $args->{'user'};
                   5315: 	   }
1.129     albertel 5316:            $returnhash{'home'}= $chome;
                   5317: 	   $returnhash{'domain'} = $cdomain;
                   5318: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5319:            if (!defined($returnhash{'type'})) {
                   5320:                $returnhash{'type'} = 'Course';
                   5321:            }
1.130     albertel 5322:            while (my ($name,$value) = each %returnhash) {
1.53      www      5323:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5324:            }
1.270     www      5325:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5326:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5327: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5328:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5329:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5330:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5331:        }
                   5332:     }
1.731     albertel 5333:     if (!$args->{'one_time'}) {
1.949     raeburn  5334: 	&appenv(\%envhash);
1.731     albertel 5335:     }
1.302     albertel 5336:     return %returnhash;
1.461     www      5337: }
                   5338: 
1.1080    raeburn  5339: sub update_released_required {
                   5340:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5341:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5342:         $cid = $env{'request.course.id'};
                   5343:         $cdom = $env{'course.'.$cid.'.domain'};
                   5344:         $cnum = $env{'course.'.$cid.'.num'};
                   5345:         $chome = $env{'course.'.$cid.'.home'};
                   5346:     }
                   5347:     if ($needsrelease) {
                   5348:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5349:         my $needsupdate;
                   5350:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5351:             $needsupdate = 1;
                   5352:         } else {
                   5353:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5354:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5355:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5356:                 $needsupdate = 1;
                   5357:             }
                   5358:         }
                   5359:         if ($needsupdate) {
                   5360:             my %needshash = (
                   5361:                              'internal.releaserequired' => $needsrelease,
                   5362:                             );
                   5363:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5364:             if ($putresult eq 'ok') {
                   5365:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5366:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5367:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5368:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5369:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5370:                 }
                   5371:             }
                   5372:         }
                   5373:     }
                   5374:     return;
                   5375: }
                   5376: 
1.461     www      5377: # -------------------------------------------------See if a user is privileged
                   5378: 
                   5379: sub privileged {
1.1219    raeburn  5380:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5381:     my $now = time;
1.1219    raeburn  5382:     my $roles;
                   5383:     if (ref($possroles) eq 'ARRAY') {
                   5384:         $roles = $possroles; 
                   5385:     } else {
                   5386:         $roles = ['dc','su'];
                   5387:     }
                   5388:     if (ref($possdomains) eq 'ARRAY') {
                   5389:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5390:         foreach my $dom (@{$possdomains}) {
                   5391:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5392:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5393:                 foreach my $role (@{$roles}) {
                   5394:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5395:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5396:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5397:                             return 1 unless (($end && $end < $now) ||
                   5398:                                              ($start && $start > $now));
                   5399:                         }
                   5400:                     }
                   5401:                 }
                   5402:             }
                   5403:         }
                   5404:     } else {
                   5405:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5406:         my $now = time;
1.1170    droeschl 5407: 
1.1275    musolffc 5408:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5409:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  5410:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 5411:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  5412:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5413:             }
1.1219    raeburn  5414:         }
                   5415:     }
                   5416:     return 0;
                   5417: }
1.1170    droeschl 5418: 
1.1219    raeburn  5419: sub privileged_by_domain {
                   5420:     my ($domains,$roles) = @_;
                   5421:     my %privileged = ();
                   5422:     my $cachetime = 60*60*24;
                   5423:     my $now = time;
                   5424:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5425:         return %privileged;
                   5426:     }
                   5427:     foreach my $dom (@{$domains}) {
                   5428:         next if (ref($privileged{$dom}) eq 'HASH');
                   5429:         my $needroles;
                   5430:         foreach my $role (@{$roles}) {
                   5431:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5432:             if (defined($cached)) {
                   5433:                 if (ref($result) eq 'HASH') {
                   5434:                     $privileged{$dom}{$role} = $result;
                   5435:                 }
                   5436:             } else {
                   5437:                 $needroles = 1;
                   5438:             }
                   5439:         }
                   5440:         if ($needroles) {
                   5441:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5442:             $privileged{$dom} = {};
                   5443:             foreach my $server (keys(%dompersonnel)) {
                   5444:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5445:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5446:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5447:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5448:                         next if ($end && $end < $now);
                   5449:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   5450:                             $dompersonnel{$server}{$item};
                   5451:                     }
                   5452:                 }
                   5453:             }
                   5454:             if (ref($privileged{$dom}) eq 'HASH') {
                   5455:                 foreach my $role (@{$roles}) {
                   5456:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5457:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5458:                     } else {
                   5459:                         my %hash = ();
                   5460:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5461:                     }
                   5462:                 }
                   5463:             }
                   5464:         }
                   5465:     }
                   5466:     return %privileged;
1.9       www      5467: }
1.1       albertel 5468: 
1.103     harris41 5469: # -------------------------------------------------------- Get user privileges
1.11      www      5470: 
                   5471: sub rolesinit {
1.1169    droeschl 5472:     my ($domain, $username) = @_;
                   5473:     my %userroles = ('user.login.time' => time);
                   5474:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5475: 
                   5476:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5477:     # also, blocking can be triggered by an activating timer
                   5478:     # it's saved in the user's %env.
                   5479:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5480:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5481:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5482:         %timerintchk, %timerintenv);
                   5483: 
1.1162    raeburn  5484:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5485:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5486:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5487:     }
1.1169    droeschl 5488: 
1.1162    raeburn  5489:     foreach my $key (keys(%timerinterval)) {
                   5490:         my ($cid,$rest) = split(/\0/,$key);
                   5491:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5492:     }
1.1169    droeschl 5493: 
1.11      www      5494:     my %allroles=();
1.1162    raeburn  5495:     my %allgroups=();
1.11      www      5496: 
1.1274    raeburn  5497:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5498:         my $role = $rolesdump{$area};
                   5499:         $area =~ s/\_\w\w$//;
                   5500: 
                   5501:         my ($trole, $tend, $tstart, $group_privs);
                   5502: 
                   5503:         if ($role =~ /^cr/) {
                   5504:         # Custom role, defined by a user 
                   5505:         # e.g., user.role.cr/msu/smith/mynewrole
                   5506:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5507:                 $trole = $1;
                   5508:                 ($tend, $tstart) = split('_', $2);
                   5509:             } else {
                   5510:                 $trole = $role;
                   5511:             }
                   5512:         } elsif ($role =~ m|^gr/|) {
                   5513:         # Role of member in a group, defined within a course/community
                   5514:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5515:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5516:             next if $tstart eq '-1';
                   5517:             ($trole, $group_privs) = split(/\//, $trole);
                   5518:             $group_privs = &unescape($group_privs);
                   5519:         } else {
                   5520:         # Just a normal role, defined in roles.tab
                   5521:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5522:         }
                   5523: 
                   5524:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5525:                  $username);
                   5526:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5527: 
                   5528:         # role expired or not available yet?
                   5529:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5530:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5531: 
                   5532:         next if $area eq '' or $trole eq '';
                   5533: 
                   5534:         my $spec = "$trole.$area";
                   5535:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5536: 
                   5537:         if ($trole =~ /^cr\//) {
                   5538:         # Custom role, defined by a user
                   5539:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5540:         } elsif ($trole eq 'gr') {
                   5541:         # Role of a member in a group, defined within a course/community
                   5542:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5543:             next;
                   5544:         } else {
                   5545:         # Normal role, defined in roles.tab
                   5546:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5547:         }
                   5548: 
                   5549:         my $cid = $tdomain.'_'.$trest;
                   5550:         unless ($firstaccchk{$cid}) {
                   5551:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5552:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5553:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5554:                         $coursetimerstarts{$cid}{$item}; 
                   5555:                 }
                   5556:             }
                   5557:             $firstaccchk{$cid} = 1;
                   5558:         }
                   5559:         unless ($timerintchk{$cid}) {
                   5560:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5561:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5562:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5563:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5564:                 }
1.12      www      5565:             }
1.1169    droeschl 5566:             $timerintchk{$cid} = 1;
1.191     harris41 5567:         }
1.11      www      5568:     }
1.1169    droeschl 5569: 
                   5570:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5571:         \%allroles, \%allgroups);
                   5572:     $env{'user.adv'} = $userroles{'user.adv'};
                   5573: 
1.1162    raeburn  5574:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5575: }
                   5576: 
1.567     raeburn  5577: sub set_arearole {
1.1215    raeburn  5578:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5579:     unless ($nolog) {
1.567     raeburn  5580: # log the associated role with the area
1.1215    raeburn  5581:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5582:     }
1.743     albertel 5583:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5584: }
                   5585: 
                   5586: sub custom_roleprivs {
                   5587:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5588:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  5589:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5590:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5591:         my ($rdummy,$roledef)=
                   5592:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5593:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5594:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5595:             if (defined($syspriv)) {
1.1043    raeburn  5596:                 if ($trest =~ /^$match_community$/) {
                   5597:                     $syspriv =~ s/bre\&S//; 
                   5598:                 }
1.567     raeburn  5599:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5600:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5601:             }
                   5602:             if ($tdomain ne '') {
                   5603:                 if (defined($dompriv)) {
                   5604:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5605:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5606:                 }
                   5607:                 if (($trest ne '') && (defined($coursepriv))) {
                   5608:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5609:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5610:                 }
                   5611:             }
                   5612:         }
                   5613:     }
                   5614: }
                   5615: 
1.678     raeburn  5616: sub group_roleprivs {
                   5617:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5618:     my $access = 1;
                   5619:     my $now = time;
                   5620:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5621:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5622:     if ($access) {
1.811     albertel 5623:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5624:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5625:     }
                   5626: }
1.567     raeburn  5627: 
                   5628: sub standard_roleprivs {
                   5629:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5630:     if (defined($pr{$trole.':s'})) {
                   5631:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5632:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5633:     }
                   5634:     if ($tdomain ne '') {
                   5635:         if (defined($pr{$trole.':d'})) {
                   5636:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5637:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5638:         }
                   5639:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5640:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5641:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5642:         }
                   5643:     }
                   5644: }
                   5645: 
                   5646: sub set_userprivs {
1.1064    raeburn  5647:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5648:     my $author=0;
                   5649:     my $adv=0;
1.678     raeburn  5650:     my %grouproles = ();
                   5651:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5652:         my @groupkeys; 
1.1000    raeburn  5653:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5654:             push(@groupkeys,$role);
                   5655:         }
                   5656:         if (ref($groups_roles) eq 'HASH') {
                   5657:             foreach my $key (keys(%{$groups_roles})) {
                   5658:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5659:                     push(@groupkeys,$key);
                   5660:                 }
                   5661:             }
                   5662:         }
                   5663:         if (@groupkeys > 0) {
                   5664:             foreach my $role (@groupkeys) {
                   5665:                 my ($trole,$area,$sec,$extendedarea);
                   5666:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5667:                     $trole = $1;
                   5668:                     $area = $2;
                   5669:                     $sec = $3;
                   5670:                     $extendedarea = $area.$sec;
                   5671:                     if (exists($$allgroups{$area})) {
                   5672:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5673:                             my $spec = $trole.'.'.$extendedarea;
                   5674:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5675:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5676:                         }
1.678     raeburn  5677:                     }
                   5678:                 }
                   5679:             }
                   5680:         }
                   5681:     }
1.800     albertel 5682:     foreach my $group (keys(%grouproles)) {
                   5683:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5684:     }
1.800     albertel 5685:     foreach my $role (keys(%{$allroles})) {
                   5686:         my %thesepriv;
1.941     raeburn  5687:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5688:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5689:             if ($item ne '') {
                   5690:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5691:                 if ($restrictions eq '') {
                   5692:                     $thesepriv{$privilege}='F';
                   5693:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5694:                     $thesepriv{$privilege}.=$restrictions;
                   5695:                 }
                   5696:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5697:             }
                   5698:         }
                   5699:         my $thesestr='';
1.1104    raeburn  5700:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5701: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5702: 	}
                   5703:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5704:     }
                   5705:     return ($author,$adv);
                   5706: }
                   5707: 
1.994     raeburn  5708: sub role_status {
1.1104    raeburn  5709:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5710:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  5711:         my ($one,$two) = split(m{\./},$rolekey,2);
                   5712:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  5713:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  5714:             $$where = '/'.$two;
1.994     raeburn  5715:             $$trolecode=$$role.'.'.$$where;
                   5716:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5717:             $$tstatus='is';
1.1104    raeburn  5718:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5719:                 $$tstatus='future';
1.1034    raeburn  5720:                 if ($$tstart<$now) {
                   5721:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5722:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5723:                             my (%allroles,%allgroups,$group_privs,
                   5724:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5725:                             my %userroles = (
                   5726:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5727:                             );
1.1064    raeburn  5728:                             @rolecodes = ('cm'); 
1.1002    raeburn  5729:                             my $spec=$$role.'.'.$$where;
                   5730:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5731:                             if ($$role =~ /^cr\//) {
                   5732:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5733:                                 push(@rolecodes,'cr');
1.1002    raeburn  5734:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5735:                                 push(@rolecodes,$$role);
1.1002    raeburn  5736:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5737:                                                     $env{'user.name'});
1.1064    raeburn  5738:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5739:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5740:                                 $group_privs = &unescape($group_privs);
                   5741:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5742:                                 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  5743:                                 &get_groups_roles($tdomain,$trest,
                   5744:                                                   \%course_roles,\@rolecodes,
                   5745:                                                   \%groups_roles);
1.1002    raeburn  5746:                             } else {
1.1064    raeburn  5747:                                 push(@rolecodes,$$role);
1.1002    raeburn  5748:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5749:                             }
1.1064    raeburn  5750:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5751:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5752:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5753:                         }
                   5754:                     }
1.1034    raeburn  5755:                     $$tstatus = 'is';
1.1002    raeburn  5756:                 }
1.994     raeburn  5757:             }
                   5758:             if ($$tend) {
1.1104    raeburn  5759:                 if ($$tend<$update) {
1.994     raeburn  5760:                     $$tstatus='expired';
                   5761:                 } elsif ($$tend<$now) {
                   5762:                     $$tstatus='will_not';
                   5763:                 }
                   5764:             }
                   5765:         }
                   5766:     }
                   5767: }
                   5768: 
1.1104    raeburn  5769: sub get_groups_roles {
                   5770:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5771:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5772:                   (ref($rolecodes) eq 'ARRAY') && 
                   5773:                   (ref($groups_roles) eq 'HASH')); 
                   5774:     if (keys(%{$cdom_courseroles}) > 0) {
                   5775:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5776:         if ($cdom ne '' && $cnum ne '') {
                   5777:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5778:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5779:                     my $crsrole = $1;
                   5780:                     my $crssec = $2;
                   5781:                     if ($crsrole =~ /^cr/) {
                   5782:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5783:                             push(@{$rolecodes},'cr');
                   5784:                         }
                   5785:                     } else {
                   5786:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5787:                             push(@{$rolecodes},$crsrole);
                   5788:                         }
                   5789:                     }
                   5790:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5791:                     if ($crssec ne '') {
                   5792:                         $rolekey .= "/$crssec";
                   5793:                     }
                   5794:                     $rolekey .= './';
                   5795:                     $groups_roles->{$rolekey} = $rolecodes;
                   5796:                 }
                   5797:             }
                   5798:         }
                   5799:     }
                   5800:     return;
                   5801: }
                   5802: 
                   5803: sub delete_env_groupprivs {
                   5804:     my ($where,$courseroles,$possroles) = @_;
                   5805:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5806:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5807:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5808:         %{$courseroles->{$udom}} =
                   5809:             &get_my_roles('','','userroles',['active'],
                   5810:                           $possroles,[$udom],1);
                   5811:     }
                   5812:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5813:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5814:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5815:             my $area = '/'.$cdom.'/'.$cnum;
                   5816:             my $privkey = "user.priv.$crsrole.$area";
                   5817:             if ($crssec ne '') {
                   5818:                 $privkey .= '/'.$crssec;
                   5819:             }
                   5820:             $privkey .= ".$area/$group";
                   5821:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5822:         }
                   5823:     }
                   5824:     return;
                   5825: }
                   5826: 
1.994     raeburn  5827: sub check_adhoc_privs {
1.1104    raeburn  5828:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5829:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185    raeburn  5830:     my $setprivs;
1.994     raeburn  5831:     if ($env{$cckey}) {
                   5832:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5833:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5834:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5835:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5836:             $setprivs = 1;
1.994     raeburn  5837:         }
                   5838:     } else {
1.1088    raeburn  5839:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5840:         $setprivs = 1;
1.994     raeburn  5841:     }
1.1185    raeburn  5842:     return $setprivs;
1.994     raeburn  5843: }
                   5844: 
                   5845: sub set_adhoc_privileges {
                   5846: # role can be cc or ca
1.1088    raeburn  5847:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5848:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5849:     my $spec = $role.'.'.$area;
                   5850:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  5851:                                   $env{'user.name'},1);
1.994     raeburn  5852:     my %ccrole = ();
                   5853:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5854:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5855:     &appenv(\%userroles,[$role,'cm']);
                   5856:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5857:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5858:         &appenv( {'request.role'        => $spec,
                   5859:                   'request.role.domain' => $dcdom,
                   5860:                   'request.course.sec'  => ''
                   5861:                  }
                   5862:                );
                   5863:         my $tadv=0;
                   5864:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5865:         &appenv({'request.role.adv'    => $tadv});
                   5866:     }
1.994     raeburn  5867: }
                   5868: 
1.12      www      5869: # --------------------------------------------------------------- get interface
                   5870: 
                   5871: sub get {
1.131     albertel 5872:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5873:    my $items='';
1.800     albertel 5874:    foreach my $item (@$storearr) {
                   5875:        $items.=&escape($item).'&';
1.191     harris41 5876:    }
1.12      www      5877:    $items=~s/\&$//;
1.620     albertel 5878:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5879:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5880:    my $uhome=&homeserver($uname,$udomain);
                   5881: 
1.133     albertel 5882:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5883:    my @pairs=split(/\&/,$rep);
1.273     albertel 5884:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5885:      return @pairs;
                   5886:    }
1.15      www      5887:    my %returnhash=();
1.42      www      5888:    my $i=0;
1.800     albertel 5889:    foreach my $item (@$storearr) {
                   5890:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5891:       $i++;
1.191     harris41 5892:    }
1.15      www      5893:    return %returnhash;
1.27      www      5894: }
                   5895: 
                   5896: # --------------------------------------------------------------- del interface
                   5897: 
                   5898: sub del {
1.133     albertel 5899:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5900:    my $items='';
1.800     albertel 5901:    foreach my $item (@$storearr) {
                   5902:        $items.=&escape($item).'&';
1.191     harris41 5903:    }
1.984     neumanie 5904: 
1.27      www      5905:    $items=~s/\&$//;
1.620     albertel 5906:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5907:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5908:    my $uhome=&homeserver($uname,$udomain);
                   5909:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5910: }
                   5911: 
                   5912: # -------------------------------------------------------------- dump interface
                   5913: 
1.1180    droeschl 5914: sub unserialize {
                   5915:     my ($rep, $escapedkeys) = @_;
                   5916: 
                   5917:     return {} if $rep =~ /^error/;
                   5918: 
                   5919:     my %returnhash=();
1.1252    raeburn  5920: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 5921: 	    my ($key, $value) = split(/=/, $item, 2);
                   5922: 	    $key = unescape($key) unless $escapedkeys;
                   5923: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  5924: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 5925: 	}
                   5926:     #return %returnhash;
                   5927:     return \%returnhash;
                   5928: }        
                   5929: 
                   5930: # see Lond::dump_with_regexp
                   5931: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5932: sub dump {
1.1180    droeschl 5933:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5934:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5935:     if (!$uname) { $uname=$env{'user.name'}; }
                   5936:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5937: 
1.1266    raeburn  5938:     if ($regexp) {
                   5939:         $regexp=&escape($regexp);
                   5940:     } else {
                   5941:         $regexp='.';
                   5942:     }
1.1180    droeschl 5943:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   5944:         # user is hosted on this machine
1.1266    raeburn  5945:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  5946:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 5947:         return %{unserialize($reply, $escapedkeys)};
                   5948:     }
1.1166    raeburn  5949:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5950:     my @pairs=split(/\&/,$rep);
                   5951:     my %returnhash=();
1.1098    foxr     5952:     if (!($rep =~ /^error/ )) {
                   5953: 	foreach my $item (@pairs) {
                   5954: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 5955:         $key = unescape($key) unless $escapedkeys;
                   5956:         #$key = &unescape($key);
1.1098    foxr     5957: 	    next if ($key =~ /^error: 2 /);
                   5958: 	    $returnhash{$key}=&thaw_unescape($value);
                   5959: 	}
1.755     albertel 5960:     }
                   5961:     return %returnhash;
1.407     www      5962: }
                   5963: 
1.1098    foxr     5964: 
1.717     albertel 5965: # --------------------------------------------------------- dumpstore interface
                   5966: 
                   5967: sub dumpstore {
                   5968:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 5969:    # same as dump but keys must be escaped. They may contain colon separated
                   5970:    # lists of values that may themself contain colons (e.g. symbs).
                   5971:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5972: }
                   5973: 
1.407     www      5974: # -------------------------------------------------------------- keys interface
                   5975: 
                   5976: sub getkeys {
                   5977:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5978:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5979:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5980:    my $uhome=&homeserver($uname,$udomain);
                   5981:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5982:    my @keyarray=();
1.800     albertel 5983:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5984:       next if ($key =~ /^error: 2 /);
1.800     albertel 5985:       push(@keyarray,&unescape($key));
1.407     www      5986:    }
                   5987:    return @keyarray;
1.318     matthew  5988: }
                   5989: 
1.319     matthew  5990: # --------------------------------------------------------------- currentdump
                   5991: sub currentdump {
1.328     matthew  5992:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5993:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5994:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5995:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5996:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 5997:    my $rep;
                   5998: 
                   5999:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6000:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   6001:                    $courseid)));
                   6002:    } else {
                   6003:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6004:    }
                   6005: 
1.318     matthew  6006:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6007:    #
1.318     matthew  6008:    my %returnhash=();
1.319     matthew  6009:    #
                   6010:    if ($rep eq "unknown_cmd") { 
                   6011:        # an old lond will not know currentdump
                   6012:        # Do a dump and make it look like a currentdump
1.822     albertel 6013:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6014:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6015:        my %hash = @tmp;
                   6016:        @tmp=();
1.424     matthew  6017:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6018:    } else {
                   6019:        my @pairs=split(/\&/,$rep);
1.800     albertel 6020:        foreach my $pair (@pairs) {
                   6021:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6022:            my ($symb,$param) = split(/:/,$key);
                   6023:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6024:                                                         &thaw_unescape($value);
1.319     matthew  6025:        }
1.191     harris41 6026:    }
1.12      www      6027:    return %returnhash;
1.424     matthew  6028: }
                   6029: 
                   6030: sub convert_dump_to_currentdump{
                   6031:     my %hash = %{shift()};
                   6032:     my %returnhash;
                   6033:     # Code ripped from lond, essentially.  The only difference
                   6034:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6035:     # we might run in to problems with parameter names =~ /^v\./
                   6036:     while (my ($key,$value) = each(%hash)) {
                   6037:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6038: 	$symb  = &unescape($symb);
                   6039: 	$param = &unescape($param);
1.424     matthew  6040:         next if ($v eq 'version' || $symb eq 'keys');
                   6041:         next if (exists($returnhash{$symb}) &&
                   6042:                  exists($returnhash{$symb}->{$param}) &&
                   6043:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6044:         $returnhash{$symb}->{$param}=$value;
                   6045:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6046:     }
                   6047:     #
                   6048:     # Remove all of the keys in the hashes which keep track of
                   6049:     # the version of the parameter.
                   6050:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6051:         # use a foreach because we are going to delete from the hash.
                   6052:         foreach my $key (keys(%$param_hash)) {
                   6053:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6054:         }
                   6055:     }
                   6056:     return \%returnhash;
1.12      www      6057: }
                   6058: 
1.627     albertel 6059: # ------------------------------------------------------ critical inc interface
                   6060: 
                   6061: sub cinc {
                   6062:     return &inc(@_,'critical');
                   6063: }
                   6064: 
1.449     matthew  6065: # --------------------------------------------------------------- inc interface
                   6066: 
                   6067: sub inc {
1.627     albertel 6068:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6069:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6070:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6071:     my $uhome=&homeserver($uname,$udomain);
                   6072:     my $items='';
                   6073:     if (! ref($store)) {
                   6074:         # got a single value, so use that instead
                   6075:         $items = &escape($store).'=&';
                   6076:     } elsif (ref($store) eq 'SCALAR') {
                   6077:         $items = &escape($$store).'=&';        
                   6078:     } elsif (ref($store) eq 'ARRAY') {
                   6079:         $items = join('=&',map {&escape($_);} @{$store});
                   6080:     } elsif (ref($store) eq 'HASH') {
                   6081:         while (my($key,$value) = each(%{$store})) {
                   6082:             $items.= &escape($key).'='.&escape($value).'&';
                   6083:         }
                   6084:     }
                   6085:     $items=~s/\&$//;
1.627     albertel 6086:     if ($critical) {
                   6087: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6088:     } else {
                   6089: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6090:     }
1.449     matthew  6091: }
                   6092: 
1.12      www      6093: # --------------------------------------------------------------- put interface
                   6094: 
                   6095: sub put {
1.134     albertel 6096:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6097:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6098:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6099:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6100:    my $items='';
1.800     albertel 6101:    foreach my $item (keys(%$storehash)) {
                   6102:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6103:    }
1.12      www      6104:    $items=~s/\&$//;
1.134     albertel 6105:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6106: }
                   6107: 
1.631     albertel 6108: # ------------------------------------------------------------ newput interface
                   6109: 
                   6110: sub newput {
                   6111:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6112:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6113:    if (!$uname) { $uname=$env{'user.name'}; }
                   6114:    my $uhome=&homeserver($uname,$udomain);
                   6115:    my $items='';
                   6116:    foreach my $key (keys(%$storehash)) {
                   6117:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6118:    }
                   6119:    $items=~s/\&$//;
                   6120:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6121: }
                   6122: 
                   6123: # ---------------------------------------------------------  putstore interface
                   6124: 
1.524     raeburn  6125: sub putstore {
1.1269    raeburn  6126:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6127:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6128:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6129:    my $uhome=&homeserver($uname,$udomain);
                   6130:    my $items='';
1.715     albertel 6131:    foreach my $key (keys(%$storehash)) {
                   6132:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6133:    }
1.715     albertel 6134:    $items=~s/\&$//;
1.716     albertel 6135:    my $esc_symb=&escape($symb);
                   6136:    my $esc_v=&escape($version);
1.715     albertel 6137:    my $reply =
1.716     albertel 6138:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6139: 	      $uhome);
1.1269    raeburn  6140:    if (($tolog) && ($reply eq 'ok')) {
                   6141:        my $namevalue='';
                   6142:        foreach my $key (keys(%{$storehash})) {
                   6143:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6144:        }
                   6145:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6146:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6147:                      '&version='.$esc_v.
                   6148:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6149:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6150:    }
1.715     albertel 6151:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6152:        # gfall back to way things use to be done
1.715     albertel 6153:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6154: 			    $uname);
1.524     raeburn  6155:    }
1.715     albertel 6156:    return $reply;
                   6157: }
                   6158: 
                   6159: sub old_putstore {
1.716     albertel 6160:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6161:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6162:     if (!$uname) { $uname=$env{'user.name'}; }
                   6163:     my $uhome=&homeserver($uname,$udomain);
                   6164:     my %newstorehash;
1.800     albertel 6165:     foreach my $item (keys(%$storehash)) {
                   6166: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6167: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6168:     }
                   6169:     my $items='';
                   6170:     my %allitems = ();
1.800     albertel 6171:     foreach my $item (keys(%newstorehash)) {
                   6172: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6173: 	    my $key = $1.':keys:'.$2;
                   6174: 	    $allitems{$key} .= $3.':';
                   6175: 	}
1.800     albertel 6176: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6177:     }
1.800     albertel 6178:     foreach my $item (keys(%allitems)) {
                   6179: 	$allitems{$item} =~ s/\:$//;
                   6180: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6181:     }
                   6182:     $items=~s/\&$//;
                   6183:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6184: }
                   6185: 
1.47      www      6186: # ------------------------------------------------------ critical put interface
                   6187: 
                   6188: sub cput {
1.134     albertel 6189:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6190:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6191:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6192:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6193:    my $items='';
1.800     albertel 6194:    foreach my $item (keys(%$storehash)) {
                   6195:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6196:    }
1.47      www      6197:    $items=~s/\&$//;
1.134     albertel 6198:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6199: }
                   6200: 
                   6201: # -------------------------------------------------------------- eget interface
                   6202: 
                   6203: sub eget {
1.133     albertel 6204:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6205:    my $items='';
1.800     albertel 6206:    foreach my $item (@$storearr) {
                   6207:        $items.=&escape($item).'&';
1.191     harris41 6208:    }
1.12      www      6209:    $items=~s/\&$//;
1.620     albertel 6210:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6211:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6212:    my $uhome=&homeserver($uname,$udomain);
                   6213:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6214:    my @pairs=split(/\&/,$rep);
                   6215:    my %returnhash=();
1.42      www      6216:    my $i=0;
1.800     albertel 6217:    foreach my $item (@$storearr) {
                   6218:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6219:       $i++;
1.191     harris41 6220:    }
1.12      www      6221:    return %returnhash;
                   6222: }
                   6223: 
1.667     albertel 6224: # ------------------------------------------------------------ tmpput interface
                   6225: sub tmpput {
1.802     raeburn  6226:     my ($storehash,$server,$context)=@_;
1.667     albertel 6227:     my $items='';
1.800     albertel 6228:     foreach my $item (keys(%$storehash)) {
                   6229: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6230:     }
                   6231:     $items=~s/\&$//;
1.802     raeburn  6232:     if (defined($context)) {
                   6233:         $items .= ':'.&escape($context);
                   6234:     }
1.667     albertel 6235:     return &reply("tmpput:$items",$server);
                   6236: }
                   6237: 
                   6238: # ------------------------------------------------------------ tmpget interface
                   6239: sub tmpget {
1.688     albertel 6240:     my ($token,$server)=@_;
                   6241:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6242:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6243:     my %returnhash;
                   6244:     foreach my $item (split(/\&/,$rep)) {
                   6245: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  6246:         next if ($key =~ /^error: 2 /);
1.667     albertel 6247: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6248:     }
                   6249:     return %returnhash;
                   6250: }
                   6251: 
1.1113    raeburn  6252: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6253: sub tmpdel {
                   6254:     my ($token,$server)=@_;
                   6255:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6256:     return &reply("tmpdel:$token",$server);
                   6257: }
                   6258: 
1.1198    raeburn  6259: # ------------------------------------------------------------ get_timebased_id 
                   6260: 
                   6261: sub get_timebased_id {
                   6262:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6263:         $maxtries) = @_;
                   6264:     my ($newid,$error,$dellock);
                   6265:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   6266:         return ('','ok','invalid call to get suffix');
                   6267:     }
                   6268: 
                   6269: # set defaults for any optional args for which values were not supplied
                   6270:     if ($who eq '') {
                   6271:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6272:     }
                   6273:     if (!$locktries) {
                   6274:         $locktries = 3;
                   6275:     }
                   6276:     if (!$maxtries) {
                   6277:         $maxtries = 10;
                   6278:     }
                   6279:     
                   6280:     if (($cdom eq '') || ($cnum eq '')) {
                   6281:         if ($env{'request.course.id'}) {
                   6282:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6283:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6284:         }
                   6285:         if (($cdom eq '') || ($cnum eq '')) {
                   6286:             return ('','ok','call to get suffix not in course context');
                   6287:         }
                   6288:     }
                   6289: 
                   6290: # construct locking item
                   6291:     my $lockhash = {
                   6292:                       $prefix."\0".'locked_'.$keyid => $who,
                   6293:                    };
                   6294:     my $tries = 0;
                   6295: 
                   6296: # attempt to get lock on nohist_$namespace file
                   6297:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6298:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6299:         $tries ++;
                   6300:         sleep 1;
                   6301:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6302:     }
                   6303: 
                   6304: # attempt to get unique identifier, based on current timestamp
                   6305:     if ($gotlock eq 'ok') {
                   6306:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6307:         my $id = time;
                   6308:         $newid = $id;
1.1268    raeburn  6309:         if ($idtype eq 'addcode') {
                   6310:             $newid .= &sixnum_code();
                   6311:         }
1.1198    raeburn  6312:         my $idtries = 0;
                   6313:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6314:             if ($idtype eq 'concat') {
                   6315:                 $newid = $id.$idtries;
1.1268    raeburn  6316:             } elsif ($idtype eq 'addcode') {
                   6317:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  6318:             } else {
                   6319:                 $newid ++;
                   6320:             }
                   6321:             $idtries ++;
                   6322:         }
                   6323:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6324:             my %new_item =  (
                   6325:                               $prefix."\0".$newid => $who,
                   6326:                             );
                   6327:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6328:                                                  $cdom,$cnum);
                   6329:             if ($putresult ne 'ok') {
                   6330:                 undef($newid);
                   6331:                 $error = 'error saving new item: '.$putresult;
                   6332:             }
                   6333:         } else {
1.1268    raeburn  6334:              undef($newid);
1.1198    raeburn  6335:              $error = ('error: no unique suffix available for the new item ');
                   6336:         }
                   6337: #  remove lock
                   6338:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6339:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6340:     } else {
                   6341:         $error = "error: could not obtain lockfile\n";
                   6342:         $dellock = 'ok';
1.1276    raeburn  6343:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6344:             $dellock = 'nolock';
                   6345:         }
1.1198    raeburn  6346:     }
                   6347:     return ($newid,$dellock,$error);
                   6348: }
                   6349: 
1.1268    raeburn  6350: sub sixnum_code {
                   6351:     my $code;
                   6352:     for (0..6) {
                   6353:         $code .= int( rand(9) );
                   6354:     }
                   6355:     return $code;
                   6356: }
                   6357: 
1.765     albertel 6358: # -------------------------------------------------- portfolio access checking
                   6359: 
                   6360: sub portfolio_access {
1.1270    raeburn  6361:     my ($requrl,$clientip) = @_;
1.765     albertel 6362:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  6363:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6364:     if ($result) {
                   6365:         my %setters;
                   6366:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6367:             my ($startblock,$endblock) =
                   6368:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6369:             if ($startblock && $endblock) {
                   6370:                 return 'B';
                   6371:             }
                   6372:         } else {
                   6373:             my ($startblock,$endblock) =
                   6374:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6375:             if ($startblock && $endblock) {
                   6376:                 return 'B';
                   6377:             }
                   6378:         }
                   6379:     }
1.765     albertel 6380:     if ($result eq 'ok') {
1.766     albertel 6381:        return 'F';
1.765     albertel 6382:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6383:        return 'A';
1.765     albertel 6384:     }
1.766     albertel 6385:     return '';
1.765     albertel 6386: }
                   6387: 
                   6388: sub get_portfolio_access {
1.1270    raeburn  6389:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 6390: 
                   6391:     if (!ref($access_hash)) {
                   6392: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6393: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6394: 						   $file_name);
                   6395: 	$access_hash = $access_controls{$file_name};
                   6396:     }
                   6397: 
1.1270    raeburn  6398:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 6399:     my $now = time;
                   6400:     if (ref($access_hash) eq 'HASH') {
                   6401:         foreach my $key (keys(%{$access_hash})) {
                   6402:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6403:             if ($start > $now) {
                   6404:                 next;
                   6405:             }
                   6406:             if ($end && $end<$now) {
                   6407:                 next;
                   6408:             }
                   6409:             if ($scope eq 'public') {
                   6410:                 $public = $key;
                   6411:                 last;
                   6412:             } elsif ($scope eq 'guest') {
                   6413:                 $guest = $key;
                   6414:             } elsif ($scope eq 'domains') {
                   6415:                 push(@domains,$key);
                   6416:             } elsif ($scope eq 'users') {
                   6417:                 push(@users,$key);
                   6418:             } elsif ($scope eq 'course') {
                   6419:                 push(@courses,$key);
                   6420:             } elsif ($scope eq 'group') {
                   6421:                 push(@groups,$key);
1.1270    raeburn  6422:             } elsif ($scope eq 'ip') {
                   6423:                 push(@ips,$key);
1.765     albertel 6424:             }
                   6425:         }
                   6426:         if ($public) {
                   6427:             return 'ok';
1.1270    raeburn  6428:         } elsif (@ips > 0) {
                   6429:             my $allowed;
                   6430:             foreach my $ipkey (@ips) {
                   6431:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   6432:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   6433:                         $allowed = 1;
                   6434:                         last; 
                   6435:                     }
                   6436:                 }
                   6437:             }
                   6438:             if ($allowed) {
                   6439:                 return 'ok';
                   6440:             }
1.765     albertel 6441:         }
                   6442:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6443:             if ($guest) {
                   6444:                 return $guest;
                   6445:             }
                   6446:         } else {
                   6447:             if (@domains > 0) {
                   6448:                 foreach my $domkey (@domains) {
                   6449:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6450:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6451:                             return 'ok';
                   6452:                         }
                   6453:                     }
                   6454:                 }
                   6455:             }
                   6456:             if (@users > 0) {
                   6457:                 foreach my $userkey (@users) {
1.865     raeburn  6458:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6459:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6460:                             if (ref($item) eq 'HASH') {
                   6461:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6462:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6463:                                     return 'ok';
                   6464:                                 }
                   6465:                             }
                   6466:                         }
                   6467:                     } 
1.765     albertel 6468:                 }
                   6469:             }
                   6470:             my %roleshash;
                   6471:             my @courses_and_groups = @courses;
                   6472:             push(@courses_and_groups,@groups); 
                   6473:             if (@courses_and_groups > 0) {
                   6474:                 my (%allgroups,%allroles); 
                   6475:                 my ($start,$end,$role,$sec,$group);
                   6476:                 foreach my $envkey (%env) {
1.1060    raeburn  6477:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6478:                         my $cid = $2.'_'.$3; 
                   6479:                         if ($1 eq 'gr') {
                   6480:                             $group = $4;
                   6481:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6482:                         } else {
                   6483:                             if ($4 eq '') {
                   6484:                                 $sec = 'none';
                   6485:                             } else {
                   6486:                                 $sec = $4;
                   6487:                             }
                   6488:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6489:                         }
1.811     albertel 6490:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6491:                         my $cid = $2.'_'.$3;
                   6492:                         if ($4 eq '') {
                   6493:                             $sec = 'none';
                   6494:                         } else {
                   6495:                             $sec = $4;
                   6496:                         }
                   6497:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6498:                     }
                   6499:                 }
                   6500:                 if (keys(%allroles) == 0) {
                   6501:                     return;
                   6502:                 }
                   6503:                 foreach my $key (@courses_and_groups) {
                   6504:                     my %content = %{$$access_hash{$key}};
                   6505:                     my $cnum = $content{'number'};
                   6506:                     my $cdom = $content{'domain'};
                   6507:                     my $cid = $cdom.'_'.$cnum;
                   6508:                     if (!exists($allroles{$cid})) {
                   6509:                         next;
                   6510:                     }    
                   6511:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6512:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6513:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6514:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6515:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6516:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6517:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6518:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6519:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6520:                                         if (grep/^all$/,@sections) {
                   6521:                                             return 'ok';
                   6522:                                         } else {
                   6523:                                             if (grep/^$sec$/,@sections) {
                   6524:                                                 return 'ok';
                   6525:                                             }
                   6526:                                         }
                   6527:                                     }
                   6528:                                 }
                   6529:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6530:                                     if (grep/^none$/,@groups) {
                   6531:                                         return 'ok';
                   6532:                                     }
                   6533:                                 } else {
                   6534:                                     if (grep/^all$/,@groups) {
                   6535:                                         return 'ok';
                   6536:                                     } 
                   6537:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6538:                                         if (grep/^$group$/,@groups) {
                   6539:                                             return 'ok';
                   6540:                                         }
                   6541:                                     }
                   6542:                                 } 
                   6543:                             }
                   6544:                         }
                   6545:                     }
                   6546:                 }
                   6547:             }
                   6548:             if ($guest) {
                   6549:                 return $guest;
                   6550:             }
                   6551:         }
                   6552:     }
                   6553:     return;
                   6554: }
                   6555: 
                   6556: sub course_group_datechecker {
                   6557:     my ($dates,$now,$status) = @_;
                   6558:     my ($start,$end) = split(/\./,$dates);
                   6559:     if (!$start && !$end) {
                   6560:         return 'ok';
                   6561:     }
                   6562:     if (grep/^active$/,@{$status}) {
                   6563:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6564:             return 'ok';
                   6565:         }
                   6566:     }
                   6567:     if (grep/^previous$/,@{$status}) {
                   6568:         if ($end > $now ) {
                   6569:             return 'ok';
                   6570:         }
                   6571:     }
                   6572:     if (grep/^future$/,@{$status}) {
                   6573:         if ($start > $now) {
                   6574:             return 'ok';
                   6575:         }
                   6576:     }
                   6577:     return; 
                   6578: }
                   6579: 
                   6580: sub parse_portfolio_url {
                   6581:     my ($url) = @_;
                   6582: 
                   6583:     my ($type,$udom,$unum,$group,$file_name);
                   6584:     
1.823     albertel 6585:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6586: 	$type = 1;
                   6587:         $udom = $1;
                   6588:         $unum = $2;
                   6589:         $file_name = $3;
1.823     albertel 6590:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6591: 	$type = 2;
                   6592:         $udom = $1;
                   6593:         $unum = $2;
                   6594:         $group = $3;
                   6595:         $file_name = $3.'/'.$4;
                   6596:     }
                   6597:     if (wantarray) {
                   6598: 	return ($type,$udom,$unum,$file_name,$group);
                   6599:     }
                   6600:     return $type;
                   6601: }
                   6602: 
                   6603: sub is_portfolio_url {
                   6604:     my ($url) = @_;
                   6605:     return scalar(&parse_portfolio_url($url));
                   6606: }
                   6607: 
1.798     raeburn  6608: sub is_portfolio_file {
                   6609:     my ($file) = @_;
1.820     raeburn  6610:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6611:         return 1;
                   6612:     }
                   6613:     return;
                   6614: }
                   6615: 
1.976     raeburn  6616: sub usertools_access {
1.1084    raeburn  6617:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6618:     my ($access,%tools);
                   6619:     if ($context eq '') {
                   6620:         $context = 'tools';
                   6621:     }
                   6622:     if ($context eq 'requestcourses') {
                   6623:         %tools = (
                   6624:                       official   => 1,
                   6625:                       unofficial => 1,
1.1006    raeburn  6626:                       community  => 1,
1.1246    raeburn  6627:                       textbook   => 1,
1.1305    raeburn  6628:                       placement  => 1,
1.985     raeburn  6629:                  );
1.1183    raeburn  6630:     } elsif ($context eq 'requestauthor') {
                   6631:         %tools = (
                   6632:                       requestauthor => 1,
                   6633:                  );
1.985     raeburn  6634:     } else {
                   6635:         %tools = (
                   6636:                       aboutme   => 1,
                   6637:                       blog      => 1,
1.1177    raeburn  6638:                       webdav    => 1,
1.985     raeburn  6639:                       portfolio => 1,
                   6640:                  );
                   6641:     }
1.976     raeburn  6642:     return if (!defined($tools{$tool}));
                   6643: 
1.1242    raeburn  6644:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6645:         $udom = $env{'user.domain'};
                   6646:         $uname = $env{'user.name'};
                   6647:     }
                   6648: 
1.978     raeburn  6649:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6650:         if ($action ne 'reload') {
1.985     raeburn  6651:             if ($context eq 'requestcourses') {
                   6652:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  6653:             } elsif ($context eq 'requestauthor') {
                   6654:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6655:             } else {
                   6656:                 return $env{'environment.availabletools.'.$tool};
                   6657:             }
                   6658:         }
1.976     raeburn  6659:     }
                   6660: 
1.1183    raeburn  6661:     my ($toolstatus,$inststatus,$envkey);
                   6662:     if ($context eq 'requestauthor') {
                   6663:         $envkey = $context; 
                   6664:     } else {
                   6665:         $envkey = $context.'.'.$tool;
                   6666:     }
1.976     raeburn  6667: 
1.985     raeburn  6668:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6669:          ($action ne 'reload')) {
1.1183    raeburn  6670:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6671:         $inststatus = $env{'environment.inststatus'};
                   6672:     } else {
1.1084    raeburn  6673:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  6674:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6675:             $inststatus = $userenvref->{'inststatus'};
                   6676:         } else {
1.1183    raeburn  6677:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6678:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6679:             $inststatus = $userenv{'inststatus'};
                   6680:         }
1.976     raeburn  6681:     }
                   6682: 
                   6683:     if ($toolstatus ne '') {
                   6684:         if ($toolstatus) {
                   6685:             $access = 1;
                   6686:         } else {
                   6687:             $access = 0;
                   6688:         }
                   6689:         return $access;
                   6690:     }
                   6691: 
1.1084    raeburn  6692:     my ($is_adv,%domdef);
                   6693:     if (ref($is_advref) eq 'HASH') {
                   6694:         $is_adv = $is_advref->{'is_adv'};
                   6695:     } else {
                   6696:         $is_adv = &is_advanced_user($udom,$uname);
                   6697:     }
                   6698:     if (ref($domdefref) eq 'HASH') {
                   6699:         %domdef = %{$domdefref};
                   6700:     } else {
                   6701:         %domdef = &get_domain_defaults($udom);
                   6702:     }
1.976     raeburn  6703:     if (ref($domdef{$tool}) eq 'HASH') {
                   6704:         if ($is_adv) {
                   6705:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6706:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6707:                     $access = 1;
                   6708:                 } else {
                   6709:                     $access = 0;
                   6710:                 }
                   6711:                 return $access;
                   6712:             }
                   6713:         }
                   6714:         if ($inststatus ne '') {
                   6715:             my ($hasaccess,$hasnoaccess);
                   6716:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6717:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6718:                     if ($domdef{$tool}{$affiliation}) {
                   6719:                         $hasaccess = 1;
                   6720:                     } else {
                   6721:                         $hasnoaccess = 1;
                   6722:                     }
                   6723:                 }
                   6724:             }
                   6725:             if ($hasaccess || $hasnoaccess) {
                   6726:                 if ($hasaccess) {
                   6727:                     $access = 1;
                   6728:                 } elsif ($hasnoaccess) {
                   6729:                     $access = 0; 
                   6730:                 }
                   6731:                 return $access;
                   6732:             }
                   6733:         } else {
                   6734:             if ($domdef{$tool}{'default'} ne '') {
                   6735:                 if ($domdef{$tool}{'default'}) {
                   6736:                     $access = 1;
                   6737:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6738:                     $access = 0;
                   6739:                 }
                   6740:                 return $access;
                   6741:             }
                   6742:         }
                   6743:     } else {
1.1177    raeburn  6744:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6745:             $access = 1;
                   6746:         } else {
                   6747:             $access = 0;
                   6748:         }
1.976     raeburn  6749:         return $access;
                   6750:     }
                   6751: }
                   6752: 
1.1050    raeburn  6753: sub is_course_owner {
                   6754:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6755:     if (($udom eq '') || ($uname eq '')) {
                   6756:         $udom = $env{'user.domain'};
                   6757:         $uname = $env{'user.name'};
                   6758:     }
                   6759:     unless (($udom eq '') || ($uname eq '')) {
                   6760:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6761:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6762:                 return 1;
                   6763:             } else {
                   6764:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6765:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6766:                     return 1;
                   6767:                 }
                   6768:             }
                   6769:         }
                   6770:     }
                   6771:     return;
                   6772: }
                   6773: 
1.976     raeburn  6774: sub is_advanced_user {
                   6775:     my ($udom,$uname) = @_;
1.1085    raeburn  6776:     if ($udom ne '' && $uname ne '') {
                   6777:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6778:             if (wantarray) {
                   6779:                 return ($env{'user.adv'},$env{'user.author'});
                   6780:             } else {
                   6781:                 return $env{'user.adv'};
                   6782:             }
1.1085    raeburn  6783:         }
                   6784:     }
1.976     raeburn  6785:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6786:     my %allroles;
1.1128    raeburn  6787:     my ($is_adv,$is_author);
1.976     raeburn  6788:     foreach my $role (keys(%roleshash)) {
                   6789:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6790:         my $area = '/'.$tdomain.'/'.$trest;
                   6791:         if ($sec ne '') {
                   6792:             $area .= '/'.$sec;
                   6793:         }
                   6794:         if (($area ne '') && ($trole ne '')) {
                   6795:             my $spec=$trole.'.'.$area;
                   6796:             if ($trole =~ /^cr\//) {
                   6797:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6798:             } elsif ($trole ne 'gr') {
                   6799:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6800:             }
1.1128    raeburn  6801:             if ($trole eq 'au') {
                   6802:                 $is_author = 1;
                   6803:             }
1.976     raeburn  6804:         }
                   6805:     }
                   6806:     foreach my $role (keys(%allroles)) {
                   6807:         last if ($is_adv);
                   6808:         foreach my $item (split(/:/,$allroles{$role})) {
                   6809:             if ($item ne '') {
                   6810:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6811:                 if ($privilege eq 'adv') {
                   6812:                     $is_adv = 1;
                   6813:                     last;
                   6814:                 }
                   6815:             }
                   6816:         }
                   6817:     }
1.1128    raeburn  6818:     if (wantarray) {
                   6819:         return ($is_adv,$is_author);
                   6820:     }
1.976     raeburn  6821:     return $is_adv;
                   6822: }
1.798     raeburn  6823: 
1.1035    raeburn  6824: sub check_can_request {
1.1036    raeburn  6825:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6826:     my $canreq = 0;
                   6827:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6828:     my @options = ('approval','validate','autolimit');
                   6829:     my $optregex = join('|',@options);
                   6830:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6831:         foreach my $type (@{$types}) {
                   6832:             if (&usertools_access($env{'user.name'},
                   6833:                                   $env{'user.domain'},
                   6834:                                   $type,undef,'requestcourses')) {
                   6835:                 $canreq ++;
1.1036    raeburn  6836:                 if (ref($request_domains) eq 'HASH') {
                   6837:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6838:                 }
1.1035    raeburn  6839:                 if ($dom eq $env{'user.domain'}) {
                   6840:                     $can_request->{$type} = 1;
                   6841:                 }
                   6842:             }
                   6843:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6844:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6845:                 if (@curr > 0) {
1.1036    raeburn  6846:                     foreach my $item (@curr) {
                   6847:                         if (ref($request_domains) eq 'HASH') {
                   6848:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6849:                             if ($otherdom ne '') {
                   6850:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6851:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6852:                                         push(@{$request_domains->{$type}},$otherdom);
                   6853:                                     }
                   6854:                                 } else {
                   6855:                                     push(@{$request_domains->{$type}},$otherdom);
                   6856:                                 }
                   6857:                             }
                   6858:                         }
                   6859:                     }
                   6860:                     unless($dom eq $env{'user.domain'}) {
                   6861:                         $canreq ++;
1.1035    raeburn  6862:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6863:                             $can_request->{$type} = 1;
                   6864:                         }
                   6865:                     }
                   6866:                 }
                   6867:             }
                   6868:         }
                   6869:     }
                   6870:     return $canreq;
                   6871: }
                   6872: 
1.341     www      6873: # ---------------------------------------------- Custom access rule evaluation
                   6874: 
                   6875: sub customaccess {
                   6876:     my ($priv,$uri)=@_;
1.807     albertel 6877:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6878:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6879:     $udom = &LONCAPA::clean_domain($udom);
                   6880:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6881:     my $access=0;
1.800     albertel 6882:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6883: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6884: 	if ($type eq 'user') {
                   6885: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6886: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6887: 		if ($tdom) {
                   6888: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6889: 		}
1.896     albertel 6890: 		if ($tuname) {
                   6891: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6892: 		}
                   6893: 		$access=($effect eq 'allow');
                   6894: 		last;
                   6895: 	    }
                   6896: 	} else {
                   6897: 	    if ($role) {
                   6898: 		if ($role ne $urole) { next; }
                   6899: 	    }
                   6900: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6901: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6902: 		if ($tdom) {
                   6903: 		    if ($tdom ne $udom) { next; }
                   6904: 		}
                   6905: 		if ($tcrs) {
                   6906: 		    if ($tcrs ne $ucrs) { next; }
                   6907: 		}
                   6908: 		if ($tsec) {
                   6909: 		    if ($tsec ne $usec) { next; }
                   6910: 		}
                   6911: 		$access=($effect eq 'allow');
                   6912: 		last;
                   6913: 	    }
                   6914: 	    if ($realm eq '' && $role eq '') {
                   6915: 		$access=($effect eq 'allow');
                   6916: 	    }
1.402     bowersj2 6917: 	}
1.341     www      6918:     }
                   6919:     return $access;
                   6920: }
                   6921: 
1.103     harris41 6922: # ------------------------------------------------- Check for a user privilege
1.12      www      6923: 
                   6924: sub allowed {
1.1281    raeburn  6925:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 6926:     my $ver_orguri=$uri;
1.439     www      6927:     $uri=&deversion($uri);
1.152     www      6928:     my $orguri=$uri;
1.52      www      6929:     $uri=&declutter($uri);
1.809     raeburn  6930: 
1.810     raeburn  6931:     if ($priv eq 'evb') {
                   6932: # Evade communication block restrictions for specified role in a course
                   6933:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6934:             return $1;
                   6935:         } else {
                   6936:             return;
                   6937:         }
                   6938:     }
                   6939: 
1.620     albertel 6940:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6941: # Free bre access to adm and meta resources
1.775     albertel 6942:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6943: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6944: 	&& ($priv eq 'bre')) {
1.14      www      6945: 	return 'F';
1.159     www      6946:     }
                   6947: 
1.545     banghart 6948: # Free bre access to user's own portfolio contents
1.714     raeburn  6949:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6950:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6951: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6952:         my %setters;
                   6953:         my ($startblock,$endblock) = 
                   6954:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6955:         if ($startblock && $endblock) {
                   6956:             return 'B';
                   6957:         } else {
                   6958:             return 'F';
                   6959:         }
1.545     banghart 6960:     }
                   6961: 
1.762     raeburn  6962: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6963:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6964:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6965:         if (exists($env{'request.course.id'})) {
                   6966:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6967:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6968:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6969:                 my $courseprivid=$env{'request.course.id'};
                   6970:                 $courseprivid=~s/\_/\//;
                   6971:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6972:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6973:                     return $1; 
1.762     raeburn  6974:                 } else {
                   6975:                     if ($env{'request.course.sec'}) {
                   6976:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6977:                     }
                   6978:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6979:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6980:                         return $2;
                   6981:                     }
1.714     raeburn  6982:                 }
                   6983:             }
                   6984:         }
                   6985:     }
                   6986: 
1.159     www      6987: # Free bre to public access
                   6988: 
                   6989:     if ($priv eq 'bre') {
1.238     www      6990:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6991: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6992:            return 'F'; 
                   6993:         }
1.238     www      6994:         if ($copyright eq 'priv') {
                   6995:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6996: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6997: 		return '';
                   6998:             }
                   6999:         }
                   7000:         if ($copyright eq 'domain') {
                   7001:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7002: 	    unless (($env{'user.domain'} eq $1) ||
                   7003:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7004: 		return '';
                   7005:             }
1.262     matthew  7006:         }
1.620     albertel 7007:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7008:             # Library role, so allow browsing of resources in this domain.
                   7009:             return 'F';
1.238     www      7010:         }
1.341     www      7011:         if ($copyright eq 'custom') {
                   7012: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7013:         }
1.14      www      7014:     }
1.264     matthew  7015:     # Domain coordinator is trying to create a course
1.620     albertel 7016:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7017:         # uri is the requested domain in this case.
                   7018:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7019:         # a role of dc for the domain in question.
1.620     albertel 7020:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7021:     }
1.29      www      7022: 
1.52      www      7023:     my $thisallowed='';
                   7024:     my $statecond=0;
                   7025:     my $courseprivid='';
                   7026: 
1.1039    raeburn  7027:     my $ownaccess;
1.1043    raeburn  7028:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7029:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7030:         if ($uri eq '') {
                   7031:             $ownaccess = 1;
                   7032:         } else {
                   7033:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7034:                 my $udom = $env{'user.domain'};
                   7035:                 my $uname = $env{'user.name'};
                   7036:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7037:                     $ownaccess = 1;
1.1040    raeburn  7038:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7039:                     unless ($uri =~ m{\.\./}) {
                   7040:                         $ownaccess = 1;
                   7041:                     }
                   7042:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7043:                     my $now = time;
                   7044:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7045:                         my $adom = $1;
                   7046:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7047:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7048:                                 my ($start,$end) = split('.',$env{$key});
                   7049:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7050:                                     $ownaccess = 1;
                   7051:                                     last;
                   7052:                                 }
                   7053:                             }
                   7054:                         }
                   7055:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7056:                         my $adom = $1;
                   7057:                         my $aname = $2;
1.1042    raeburn  7058:                         foreach my $role ('ca','aa') { 
                   7059:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7060:                                 my ($start,$end) =
                   7061:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7062:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7063:                                     $ownaccess = 1;
                   7064:                                     last;
                   7065:                                 }
1.1039    raeburn  7066:                             }
                   7067:                         }
                   7068:                     }
                   7069:                 }
                   7070:             }
                   7071:         }
                   7072:     }
                   7073: 
1.52      www      7074: # Course
                   7075: 
1.620     albertel 7076:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7077:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7078:             $thisallowed.=$1;
                   7079:         }
1.52      www      7080:     }
1.29      www      7081: 
1.52      www      7082: # Domain
                   7083: 
1.620     albertel 7084:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7085:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7086:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7087:             $thisallowed.=$1;
                   7088:         }
1.12      www      7089:     }
1.52      www      7090: 
1.1141    raeburn  7091: # User who is not author or co-author might still be able to edit
                   7092: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7093:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7094:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7095:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7096:             $thisallowed.=$1;
                   7097:         }
                   7098:     }
                   7099: 
1.52      www      7100: # Course: uri itself is a course
1.66      www      7101:     my $courseuri=$uri;
                   7102:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7103:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7104: 
1.620     albertel 7105:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7106:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7107:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7108:             $thisallowed.=$1;
                   7109:         }
1.12      www      7110:     }
1.29      www      7111: 
1.665     albertel 7112: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7113: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7114:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7115: 	$thisallowed='';
1.671     raeburn  7116:         my ($match)=&is_on_map($uri);
                   7117:         if ($match) {
                   7118:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7119:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  7120:                 my $value = $1;
                   7121:                 if ($noblockcheck) {
                   7122:                     $thisallowed.=$value;
1.1162    raeburn  7123:                 } else {
1.1281    raeburn  7124:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7125:                     if (@blockers > 0) {
                   7126:                         $thisallowed = 'B';
                   7127:                     } else {
                   7128:                         $thisallowed.=$value;
                   7129:                     }
1.1162    raeburn  7130:                 }
1.671     raeburn  7131:             }
                   7132:         } else {
1.705     albertel 7133:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7134:             if ($refuri) {
                   7135:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7136:                     $thisallowed='F';
1.671     raeburn  7137:                 } else {
                   7138:                     $refuri=&declutter($refuri);
                   7139:                     my ($match) = &is_on_map($refuri);
                   7140:                     if ($match) {
1.1281    raeburn  7141:                         if ($noblockcheck) {
                   7142:                             $thisallowed='F';
1.1162    raeburn  7143:                         } else {
1.1281    raeburn  7144:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7145:                             if (@blockers > 0) {
                   7146:                                 $thisallowed = 'B';
                   7147:                             } else {
                   7148:                                 $thisallowed='F';
                   7149:                             }
1.1162    raeburn  7150:                         }
1.671     raeburn  7151:                     }
1.669     raeburn  7152:                 }
1.671     raeburn  7153:             }
                   7154:         }
1.314     www      7155:     }
1.492     albertel 7156: 
1.766     albertel 7157:     if ($priv eq 'bre'
                   7158: 	&& $thisallowed ne 'F' 
                   7159: 	&& $thisallowed ne '2'
                   7160: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  7161: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7162:     }
1.1250    raeburn  7163: 
1.52      www      7164: # Full access at system, domain or course-wide level? Exit.
1.29      www      7165:     if ($thisallowed=~/F/) {
                   7166: 	return 'F';
                   7167:     }
                   7168: 
1.52      www      7169: # If this is generating or modifying users, exit with special codes
1.29      www      7170: 
1.643     www      7171:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7172: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7173: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7174: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7175: 	    unless ($auname) { return $thisallowed; }
                   7176: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7177: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7178: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7179: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7180: 	}
1.52      www      7181: 	return $thisallowed;
                   7182:     }
                   7183: #
1.103     harris41 7184: # Gathered so far: system, domain and course wide privileges
1.52      www      7185: #
                   7186: # Course: See if uri or referer is an individual resource that is part of 
                   7187: # the course
                   7188: 
1.620     albertel 7189:     if ($env{'request.course.id'}) {
1.232     www      7190: 
1.620     albertel 7191:        $courseprivid=$env{'request.course.id'};
                   7192:        if ($env{'request.course.sec'}) {
                   7193:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7194:        }
                   7195:        $courseprivid=~s/\_/\//;
                   7196:        my $checkreferer=1;
1.232     www      7197:        my ($match,$cond)=&is_on_map($uri);
                   7198:        if ($match) {
                   7199:            $statecond=$cond;
1.620     albertel 7200:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7201:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7202:                my $value = $1;
                   7203:                if ($priv eq 'bre') {
1.1281    raeburn  7204:                    if ($noblockcheck) {
                   7205:                        $thisallowed.=$value;
1.1162    raeburn  7206:                    } else {
1.1281    raeburn  7207:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7208:                        if (@blockers > 0) {
                   7209:                            $thisallowed = 'B';
                   7210:                        } else {
                   7211:                            $thisallowed.=$value;
                   7212:                        }
1.1162    raeburn  7213:                    }
                   7214:                } else {
                   7215:                    $thisallowed.=$value;
                   7216:                }
1.52      www      7217:                $checkreferer=0;
                   7218:            }
1.29      www      7219:        }
1.83      www      7220:        
1.148     www      7221:        if ($checkreferer) {
1.620     albertel 7222: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7223:             unless ($refuri) {
1.800     albertel 7224:                 foreach my $key (keys(%env)) {
                   7225: 		    if ($key=~/^httpref\..*\*/) {
                   7226: 			my $pattern=$key;
1.156     www      7227:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7228:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7229:                         $pattern=~s/\//\\\//g;
1.152     www      7230:                         if ($orguri=~/$pattern/) {
1.800     albertel 7231: 			    $refuri=$env{$key};
1.148     www      7232:                         }
                   7233:                     }
1.191     harris41 7234:                 }
1.148     www      7235:             }
1.232     www      7236: 
1.148     www      7237:          if ($refuri) { 
1.152     www      7238: 	  $refuri=&declutter($refuri);
1.232     www      7239:           my ($match,$cond)=&is_on_map($refuri);
                   7240:             if ($match) {
                   7241:               my $refstatecond=$cond;
1.620     albertel 7242:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7243:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7244:                   my $value = $1;
                   7245:                   if ($priv eq 'bre') {
1.1281    raeburn  7246:                       if ($noblockcheck) {
                   7247:                           $thisallowed.=$value;
1.1162    raeburn  7248:                       } else {
1.1281    raeburn  7249:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7250:                           if (@blockers > 0) {
                   7251:                               $thisallowed = 'B';
                   7252:                           } else {
                   7253:                               $thisallowed.=$value;
                   7254:                           }
1.1162    raeburn  7255:                       }
                   7256:                   } else {
                   7257:                       $thisallowed.=$value;
                   7258:                   }
1.53      www      7259:                   $uri=$refuri;
                   7260:                   $statecond=$refstatecond;
1.52      www      7261:               }
                   7262:           }
1.148     www      7263:         }
1.29      www      7264:        }
1.52      www      7265:    }
1.29      www      7266: 
1.52      www      7267: #
1.103     harris41 7268: # Gathered now: all privileges that could apply, and condition number
1.52      www      7269: # 
                   7270: #
                   7271: # Full or no access?
                   7272: #
1.29      www      7273: 
1.52      www      7274:     if ($thisallowed=~/F/) {
                   7275: 	return 'F';
                   7276:     }
1.29      www      7277: 
1.52      www      7278:     unless ($thisallowed) {
                   7279:         return '';
                   7280:     }
1.29      www      7281: 
1.52      www      7282: # Restrictions exist, deal with them
                   7283: #
                   7284: #   C:according to course preferences
                   7285: #   R:according to resource settings
                   7286: #   L:unless locked
                   7287: #   X:according to user session state
                   7288: #
                   7289: 
                   7290: # Possibly locked functionality, check all courses
1.54      www      7291: # Locks might take effect only after 10 minutes cache expiration for other
                   7292: # courses, and 2 minutes for current course
1.52      www      7293: 
                   7294:     my $envkey;
                   7295:     if ($thisallowed=~/L/) {
1.1000    raeburn  7296:         foreach $envkey (keys(%env)) {
1.54      www      7297:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7298:                my $courseid=$2;
                   7299:                my $roleid=$1.'.'.$2;
1.92      www      7300:                $courseid=~s/^\///;
1.54      www      7301:                my $expiretime=600;
1.620     albertel 7302:                if ($env{'request.role'} eq $roleid) {
1.54      www      7303: 		  $expiretime=120;
                   7304:                }
                   7305: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7306:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7307:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7308: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7309:                }
1.620     albertel 7310:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7311:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7312: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7313:                        &log($env{'user.domain'},$env{'user.name'},
                   7314:                             $env{'user.home'},
1.57      www      7315:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7316:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7317:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7318: 		       return '';
                   7319:                    }
                   7320:                }
1.620     albertel 7321:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7322:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7323: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7324:                        &log($env{'user.domain'},$env{'user.name'},
                   7325:                             $env{'user.home'},
1.57      www      7326:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7327:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7328:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7329: 		       return '';
                   7330:                    }
                   7331:                }
                   7332: 	   }
1.29      www      7333:        }
1.52      www      7334:     }
                   7335:    
                   7336: #
                   7337: # Rest of the restrictions depend on selected course
                   7338: #
                   7339: 
1.620     albertel 7340:     unless ($env{'request.course.id'}) {
1.766     albertel 7341: 	if ($thisallowed eq 'A') {
                   7342: 	    return 'A';
1.814     raeburn  7343:         } elsif ($thisallowed eq 'B') {
                   7344:             return 'B';
1.766     albertel 7345: 	} else {
                   7346: 	    return '1';
                   7347: 	}
1.52      www      7348:     }
1.29      www      7349: 
1.52      www      7350: #
                   7351: # Now user is definitely in a course
                   7352: #
1.53      www      7353: 
                   7354: 
                   7355: # Course preferences
                   7356: 
                   7357:    if ($thisallowed=~/C/) {
1.620     albertel 7358:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7359:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7360:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7361: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  7362: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 7363: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7364: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7365: 			$env{'request.course.id'});
                   7366: 	   }
1.237     www      7367:            return '';
                   7368:        }
                   7369: 
1.620     albertel 7370:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7371: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  7372: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 7373: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7374: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7375: 			$env{'request.course.id'});
                   7376: 	   }
1.54      www      7377:            return '';
                   7378:        }
1.53      www      7379:    }
                   7380: 
                   7381: # Resource preferences
                   7382: 
                   7383:    if ($thisallowed=~/R/) {
1.620     albertel 7384:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7385:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7386: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7387: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7388: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7389: 	   }
                   7390: 	   return '';
1.54      www      7391:        }
1.53      www      7392:    }
1.30      www      7393: 
1.246     www      7394: # Restricted by state or randomout?
1.30      www      7395: 
1.52      www      7396:    if ($thisallowed=~/X/) {
1.620     albertel 7397:       if ($env{'acc.randomout'}) {
1.579     albertel 7398: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7399:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7400:             return ''; 
                   7401:          }
1.247     www      7402:       }
                   7403:       if (&condval($statecond)) {
1.52      www      7404: 	 return '2';
                   7405:       } else {
                   7406:          return '';
                   7407:       }
                   7408:    }
1.30      www      7409: 
1.766     albertel 7410:     if ($thisallowed eq 'A') {
                   7411: 	return 'A';
1.814     raeburn  7412:     } elsif ($thisallowed eq 'B') {
                   7413:         return 'B';
1.766     albertel 7414:     }
1.52      www      7415:    return 'F';
1.232     www      7416: }
1.1162    raeburn  7417: 
1.1192    raeburn  7418: # ------------------------------------------- Check construction space access
                   7419: 
                   7420: sub constructaccess {
                   7421:     my ($url,$setpriv)=@_;
                   7422: 
                   7423: # We do not allow editing of previous versions of files
                   7424:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7425: 
                   7426: # Get username and domain from URL
                   7427:     my ($ownername,$ownerdomain,$ownerhome);
                   7428: 
                   7429:     ($ownerdomain,$ownername) =
1.1297    damieng  7430:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)/});
1.1192    raeburn  7431: 
                   7432: # The URL does not really point to any authorspace, forget it
                   7433:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7434: 
                   7435: # Now we need to see if the user has access to the authorspace of
                   7436: # $ownername at $ownerdomain
                   7437: 
                   7438:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7439: # Real author for this?
                   7440:        $ownerhome = $env{'user.home'};
                   7441:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7442:           return ($ownername,$ownerdomain,$ownerhome);
                   7443:        }
                   7444:     } else {
                   7445: # Co-author for this?
                   7446:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7447:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7448:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7449:             return ($ownername,$ownerdomain,$ownerhome);
                   7450:         }
1.1312    raeburn  7451:         if ($env{'request.course.id'}) {
                   7452:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
                   7453:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
                   7454:                 if (&allowed('mdc',$env{'request.course.id'})) {
                   7455:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   7456:                     return ($ownername,$ownerdomain,$ownerhome);
                   7457:                 }
                   7458:             }
                   7459:         }
1.1192    raeburn  7460:     }
                   7461: 
                   7462: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7463: # we might as well leave
                   7464:    unless ($setpriv) { return ''; }
                   7465: 
                   7466: # Backdoor access?
                   7467:     my $allowed=&allowed('eco',$ownerdomain);
                   7468: # Nope
                   7469:     unless ($allowed) { return ''; }
                   7470: # Looks like we may have access, but could be locked by the owner of the construction space
                   7471:     if ($allowed eq 'U') {
                   7472:         my %blocked=&get('environment',['domcoord.author'],
                   7473:                          $ownerdomain,$ownername);
                   7474: # Is blocked by owner
                   7475:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7476:     }
                   7477:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7478: # Grant temporary access
                   7479:         my $then=$env{'user.login.time'};
1.1209    raeburn  7480:         my $update=$env{'user.update.time'};
1.1192    raeburn  7481:         if (!$update) { $update = $then; }
                   7482:         my $refresh=$env{'user.refresh.time'};
                   7483:         if (!$refresh) { $refresh = $update; }
                   7484:         my $now = time;
                   7485:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7486:                            $now,'ca','constructaccess');
                   7487:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7488:         return($ownername,$ownerdomain,$ownerhome);
                   7489:     }
                   7490: # No business here
                   7491:     return '';
                   7492: }
                   7493: 
1.1282    raeburn  7494: # ----------------------------------------------------------- Content Blocking
                   7495: 
                   7496: {
                   7497: # Caches for faster Course Contents display where content blocking
                   7498: # is in operation (i.e., interval param set) for timed quiz.
                   7499: #
                   7500: # User for whom data are being temporarily cached.
                   7501: my $cacheduser='';
                   7502: # Cached blockers for this user (a hash of blocking items). 
                   7503: my %cachedblockers=();
                   7504: # When the data were last cached.
                   7505: my $cachedlast='';
                   7506: 
                   7507: sub load_all_blockers {
                   7508:     my ($uname,$udom,$blocks)=@_;
                   7509:     if (($uname ne '') && ($udom ne '')) { 
                   7510:         if (($cacheduser eq $uname.':'.$udom) &&
                   7511:             (abs($cachedlast-time)<5)) {
                   7512:             return;
                   7513:         }
                   7514:     }
                   7515:     $cachedlast=time;
                   7516:     $cacheduser=$uname.':'.$udom;
                   7517:     %cachedblockers = &get_commblock_resources($blocks);
                   7518: }
                   7519: 
1.1162    raeburn  7520: sub get_comm_blocks {
                   7521:     my ($cdom,$cnum) = @_;
                   7522:     if ($cdom eq '' || $cnum eq '') {
                   7523:         return unless ($env{'request.course.id'});
                   7524:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7525:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7526:     }
                   7527:     my %commblocks;
                   7528:     my $hashid=$cdom.'_'.$cnum;
                   7529:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7530:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7531:         %commblocks = %{$blocksref};
                   7532:     } else {
                   7533:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7534:         my $cachetime = 600;
                   7535:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7536:     }
                   7537:     return %commblocks;
                   7538: }
                   7539: 
1.1282    raeburn  7540: sub get_commblock_resources {
                   7541:     my ($blocks) = @_;
                   7542:     my %blockers = ();
                   7543:     return %blockers unless ($env{'request.course.id'});
                   7544:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  7545:     my %commblocks;
                   7546:     if (ref($blocks) eq 'HASH') {
                   7547:         %commblocks = %{$blocks};
                   7548:     } else {
                   7549:         %commblocks = &get_comm_blocks();
                   7550:     }
1.1282    raeburn  7551:     return %blockers unless (keys(%commblocks) > 0); 
                   7552:     my $navmap = Apache::lonnavmaps::navmap->new();
                   7553:     return %blockers unless (ref($navmap));
1.1162    raeburn  7554:     my $now = time;
                   7555:     foreach my $block (keys(%commblocks)) {
                   7556:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7557:             my ($start,$end) = ($1,$2);
                   7558:             if ($start <= $now && $end >= $now) {
                   7559:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7560:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7561:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  7562:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7563:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  7564:                             }
                   7565:                         }
                   7566:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  7567:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7568:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  7569:                             }
                   7570:                         }
                   7571:                     }
                   7572:                 }
                   7573:             }
                   7574:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7575:             my $item = $1;
1.1163    raeburn  7576:             my @to_test;
1.1162    raeburn  7577:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7578:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282    raeburn  7579:                     my @interval;
                   7580:                     my $type = 'map';
                   7581:                     if ($item eq 'course') {
                   7582:                         $type = 'course';
                   7583:                         @interval=&EXT("resource.0.interval");
                   7584:                     } else {
                   7585:                         if ($item =~ /___\d+___/) {
                   7586:                             $type = 'resource';
                   7587:                             @interval=&EXT("resource.0.interval",$item);
                   7588:                             if (ref($navmap)) {                        
                   7589:                                 my $res = $navmap->getBySymb($item); 
                   7590:                                 push(@to_test,$res);
                   7591:                             }
1.1162    raeburn  7592:                         } else {
1.1282    raeburn  7593:                             my $mapsymb = &symbread($item,1);
                   7594:                             if ($mapsymb) {
                   7595:                                 if (ref($navmap)) {
                   7596:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   7597:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   7598:                                     foreach my $res (@to_test) {
                   7599:                                         my $symb = $res->symb();
                   7600:                                         next if ($symb eq $mapsymb);
                   7601:                                         if ($symb ne '') {
                   7602:                                             @interval=&EXT("resource.0.interval",$symb);
                   7603:                                             if ($interval[1] eq 'map') {
                   7604:                                                 last;
1.1162    raeburn  7605:                                             }
                   7606:                                         }
                   7607:                                     }
                   7608:                                 }
                   7609:                             }
                   7610:                         }
1.1282    raeburn  7611:                     }
1.1310    raeburn  7612:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  7613:                         my $timelimit = $1; 
1.1282    raeburn  7614:                         my $first_access;
                   7615:                         if ($type eq 'resource') {
                   7616:                             $first_access=&get_first_access($interval[1],$item);
                   7617:                         } elsif ($type eq 'map') {
                   7618:                             $first_access=&get_first_access($interval[1],undef,$item);
                   7619:                         } else {
                   7620:                             $first_access=&get_first_access($interval[1]);
                   7621:                         }
                   7622:                         if ($first_access) {
1.1292    raeburn  7623:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  7624:                             if ($timesup > $now) {
                   7625:                                 my $activeblock;
                   7626:                                 foreach my $res (@to_test) {
1.1283    raeburn  7627:                                     if ($res->answerable()) {
1.1282    raeburn  7628:                                         $activeblock = 1;
                   7629:                                         last;
                   7630:                                     }
                   7631:                                 }
                   7632:                                 if ($activeblock) {
                   7633:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7634:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7635:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   7636:                                          }
                   7637:                                     }
                   7638:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7639:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7640:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  7641:                                         }
1.1162    raeburn  7642:                                     }
                   7643:                                 }
                   7644:                             }
                   7645:                         }
                   7646:                     }
                   7647:                 }
                   7648:             }
                   7649:         }
                   7650:     }
1.1282    raeburn  7651:     return %blockers;
1.1162    raeburn  7652: }
                   7653: 
1.1282    raeburn  7654: sub has_comm_blocking {
                   7655:     my ($priv,$symb,$uri,$blocks) = @_;
                   7656:     my @blockers;
                   7657:     return unless ($env{'request.course.id'});
                   7658:     return unless ($priv eq 'bre');
                   7659:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7660:     return if ($env{'request.state'} eq 'construct');
                   7661:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   7662:     return unless (keys(%cachedblockers) > 0);
                   7663:     my (%possibles,@symbs);
                   7664:     if (!$symb) {
                   7665:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  7666:     }
1.1282    raeburn  7667:     if ($symb) {
                   7668:         @symbs = ($symb);
                   7669:     } elsif (keys(%possibles)) { 
                   7670:         @symbs = keys(%possibles);
                   7671:     }
                   7672:     my $noblock;
                   7673:     foreach my $symb (@symbs) {
                   7674:         last if ($noblock);
                   7675:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   7676:         foreach my $block (keys(%cachedblockers)) {
                   7677:             if ($block =~ /^firstaccess____(.+)$/) {
                   7678:                 my $item = $1;
                   7679:                 if (($item eq $map) || ($item eq $symb)) {
                   7680:                     $noblock = 1;
                   7681:                     last;
                   7682:                 }
                   7683:             }
                   7684:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   7685:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   7686:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   7687:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   7688:                             push(@blockers,$block);
                   7689:                         }
                   7690:                     }
                   7691:                 }
1.1162    raeburn  7692:             }
1.1282    raeburn  7693:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   7694:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   7695:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   7696:                         push(@blockers,$block);
                   7697:                     }
                   7698:                 }
1.1162    raeburn  7699:             }
                   7700:         }
                   7701:     }
1.1282    raeburn  7702:     return if ($noblock);
                   7703:     return @blockers;
                   7704: }
1.1162    raeburn  7705: }
                   7706: 
1.1282    raeburn  7707: # -------------------------------- Deversion and split uri into path an filename   
                   7708: 
1.1133    foxr     7709: #
1.1282    raeburn  7710: #   Removes the version from a URI and
1.1133    foxr     7711: #   splits it in to its filename and path to the filename.
                   7712: #   Seems like File::Basename could have done this more clearly.
                   7713: #   Parameters:
                   7714: #      $uri   - input URI
                   7715: #   Returns:
                   7716: #     Two element list consisting of 
                   7717: #     $pathname  - the URI up to and excluding the trailing /
                   7718: #     $filename  - The part of the URI following the last /
                   7719: #  NOTE:
                   7720: #    Another realization of this is simply:
                   7721: #    use File::Basename;
                   7722: #    ...
                   7723: #    $uri = shift;
                   7724: #    $filename = basename($uri);
                   7725: #    $path     = dirname($uri);
                   7726: #    return ($filename, $path);
                   7727: #
                   7728: #     The implementation below is probably faster however.
                   7729: #
1.710     albertel 7730: sub split_uri_for_cond {
                   7731:     my $uri=&deversion(&declutter(shift));
                   7732:     my @uriparts=split(/\//,$uri);
                   7733:     my $filename=pop(@uriparts);
                   7734:     my $pathname=join('/',@uriparts);
                   7735:     return ($pathname,$filename);
                   7736: }
1.232     www      7737: # --------------------------------------------------- Is a resource on the map?
                   7738: 
                   7739: sub is_on_map {
1.710     albertel 7740:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7741:     #Trying to find the conditional for the file
1.620     albertel 7742:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7743: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7744:     if ($match) {
1.289     bowersj2 7745: 	return (1,$1);
                   7746:     } else {
1.434     www      7747: 	return (0,0);
1.289     bowersj2 7748:     }
1.12      www      7749: }
                   7750: 
1.427     www      7751: # --------------------------------------------------------- Get symb from alias
                   7752: 
                   7753: sub get_symb_from_alias {
                   7754:     my $symb=shift;
                   7755:     my ($map,$resid,$url)=&decode_symb($symb);
                   7756: # Already is a symb
                   7757:     if ($url) { return $symb; }
                   7758: # Must be an alias
                   7759:     my $aliassymb='';
                   7760:     my %bighash;
1.620     albertel 7761:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7762:                             &GDBM_READER(),0640)) {
                   7763:         my $rid=$bighash{'mapalias_'.$symb};
                   7764: 	if ($rid) {
                   7765: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7766: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7767: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7768: 	}
                   7769:         untie %bighash;
                   7770:     }
                   7771:     return $aliassymb;
                   7772: }
                   7773: 
1.12      www      7774: # ----------------------------------------------------------------- Define Role
                   7775: 
                   7776: sub definerole {
                   7777:   if (allowed('mcr','/')) {
                   7778:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7779:     foreach my $role (split(':',$sysrole)) {
                   7780: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7781:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7782:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7783: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7784:                return "refused:s:$crole&$cqual"; 
                   7785:             }
                   7786:         }
1.191     harris41 7787:     }
1.800     albertel 7788:     foreach my $role (split(':',$domrole)) {
                   7789: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7790:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7791:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7792: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7793:                return "refused:d:$crole&$cqual"; 
                   7794:             }
                   7795:         }
1.191     harris41 7796:     }
1.800     albertel 7797:     foreach my $role (split(':',$courole)) {
                   7798: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7799:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7800:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7801: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7802:                return "refused:c:$crole&$cqual"; 
                   7803:             }
                   7804:         }
1.191     harris41 7805:     }
1.620     albertel 7806:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7807:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7808: 	        "rolesdef_$rolename=".
                   7809:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7810:     return reply($command,$env{'user.home'});
1.12      www      7811:   } else {
                   7812:     return 'refused';
                   7813:   }
1.105     harris41 7814: }
                   7815: 
                   7816: # ---------------- Make a metadata query against the network of library servers
                   7817: 
                   7818: sub metadata_query {
1.1237    raeburn  7819:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 7820:     my %rhash;
1.845     albertel 7821:     my %libserv = &all_library();
1.244     matthew  7822:     my @server_list = (defined($server_array) ? @$server_array
                   7823:                                               : keys(%libserv) );
                   7824:     for my $server (@server_list) {
1.1237    raeburn  7825:         my $domains = ''; 
                   7826:         if (ref($domains_hash) eq 'HASH') {
                   7827:             $domains = $domains_hash->{$server}; 
                   7828:         }
1.118     harris41 7829: 	unless ($custom or $customshow) {
1.1237    raeburn  7830: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 7831: 	    $rhash{$server}=$reply;
                   7832: 	}
                   7833: 	else {
                   7834: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  7835: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 7836: 			     $server);
                   7837: 	    $rhash{$server}=$reply;
                   7838: 	}
1.112     harris41 7839:     }
1.118     harris41 7840:     return \%rhash;
1.240     www      7841: }
                   7842: 
                   7843: # ----------------------------------------- Send log queries and wait for reply
                   7844: 
                   7845: sub log_query {
                   7846:     my ($uname,$udom,$query,%filters)=@_;
                   7847:     my $uhome=&homeserver($uname,$udom);
                   7848:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7849:     my $uhost=&hostname($uhome);
1.800     albertel 7850:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7851:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7852:                        $uhome);
1.479     albertel 7853:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7854:     return get_query_reply($queryid);
                   7855: }
                   7856: 
1.818     raeburn  7857: # -------------------------- Update MySQL table for portfolio file
                   7858: 
                   7859: sub update_portfolio_table {
1.821     raeburn  7860:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7861:     if ($group ne '') {
                   7862:         $file_name =~s /^\Q$group\E//;
                   7863:     }
1.818     raeburn  7864:     my $homeserver = &homeserver($uname,$udom);
                   7865:     my $queryid=
1.821     raeburn  7866:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7867:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7868:     my $reply = &get_query_reply($queryid);
                   7869:     return $reply;
                   7870: }
                   7871: 
1.899     raeburn  7872: # -------------------------- Update MySQL allusers table
                   7873: 
                   7874: sub update_allusers_table {
                   7875:     my ($uname,$udom,$names) = @_;
                   7876:     my $homeserver = &homeserver($uname,$udom);
                   7877:     my $queryid=
                   7878:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7879:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7880:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7881:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7882:                'generation='.&escape($names->{'generation'}).'%%'.
                   7883:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7884:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7885:     return;
1.899     raeburn  7886: }
                   7887: 
1.508     raeburn  7888: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7889: 
                   7890: sub fetch_enrollment_query {
1.511     raeburn  7891:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317    raeburn  7892:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  7893:     my $maxtries = 1;
1.508     raeburn  7894:     if ($context eq 'automated') {
                   7895:         $homeserver = $perlvar{'lonHostID'};
1.1317    raeburn  7896:         $sleep = 2;
                   7897:         $loopmax = 100;
1.547     raeburn  7898:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7899:     } else {
                   7900:         $homeserver = &homeserver($cnum,$dom);
                   7901:     }
1.838     albertel 7902:     my $host=&hostname($homeserver);
1.506     raeburn  7903:     my $cmd = '';
1.1000    raeburn  7904:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7905:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7906:     }
                   7907:     $cmd =~ s/%%$//;
                   7908:     $cmd = &escape($cmd);
                   7909:     my $query = 'fetchenrollment';
1.620     albertel 7910:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7911:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7912:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7913:         return 'error: '.$queryid;
                   7914:     }
1.1317    raeburn  7915:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  7916:     my $tries = 1;
                   7917:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317    raeburn  7918:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  7919:         $tries ++;
                   7920:     }
1.526     raeburn  7921:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7922:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7923:     } else {
1.901     albertel 7924:         my @responses = split(/:/,$reply);
1.1322    raeburn  7925:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 7926:             foreach my $line (@responses) {
                   7927:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7928:                 $$replyref{$key} = $value;
                   7929:             }
                   7930:         } else {
1.1117    foxr     7931:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7932:             foreach my $line (@responses) {
                   7933:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7934:                 $$replyref{$key} = $value;
                   7935:                 if ($value > 0) {
1.800     albertel 7936:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7937:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7938:                         my $destname = $pathname.'/'.$filename;
                   7939:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7940:                         if ($xml_classlist =~ /^error/) {
                   7941:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7942:                         } else {
1.506     raeburn  7943:                             if ( open(FILE,">$destname") ) {
                   7944:                                 print FILE &unescape($xml_classlist);
                   7945:                                 close(FILE);
1.526     raeburn  7946:                             } else {
                   7947:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7948:                             }
                   7949:                         }
                   7950:                     }
                   7951:                 }
                   7952:             }
                   7953:         }
                   7954:         return 'ok';
                   7955:     }
                   7956:     return 'error';
                   7957: }
                   7958: 
1.242     www      7959: sub get_query_reply {
1.1317    raeburn  7960:     my ($queryid,$sleep,$loopmax) = @_;;
                   7961:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   7962:         $sleep = 0.2;
                   7963:     }
                   7964:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   7965:         $loopmax = 100;
                   7966:     }
1.1117    foxr     7967:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7968:     my $reply='';
1.1317    raeburn  7969:     for (1..$loopmax) {
                   7970: 	sleep($sleep);
1.240     www      7971:         if (-e $replyfile.'.end') {
1.448     albertel 7972: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7973: 		$reply = join('',<$fh>);
                   7974: 		close($fh);
1.240     www      7975: 	   } else { return 'error: reply_file_error'; }
1.242     www      7976:            return &unescape($reply);
                   7977: 	}
1.240     www      7978:     }
1.242     www      7979:     return 'timeout:'.$queryid;
1.240     www      7980: }
                   7981: 
                   7982: sub courselog_query {
1.241     www      7983: #
                   7984: # possible filters:
                   7985: # url: url or symb
                   7986: # username
                   7987: # domain
                   7988: # action: view, submit, grade
                   7989: # start: timestamp
                   7990: # end: timestamp
                   7991: #
1.240     www      7992:     my (%filters)=@_;
1.620     albertel 7993:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7994:     if ($filters{'url'}) {
                   7995: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7996:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7997:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7998:     }
1.620     albertel 7999:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8000:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8001:     return &log_query($cname,$cdom,'courselog',%filters);
                   8002: }
                   8003: 
                   8004: sub userlog_query {
1.858     raeburn  8005: #
                   8006: # possible filters:
                   8007: # action: log check role
                   8008: # start: timestamp
                   8009: # end: timestamp
                   8010: #
1.240     www      8011:     my ($uname,$udom,%filters)=@_;
                   8012:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8013: }
                   8014: 
1.506     raeburn  8015: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8016: 
                   8017: sub auto_run {
1.508     raeburn  8018:     my ($cnum,$cdom) = @_;
1.876     raeburn  8019:     my $response = 0;
                   8020:     my $settings;
                   8021:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8022:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8023:         $settings = $domconfig{'autoenroll'};
                   8024:         if ($settings->{'run'} eq '1') {
                   8025:             $response = 1;
                   8026:         }
                   8027:     } else {
1.934     raeburn  8028:         my $homeserver;
                   8029:         if (&is_course($cdom,$cnum)) {
                   8030:             $homeserver = &homeserver($cnum,$cdom);
                   8031:         } else {
                   8032:             $homeserver = &domain($cdom,'primary');
                   8033:         }
                   8034:         if ($homeserver ne 'no_host') {
                   8035:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8036:         }
1.876     raeburn  8037:     }
1.506     raeburn  8038:     return $response;
                   8039: }
1.776     albertel 8040: 
1.506     raeburn  8041: sub auto_get_sections {
1.508     raeburn  8042:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8043:     my $homeserver;
                   8044:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8045:         $homeserver = &homeserver($cnum,$cdom);
                   8046:     }
                   8047:     if (!defined($homeserver)) { 
                   8048:         if ($cdom =~ /^$match_domain$/) {
                   8049:             $homeserver = &domain($cdom,'primary');
                   8050:         }
                   8051:     }
                   8052:     my @secs;
                   8053:     if (defined($homeserver)) {
                   8054:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8055:         unless ($response eq 'refused') {
                   8056:             @secs = split(/:/,$response);
                   8057:         }
1.506     raeburn  8058:     }
                   8059:     return @secs;
                   8060: }
1.776     albertel 8061: 
1.506     raeburn  8062: sub auto_new_course {
1.1099    raeburn  8063:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8064:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8065:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8066:     return $response;
                   8067: }
1.776     albertel 8068: 
1.506     raeburn  8069: sub auto_validate_courseID {
1.508     raeburn  8070:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8071:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8072:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8073:     return $response;
                   8074: }
1.776     albertel 8075: 
1.1007    raeburn  8076: sub auto_validate_instcode {
1.1020    raeburn  8077:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8078:     my ($homeserver,$response);
                   8079:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8080:         $homeserver = &homeserver($cnum,$cdom);
                   8081:     }
                   8082:     if (!defined($homeserver)) {
                   8083:         if ($cdom =~ /^$match_domain$/) {
                   8084:             $homeserver = &domain($cdom,'primary');
                   8085:         }
                   8086:     }
1.1065    raeburn  8087:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8088:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  8089:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8090:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8091: }
                   8092: 
1.506     raeburn  8093: sub auto_create_password {
1.873     raeburn  8094:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8095:     my ($homeserver,$response);
1.506     raeburn  8096:     my $create_passwd = 0;
                   8097:     my $authchk = '';
1.873     raeburn  8098:     if ($udom =~ /^$match_domain$/) {
                   8099:         $homeserver = &domain($udom,'primary');
                   8100:     }
                   8101:     if ($homeserver eq '') {
                   8102:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8103:             $homeserver = &homeserver($cnum,$cdom);
                   8104:         }
                   8105:     }
                   8106:     if ($homeserver eq '') {
                   8107:         $authchk = 'nodomain';
1.506     raeburn  8108:     } else {
1.873     raeburn  8109:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8110:         if ($response eq 'refused') {
                   8111:             $authchk = 'refused';
                   8112:         } else {
1.901     albertel 8113:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8114:         }
1.506     raeburn  8115:     }
                   8116:     return ($authparam,$create_passwd,$authchk);
                   8117: }
                   8118: 
1.706     raeburn  8119: sub auto_photo_permission {
                   8120:     my ($cnum,$cdom,$students) = @_;
                   8121:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8122:     my ($outcome,$perm_reqd,$conditions) = 
                   8123: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8124:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8125: 	return (undef,undef);
                   8126:     }
1.706     raeburn  8127:     return ($outcome,$perm_reqd,$conditions);
                   8128: }
                   8129: 
                   8130: sub auto_checkphotos {
                   8131:     my ($uname,$udom,$pid) = @_;
                   8132:     my $homeserver = &homeserver($uname,$udom);
                   8133:     my ($result,$resulttype);
                   8134:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8135: 				   &escape($uname).':'.&escape($pid),
                   8136: 				   $homeserver));
1.709     albertel 8137:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8138: 	return (undef,undef);
                   8139:     }
1.706     raeburn  8140:     if ($outcome) {
                   8141:         ($result,$resulttype) = split(/:/,$outcome);
                   8142:     } 
                   8143:     return ($result,$resulttype);
                   8144: }
                   8145: 
                   8146: sub auto_photochoice {
                   8147:     my ($cnum,$cdom) = @_;
                   8148:     my $homeserver = &homeserver($cnum,$cdom);
                   8149:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8150: 						       &escape($cdom),
                   8151: 						       $homeserver)));
1.709     albertel 8152:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8153: 	return (undef,undef);
                   8154:     }
1.706     raeburn  8155:     return ($update,$comment);
                   8156: }
                   8157: 
                   8158: sub auto_photoupdate {
                   8159:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8160:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8161:     my $host=&hostname($homeserver);
1.706     raeburn  8162:     my $cmd = '';
                   8163:     my $maxtries = 1;
1.800     albertel 8164:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8165:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8166:     }
                   8167:     $cmd =~ s/%%$//;
                   8168:     $cmd = &escape($cmd);
                   8169:     my $query = 'institutionalphotos';
                   8170:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8171:     unless ($queryid=~/^\Q$host\E\_/) {
                   8172:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8173:         return 'error: '.$queryid;
                   8174:     }
                   8175:     my $reply = &get_query_reply($queryid);
                   8176:     my $tries = 1;
                   8177:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8178:         $reply = &get_query_reply($queryid);
                   8179:         $tries ++;
                   8180:     }
                   8181:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8182:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8183:     } else {
                   8184:         my @responses = split(/:/,$reply);
                   8185:         my $outcome = shift(@responses); 
                   8186:         foreach my $item (@responses) {
                   8187:             my ($key,$value) = split(/=/,$item);
                   8188:             $$photo{$key} = $value;
                   8189:         }
                   8190:         return $outcome;
                   8191:     }
                   8192:     return 'error';
                   8193: }
                   8194: 
1.521     raeburn  8195: sub auto_instcode_format {
1.793     albertel 8196:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8197: 	$cat_order) = @_;
1.521     raeburn  8198:     my $courses = '';
1.772     raeburn  8199:     my @homeservers;
1.521     raeburn  8200:     if ($caller eq 'global') {
1.841     albertel 8201: 	my %servers = &get_servers($codedom,'library');
                   8202: 	foreach my $tryserver (keys(%servers)) {
                   8203: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8204: 		push(@homeservers,$tryserver);
                   8205: 	    }
1.584     raeburn  8206:         }
1.1022    raeburn  8207:     } elsif ($caller eq 'requests') {
                   8208:         if ($codedom =~ /^$match_domain$/) {
                   8209:             my $chome = &domain($codedom,'primary');
                   8210:             unless ($chome eq 'no_host') {
                   8211:                 push(@homeservers,$chome);
                   8212:             }
                   8213:         }
1.521     raeburn  8214:     } else {
1.772     raeburn  8215:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8216:     }
1.793     albertel 8217:     foreach my $code (keys(%{$instcodes})) {
                   8218:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8219:     }
                   8220:     chop($courses);
1.772     raeburn  8221:     my $ok_response = 0;
                   8222:     my $response;
                   8223:     while (@homeservers > 0 && $ok_response == 0) {
                   8224:         my $server = shift(@homeservers); 
                   8225:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8226:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8227:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8228: 		split(/:/,$response);
1.772     raeburn  8229:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8230:             push(@{$codetitles},&str2array($codetitles_str));
                   8231:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8232:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8233:             $ok_response = 1;
                   8234:         }
                   8235:     }
                   8236:     if ($ok_response) {
1.521     raeburn  8237:         return 'ok';
1.772     raeburn  8238:     } else {
                   8239:         return $response;
1.521     raeburn  8240:     }
                   8241: }
                   8242: 
1.792     raeburn  8243: sub auto_instcode_defaults {
                   8244:     my ($domain,$returnhash,$code_order) = @_;
                   8245:     my @homeservers;
1.841     albertel 8246: 
                   8247:     my %servers = &get_servers($domain,'library');
                   8248:     foreach my $tryserver (keys(%servers)) {
                   8249: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8250: 	    push(@homeservers,$tryserver);
                   8251: 	}
1.792     raeburn  8252:     }
1.841     albertel 8253: 
1.792     raeburn  8254:     my $response;
1.841     albertel 8255:     foreach my $server (@homeservers) {
1.792     raeburn  8256:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8257:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8258: 	
                   8259: 	foreach my $pair (split(/\&/,$response)) {
                   8260: 	    my ($name,$value)=split(/\=/,$pair);
                   8261: 	    if ($name eq 'code_order') {
                   8262: 		@{$code_order} = split(/\&/,&unescape($value));
                   8263: 	    } else {
                   8264: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8265: 	    }
                   8266: 	}
                   8267: 	return 'ok';
1.792     raeburn  8268:     }
1.841     albertel 8269: 
                   8270:     return $response;
1.1003    raeburn  8271: }
                   8272: 
                   8273: sub auto_possible_instcodes {
1.1007    raeburn  8274:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8275:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8276:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8277:         return;
                   8278:     }
1.1003    raeburn  8279:     my (@homeservers,$uhome);
                   8280:     if (defined(&domain($domain,'primary'))) {
                   8281:         $uhome=&domain($domain,'primary');
                   8282:         push(@homeservers,&domain($domain,'primary'));
                   8283:     } else {
                   8284:         my %servers = &get_servers($domain,'library');
                   8285:         foreach my $tryserver (keys(%servers)) {
                   8286:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8287:                 push(@homeservers,$tryserver);
                   8288:             }
                   8289:         }
                   8290:     }
                   8291:     my $response;
                   8292:     foreach my $server (@homeservers) {
                   8293:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8294:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8295:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8296:             split(':',$response);
                   8297:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8298:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8299:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8300:             my ($name,$value)=split('=',$item);
                   8301:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8302:         }
                   8303:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8304:             my ($name,$value)=split('=',$item);
                   8305:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8306:         }
                   8307:         return 'ok';
                   8308:     }
                   8309:     return $response;
                   8310: }
1.792     raeburn  8311: 
1.1010    raeburn  8312: sub auto_courserequest_checks {
                   8313:     my ($dom) = @_;
1.1020    raeburn  8314:     my ($homeserver,%validations);
                   8315:     if ($dom =~ /^$match_domain$/) {
                   8316:         $homeserver = &domain($dom,'primary');
                   8317:     }
                   8318:     unless ($homeserver eq 'no_host') {
                   8319:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8320:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8321:             my @items = split(/&/,$response);
                   8322:             foreach my $item (@items) {
                   8323:                 my ($key,$value) = split('=',$item);
                   8324:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8325:             }
                   8326:         }
                   8327:     }
1.1010    raeburn  8328:     return %validations; 
                   8329: }
                   8330: 
1.1020    raeburn  8331: sub auto_courserequest_validation {
1.1255    raeburn  8332:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8333:     my ($homeserver,$response);
                   8334:     if ($dom =~ /^$match_domain$/) {
                   8335:         $homeserver = &domain($dom,'primary');
                   8336:     }
1.1255    raeburn  8337:     unless ($homeserver eq 'no_host') {
                   8338:         my $customdata;
                   8339:         if (ref($custominfo) eq 'HASH') {
                   8340:             $customdata = &freeze_escape($custominfo);
                   8341:         }
1.1020    raeburn  8342:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8343:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  8344:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8345:                                     $customdata,$homeserver));
1.1020    raeburn  8346:     }
                   8347:     return $response;
                   8348: }
                   8349: 
1.777     albertel 8350: sub auto_validate_class_sec {
1.918     raeburn  8351:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8352:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8353:     my $ownerlist;
                   8354:     if (ref($owners) eq 'ARRAY') {
                   8355:         $ownerlist = join(',',@{$owners});
                   8356:     } else {
                   8357:         $ownerlist = $owners;
                   8358:     }
1.773     raeburn  8359:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8360:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8361:     return $response;
                   8362: }
                   8363: 
1.1248    raeburn  8364: sub auto_crsreq_update {
                   8365:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  8366:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  8367:     my ($homeserver,%crsreqresponse);
                   8368:     if ($cdom =~ /^$match_domain$/) {
                   8369:         $homeserver = &domain($cdom,'primary');
                   8370:     }
                   8371:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8372:         my $info;
                   8373:         if (ref($inbound) eq 'HASH') {
                   8374:             $info = &freeze_escape($inbound);
                   8375:         }
                   8376:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8377:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8378:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  8379:                             &escape($title).':'.&escape($code).':'.
                   8380:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   8381:                             $homeserver);
1.1248    raeburn  8382:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8383:             my @items = split(/&/,$response);
                   8384:             foreach my $item (@items) {
                   8385:                 my ($key,$value) = split('=',$item);
                   8386:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8387:             }
                   8388:         }
                   8389:     }
                   8390:     return \%crsreqresponse;
                   8391: }
                   8392: 
1.1305    raeburn  8393: sub auto_export_grades {
1.1309    raeburn  8394:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   8395:     my ($homeserver,%exportresponse);
                   8396:     if ($cdom =~ /^$match_domain$/) {
                   8397:         $homeserver = &domain($cdom,'primary');
                   8398:     }
                   8399:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8400:         my $info;
                   8401:         if (ref($inforef) eq 'HASH') {
                   8402:             $info = &freeze_escape($inforef);
                   8403:         }
                   8404:         if (ref($gradesref) eq 'HASH') {
                   8405:             my $grades = &freeze_escape($gradesref);
                   8406:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   8407:                                 $info.':'.$grades,$homeserver);
                   8408:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   8409:                 my @items = split(/&/,$response);
                   8410:                 foreach my $item (@items) {
                   8411:                     my ($key,$value) = split('=',$item);
                   8412:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   8413:                 }
                   8414:             }
                   8415:         }
                   8416:     }
                   8417:     return \%exportresponse;
1.1305    raeburn  8418: }
                   8419: 
1.1287    raeburn  8420: sub check_instcode_cloning {
                   8421:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   8422:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8423:         return;
                   8424:     }
                   8425:     my $canclone;
                   8426:     if (@{$code_order} > 0) {
                   8427:         my $instcoderegexp ='^';
                   8428:         my @clonecodes = split(/\&/,$cloner);
                   8429:         foreach my $item (@{$code_order}) {
                   8430:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   8431:                 foreach my $pair (@clonecodes) {
                   8432:                     my ($key,$val) = split(/\=/,$pair,2);
                   8433:                     $val = &unescape($val);
                   8434:                     if ($key eq $item) {
                   8435:                         $instcoderegexp .= '('.$val.')';
                   8436:                         last;
                   8437:                     }
                   8438:                 }
                   8439:             } else {
                   8440:                 $instcoderegexp .= $codedefaults->{$item};
                   8441:             }
                   8442:         }
                   8443:         $instcoderegexp .= '$';
                   8444:         my (@from,@to);
                   8445:         eval {
                   8446:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8447:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8448:         };
                   8449:         if ((@from > 0) && (@to > 0)) {
                   8450:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8451:             if (!@diffs) {
                   8452:                 $canclone = 1;
                   8453:             }
                   8454:         }
                   8455:     }
                   8456:     return $canclone;
                   8457: }
                   8458: 
                   8459: sub default_instcode_cloning {
                   8460:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   8461:     my (%codedefaults,@code_order,$canclone);
                   8462:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   8463:         %codedefaults = %{$codedefaultsref};
                   8464:         @code_order = @{$codeorderref};
                   8465:     } elsif ($clonedom) {
                   8466:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   8467:     }
                   8468:     if (($domdefclone) && (@code_order)) {
                   8469:         my @clonecodes = split(/\+/,$domdefclone);
                   8470:         my $instcoderegexp ='^';
                   8471:         foreach my $item (@code_order) {
                   8472:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   8473:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   8474:             } else {
                   8475:                 $instcoderegexp .= $codedefaults{$item};
                   8476:             }
                   8477:         }
                   8478:         $instcoderegexp .= '$';
                   8479:         my (@from,@to);
                   8480:         eval {
                   8481:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8482:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8483:         };
                   8484:         if ((@from > 0) && (@to > 0)) {
                   8485:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8486:             if (!@diffs) {
                   8487:                 $canclone = 1;
                   8488:             }
                   8489:         }
                   8490:     }
                   8491:     return $canclone;
                   8492: }
                   8493: 
1.679     raeburn  8494: # ------------------------------------------------------- Course Group routines
                   8495: 
                   8496: sub get_coursegroups {
1.809     raeburn  8497:     my ($cdom,$cnum,$group,$namespace) = @_;
                   8498:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  8499: }
                   8500: 
1.679     raeburn  8501: sub modify_coursegroup {
                   8502:     my ($cdom,$cnum,$groupsettings) = @_;
                   8503:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   8504: }
                   8505: 
1.809     raeburn  8506: sub toggle_coursegroup_status {
                   8507:     my ($cdom,$cnum,$group,$action) = @_;
                   8508:     my ($from_namespace,$to_namespace);
                   8509:     if ($action eq 'delete') {
                   8510:         $from_namespace = 'coursegroups';
                   8511:         $to_namespace = 'deleted_groups';
                   8512:     } else {
                   8513:         $from_namespace = 'deleted_groups';
                   8514:         $to_namespace = 'coursegroups';
                   8515:     }
                   8516:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  8517:     if (my $tmp = &error(%curr_group)) {
                   8518:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   8519:         return ('read error',$tmp);
                   8520:     } else {
                   8521:         my %savedsettings = %curr_group; 
1.809     raeburn  8522:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  8523:         my $deloutcome;
                   8524:         if ($result eq 'ok') {
1.809     raeburn  8525:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  8526:         } else {
                   8527:             return ('write error',$result);
                   8528:         }
                   8529:         if ($deloutcome eq 'ok') {
                   8530:             return 'ok';
                   8531:         } else {
                   8532:             return ('delete error',$deloutcome);
                   8533:         }
                   8534:     }
                   8535: }
                   8536: 
1.679     raeburn  8537: sub modify_group_roles {
1.957     raeburn  8538:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  8539:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   8540:     my $role = 'gr/'.&escape($userprivs);
                   8541:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  8542:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  8543:     if ($result eq 'ok') {
                   8544:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   8545:     }
1.679     raeburn  8546:     return $result;
                   8547: }
                   8548: 
                   8549: sub modify_coursegroup_membership {
                   8550:     my ($cdom,$cnum,$membership) = @_;
                   8551:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   8552:     return $result;
                   8553: }
                   8554: 
1.682     raeburn  8555: sub get_active_groups {
                   8556:     my ($udom,$uname,$cdom,$cnum) = @_;
                   8557:     my $now = time;
                   8558:     my %groups = ();
                   8559:     foreach my $key (keys(%env)) {
1.811     albertel 8560:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  8561:             my ($start,$end) = split(/\./,$env{$key});
                   8562:             if (($end!=0) && ($end<$now)) { next; }
                   8563:             if (($start!=0) && ($start>$now)) { next; }
                   8564:             if ($1 eq $cdom && $2 eq $cnum) {
                   8565:                 $groups{$3} = $env{$key} ;
                   8566:             }
                   8567:         }
                   8568:     }
                   8569:     return %groups;
                   8570: }
                   8571: 
1.683     raeburn  8572: sub get_group_membership {
                   8573:     my ($cdom,$cnum,$group) = @_;
                   8574:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   8575: }
                   8576: 
                   8577: sub get_users_groups {
                   8578:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  8579:     my @usersgroups;
1.683     raeburn  8580:     my $cachetime=1800;
                   8581: 
                   8582:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  8583:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   8584:     if (defined($cached)) {
1.734     albertel 8585:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  8586:     } else {  
                   8587:         $grouplist = '';
1.816     raeburn  8588:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  8589:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  8590:         my $access_end = $env{'course.'.$courseid.
                   8591:                               '.default_enrollment_end_date'};
                   8592:         my $now = time;
                   8593:         foreach my $key (keys(%roleshash)) {
                   8594:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   8595:                 my $group = $1;
                   8596:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   8597:                     my $start = $2;
                   8598:                     my $end = $1;
                   8599:                     if ($start == -1) { next; } # deleted from group
                   8600:                     if (($start!=0) && ($start>$now)) { next; }
                   8601:                     if (($end!=0) && ($end<$now)) {
                   8602:                         if ($access_end && $access_end < $now) {
                   8603:                             if ($access_end - $end < 86400) {
                   8604:                                 push(@usersgroups,$group);
1.733     raeburn  8605:                             }
                   8606:                         }
1.817     raeburn  8607:                         next;
1.733     raeburn  8608:                     }
1.817     raeburn  8609:                     push(@usersgroups,$group);
1.683     raeburn  8610:                 }
                   8611:             }
                   8612:         }
1.817     raeburn  8613:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8614:         $grouplist = join(':',@usersgroups);
                   8615:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8616:     }
1.733     raeburn  8617:     return @usersgroups;
1.683     raeburn  8618: }
                   8619: 
                   8620: sub devalidate_getgroups_cache {
                   8621:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8622:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8623: 
1.683     raeburn  8624:     my $hashid="$udom:$uname:$courseid";
                   8625:     &devalidate_cache_new('getgroups',$hashid);
                   8626: }
                   8627: 
1.12      www      8628: # ------------------------------------------------------------------ Plain Text
                   8629: 
                   8630: sub plaintext {
1.988     raeburn  8631:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8632:     if ($short =~ m{^cr/}) {
1.758     albertel 8633: 	return (split('/',$short))[-1];
                   8634:     }
1.742     raeburn  8635:     if (!defined($cid)) {
                   8636:         $cid = $env{'request.course.id'};
                   8637:     }
                   8638:     my %rolenames = (
1.1008    raeburn  8639:                       Course    => 'std',
                   8640:                       Community => 'alt1',
1.1305    raeburn  8641:                       Placement => 'std',
1.742     raeburn  8642:                     );
1.1037    raeburn  8643:     if ($cid ne '') {
                   8644:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8645:             unless ($forcedefault) {
                   8646:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8647:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8648:                 return &Apache::lonlocal::mt($roletext);
                   8649:             }
                   8650:         }
                   8651:     }
                   8652:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8653:         (defined($rolenames{$type})) && 
                   8654:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8655:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8656:     } elsif ($cid ne '') {
                   8657:         my $crstype = $env{'course.'.$cid.'.type'};
                   8658:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8659:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8660:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8661:         }
1.742     raeburn  8662:     }
1.1037    raeburn  8663:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8664: }
                   8665: 
                   8666: # ----------------------------------------------------------------- Assign Role
                   8667: 
                   8668: sub assignrole {
1.957     raeburn  8669:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8670:         $context)=@_;
1.21      www      8671:     my $mrole;
                   8672:     if ($role =~ /^cr\//) {
1.393     www      8673:         my $cwosec=$url;
1.811     albertel 8674:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8675: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8676:            my $refused = 1;
                   8677:            if ($context eq 'requestcourses') {
                   8678:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8679:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8680:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8681:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8682:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8683:                            if ($crsenv{'internal.courseowner'} eq
                   8684:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8685:                                $refused = '';
                   8686:                            }
                   8687:                        }
                   8688:                    }
                   8689:                }
                   8690:            }
                   8691:            if ($refused) {
                   8692:                &logthis('Refused custom assignrole: '.
                   8693:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8694:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8695:                return 'refused';
                   8696:            }
1.104     www      8697:         }
1.21      www      8698:         $mrole='cr';
1.678     raeburn  8699:     } elsif ($role =~ /^gr\//) {
                   8700:         my $cwogrp=$url;
1.811     albertel 8701:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8702:         unless (&allowed('mdg',$cwogrp)) {
                   8703:             &logthis('Refused group assignrole: '.
                   8704:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   8705:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   8706:             return 'refused';
                   8707:         }
                   8708:         $mrole='gr';
1.21      www      8709:     } else {
1.82      www      8710:         my $cwosec=$url;
1.811     albertel 8711:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  8712:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   8713:             my $refused;
                   8714:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   8715:                 if (!(&allowed('c'.$role,$url))) {
                   8716:                     $refused = 1;
                   8717:                 }
                   8718:             } else {
                   8719:                 $refused = 1;
                   8720:             }
1.947     raeburn  8721:             if ($refused) {
1.1045    raeburn  8722:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8723:                 if (!$selfenroll && $context eq 'course') {
                   8724:                     my %crsenv;
                   8725:                     if ($role eq 'cc' || $role eq 'co') {
                   8726:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8727:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   8728:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   8729:                                 if ($crsenv{'internal.courseowner'} eq 
                   8730:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8731:                                     $refused = '';
                   8732:                                 }
                   8733:                             }
                   8734:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   8735:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   8736:                                 if ($crsenv{'internal.courseowner'} eq 
                   8737:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8738:                                     $refused = '';
                   8739:                                 }
                   8740:                             }
                   8741:                         }
                   8742:                     }
                   8743:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8744:                     $refused = '';
1.1017    raeburn  8745:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8746:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8747:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8748:                         my $wrongcc;
                   8749:                         if ($cnum =~ /^$match_community$/) {
                   8750:                             $wrongcc = 1 if ($role eq 'cc');
                   8751:                         } else {
                   8752:                             $wrongcc = 1 if ($role eq 'co');
                   8753:                         }
                   8754:                         unless ($wrongcc) {
                   8755:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8756:                             if ($crsenv{'internal.courseowner'} eq 
                   8757:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8758:                                 $refused = '';
                   8759:                             }
1.1017    raeburn  8760:                         }
                   8761:                     }
1.1183    raeburn  8762:                 } elsif ($context eq 'requestauthor') {
                   8763:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   8764:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8765:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8766:                             $refused = '';
                   8767:                         } else {
                   8768:                             my %domdefaults = &get_domain_defaults($udom);
                   8769:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   8770:                                 my $checkbystatus;
                   8771:                                 if ($env{'user.adv'}) { 
                   8772:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8773:                                     if ($disposition eq 'automatic') {
                   8774:                                         $refused = '';
                   8775:                                     } elsif ($disposition eq '') {
                   8776:                                         $checkbystatus = 1;
                   8777:                                     } 
                   8778:                                 } else {
                   8779:                                     $checkbystatus = 1;
                   8780:                                 }
                   8781:                                 if ($checkbystatus) {
                   8782:                                     if ($env{'environment.inststatus'}) {
                   8783:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8784:                                         foreach my $type (@inststatuses) {
                   8785:                                             if (($type ne '') &&
                   8786:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   8787:                                                 $refused = '';
                   8788:                                             }
                   8789:                                         }
                   8790:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8791:                                         $refused = '';
                   8792:                                     }
                   8793:                                 }
                   8794:                             }
                   8795:                         }
                   8796:                     }
1.1017    raeburn  8797:                 }
                   8798:                 if ($refused) {
1.947     raeburn  8799:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8800:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8801: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8802:                     return 'refused';
                   8803:                 }
1.932     raeburn  8804:             }
1.1131    raeburn  8805:         } elsif ($role eq 'au') {
                   8806:             if ($url ne '/'.$udom.'/') {
                   8807:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8808:                          ' to assign author role for '.$uname.':'.$udom.
                   8809:                          ' in domain: '.$url.' refused (wrong domain).');
                   8810:                 return 'refused';
                   8811:             }
1.104     www      8812:         }
1.21      www      8813:         $mrole=$role;
                   8814:     }
1.620     albertel 8815:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8816:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8817:     if ($end) { $command.='_'.$end; }
1.21      www      8818:     if ($start) {
                   8819: 	if ($end) { 
1.81      www      8820:            $command.='_'.$start; 
1.21      www      8821:         } else {
1.81      www      8822:            $command.='_0_'.$start;
1.21      www      8823:         }
                   8824:     }
1.739     raeburn  8825:     my $origstart = $start;
                   8826:     my $origend = $end;
1.957     raeburn  8827:     my $delflag;
1.357     www      8828: # actually delete
                   8829:     if ($deleteflag) {
1.373     www      8830: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8831: # modify command to delete the role
1.620     albertel 8832:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8833:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8834: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8835: # set start and finish to negative values for userrolelog
                   8836:            $start=-1;
                   8837:            $end=-1;
1.957     raeburn  8838:            $delflag = 1;
1.357     www      8839:         }
                   8840:     }
                   8841: # send command
1.349     www      8842:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8843: # log new user role if status is ok
1.349     www      8844:     if ($answer eq 'ok') {
1.663     raeburn  8845: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  8846:         if (($role eq 'cc') || ($role eq 'in') ||
                   8847:             ($role eq 'ep') || ($role eq 'ad') ||
                   8848:             ($role eq 'ta') || ($role eq 'st') ||
                   8849:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8850:             ($role eq 'co')) {
1.1200    raeburn  8851: # for course roles, perform group memberships changes triggered by role change.
                   8852:             unless ($role =~ /^gr/) {
                   8853:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8854:                                                  $origstart,$selfenroll,$context);
                   8855:             }
1.1184    raeburn  8856:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8857:                            $selfenroll,$context);
                   8858:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8859:                  ($role eq 'au') || ($role eq 'dc')) {
                   8860:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8861:                            $context);
                   8862:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8863:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8864:                              $context); 
                   8865:         }
1.1053    raeburn  8866:         if ($role eq 'cc') {
                   8867:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8868:         }
1.349     www      8869:     }
                   8870:     return $answer;
1.169     harris41 8871: }
                   8872: 
1.1053    raeburn  8873: sub autoupdate_coowners {
                   8874:     my ($url,$end,$start,$uname,$udom) = @_;
                   8875:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8876:     if (($cdom ne '') && ($cnum ne '')) {
                   8877:         my $now = time;
                   8878:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8879:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8880:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8881:             my $instcode = $coursehash{'internal.coursecode'};
                   8882:             if ($instcode ne '') {
1.1056    raeburn  8883:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8884:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8885:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8886:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8887:                         if ($result eq 'valid') {
                   8888:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8889:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8890:                                     push(@newcoowners,$coowner);
                   8891:                                 }
                   8892:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8893:                                     push(@newcoowners,$uname.':'.$udom);
                   8894:                                 }
                   8895:                                 @newcoowners = sort(@newcoowners);
                   8896:                             } else {
                   8897:                                 push(@newcoowners,$uname.':'.$udom);
                   8898:                             }
                   8899:                         } else {
                   8900:                             if ($coursehash{'internal.co-owners'}) {
                   8901:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8902:                                     unless ($coowner eq $uname.':'.$udom) {
                   8903:                                         push(@newcoowners,$coowner);
                   8904:                                     }
                   8905:                                 }
                   8906:                                 unless (@newcoowners > 0) {
                   8907:                                     $delcoowners = 1;
                   8908:                                     $coowners = '';
                   8909:                                 }
                   8910:                             }
                   8911:                         }
                   8912:                         if (@newcoowners || $delcoowners) {
                   8913:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8914:                                             $delcoowners,@newcoowners);
                   8915:                         }
                   8916:                     }
                   8917:                 }
                   8918:             }
                   8919:         }
                   8920:     }
                   8921: }
                   8922: 
                   8923: sub store_coowners {
                   8924:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8925:     my $cid = $cdom.'_'.$cnum;
                   8926:     my ($coowners,$delresult,$putresult);
                   8927:     if (@newcoowners) {
                   8928:         $coowners = join(',',@newcoowners);
                   8929:         my %coownershash = (
                   8930:                             'internal.co-owners' => $coowners,
                   8931:                            );
                   8932:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8933:         if ($putresult eq 'ok') {
                   8934:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8935:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8936:             }
                   8937:         }
                   8938:     }
                   8939:     if ($delcoowners) {
                   8940:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8941:         if ($delresult eq 'ok') {
                   8942:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8943:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8944:             }
                   8945:         }
                   8946:     }
                   8947:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8948:         my %crsinfo =
                   8949:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8950:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8951:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8952:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8953:         }
                   8954:     }
                   8955: }
                   8956: 
1.169     harris41 8957: # -------------------------------------------------- Modify user authentication
1.197     www      8958: # Overrides without validation
                   8959: 
1.169     harris41 8960: sub modifyuserauth {
                   8961:     my ($udom,$uname,$umode,$upass)=@_;
                   8962:     my $uhome=&homeserver($uname,$udom);
1.197     www      8963:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8964:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8965:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8966:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8967:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8968: 		     &escape($upass),$uhome);
1.620     albertel 8969:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8970:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8971:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8972:     &log($udom,,$uname,$uhome,
1.620     albertel 8973:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8974:                                      $env{'user.name'}.', '.$umode.
1.197     www      8975:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8976:     unless ($reply eq 'ok') {
1.197     www      8977:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8978: 	return 'error: '.$reply;
                   8979:     }   
1.170     harris41 8980:     return 'ok';
1.80      www      8981: }
                   8982: 
1.81      www      8983: # --------------------------------------------------------------- Modify a user
1.80      www      8984: 
1.81      www      8985: sub modifyuser {
1.206     matthew  8986:     my ($udom,    $uname, $uid,
                   8987:         $umode,   $upass, $first,
                   8988:         $middle,  $last,  $gene,
1.1058    raeburn  8989:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8990:     $udom= &LONCAPA::clean_domain($udom);
                   8991:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8992:     my $showcandelete = 'none';
                   8993:     if (ref($candelete) eq 'ARRAY') {
                   8994:         if (@{$candelete} > 0) {
                   8995:             $showcandelete = join(', ',@{$candelete});
                   8996:         }
                   8997:     }
1.81      www      8998:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8999:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9000: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9001:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9002:                                      ' desiredhome not specified'). 
1.620     albertel 9003:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9004:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9005:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9006:     my $newuser;
                   9007:     if ($uhome eq 'no_host') {
                   9008:         $newuser = 1;
                   9009:     }
1.80      www      9010: # ----------------------------------------------------------------- Create User
1.406     albertel 9011:     if (($uhome eq 'no_host') && 
                   9012: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      9013:         my $unhome='';
1.844     albertel 9014:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9015:             $unhome = $desiredhome;
1.620     albertel 9016: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9017: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9018:         } else { # load balancing routine for determining $unhome
1.81      www      9019:             my $loadm=10000000;
1.841     albertel 9020: 	    my %servers = &get_servers($udom,'library');
                   9021: 	    foreach my $tryserver (keys(%servers)) {
                   9022: 		my $answer=reply('load',$tryserver);
                   9023: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9024: 		    $loadm=$answer;
                   9025: 		    $unhome=$tryserver;
                   9026: 		}
1.80      www      9027: 	    }
                   9028:         }
                   9029:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9030: 	    return 'error: unable to find a home server for '.$uname.
                   9031:                    ' in domain '.$udom;
1.80      www      9032:         }
                   9033:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9034:                          &escape($upass),$unhome);
                   9035: 	unless ($reply eq 'ok') {
                   9036:             return 'error: '.$reply;
                   9037:         }   
1.230     stredwic 9038:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9039:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9040: 	    return 'error: unable verify users home machine.';
1.80      www      9041:         }
1.209     matthew  9042:     }   # End of creation of new user
1.80      www      9043: # ---------------------------------------------------------------------- Add ID
                   9044:     if ($uid) {
                   9045:        $uid=~tr/A-Z/a-z/;
                   9046:        my %uidhash=&idrget($udom,$uname);
1.196     www      9047:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9048:          && (!$forceid)) {
1.80      www      9049: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9050: 	      return 'error: user id "'.$uid.'" does not match '.
                   9051:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9052:           }
                   9053:        } else {
1.1300    raeburn  9054: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      9055:        }
                   9056:     }
                   9057: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9058:     my @tmp=&get('environment',
1.899     raeburn  9059: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9060:                     'permanentemail','inststatus'],
1.134     albertel 9061: 		   $udom,$uname);
1.1075    raeburn  9062:     my (%names,%oldnames);
1.313     matthew  9063:     if ($tmp[0] =~ m/^error:.*/) { 
                   9064:         %names=(); 
                   9065:     } else {
                   9066:         %names = @tmp;
1.1075    raeburn  9067:         %oldnames = %names;
1.313     matthew  9068:     }
1.388     www      9069: #
1.1058    raeburn  9070: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9071: # of users did not contain them), do not overwrite existing values
                   9072: # unless field is in $candelete array ref.  
                   9073: #
                   9074: 
                   9075:     my @fields = ('firstname','middlename','lastname','generation',
                   9076:                   'permanentemail','id');
                   9077:     my %newvalues;
                   9078:     if (ref($candelete) eq 'ARRAY') {
                   9079:         foreach my $field (@fields) {
                   9080:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9081:                 if ($field eq 'firstname') {
                   9082:                     $names{$field} = $first;
                   9083:                 } elsif ($field eq 'middlename') {
                   9084:                     $names{$field} = $middle;
                   9085:                 } elsif ($field eq 'lastname') {
                   9086:                     $names{$field} = $last;
                   9087:                 } elsif ($field eq 'generation') { 
                   9088:                     $names{$field} = $gene;
                   9089:                 } elsif ($field eq 'permanentemail') {
                   9090:                     $names{$field} = $email;
                   9091:                 } elsif ($field eq 'id') {
                   9092:                     $names{$field}  = $uid;
                   9093:                 }
                   9094:             }
                   9095:         }
                   9096:     }
1.388     www      9097:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9098:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9099:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9100:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9101:     if ($email) {
                   9102:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9103:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9104:     }
1.899     raeburn  9105:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9106:     if (defined($inststatus)) {
                   9107:         $names{'inststatus'} = '';
                   9108:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9109:         if (ref($usertypes) eq 'HASH') {
                   9110:             my @okstatuses; 
                   9111:             foreach my $item (split(/:/,$inststatus)) {
                   9112:                 if (defined($usertypes->{$item})) {
                   9113:                     push(@okstatuses,$item);  
                   9114:                 }
                   9115:             }
                   9116:             if (@okstatuses) {
                   9117:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9118:             }
                   9119:         }
                   9120:     }
1.1075    raeburn  9121:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9122:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9123:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9124:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9125:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9126:     } else {
                   9127:         $logmsg .= ' during self creation';
                   9128:     }
1.1075    raeburn  9129:     my $changed;
                   9130:     if ($newuser) {
                   9131:         $changed = 1;
                   9132:     } else {
                   9133:         foreach my $field (@fields) {
                   9134:             if ($names{$field} ne $oldnames{$field}) {
                   9135:                 $changed = 1;
                   9136:                 last;
                   9137:             }
                   9138:         }
                   9139:     }
                   9140:     unless ($changed) {
                   9141:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9142:         &logthis($logmsg);
                   9143:         return 'ok';
                   9144:     }
                   9145:     my $reply = &put('environment', \%names, $udom,$uname);
                   9146:     if ($reply ne 'ok') { 
                   9147:         return 'error: '.$reply;
                   9148:     }
1.1087    raeburn  9149:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9150:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9151:     }
1.1075    raeburn  9152:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9153:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9154:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9155:     &logthis($logmsg);
1.134     albertel 9156:     return 'ok';
1.80      www      9157: }
                   9158: 
1.81      www      9159: # -------------------------------------------------------------- Modify student
1.80      www      9160: 
1.81      www      9161: sub modifystudent {
                   9162:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9163:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314    raeburn  9164:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9165:     if (!$cid) {
1.620     albertel 9166: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9167: 	    return 'not_in_class';
                   9168: 	}
1.80      www      9169:     }
                   9170: # --------------------------------------------------------------- Make the user
1.81      www      9171:     my $reply=&modifyuser
1.209     matthew  9172: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9173:          $desiredhome,$email,$inststatus);
1.80      www      9174:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9175:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  9176:     # student's environment
1.297     matthew  9177:     $uid = undef if (!$forceid);
1.455     albertel 9178:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  9179:                                         $gene,$usec,$end,$start,$type,$locktype,
1.1314    raeburn  9180:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9181:     return $reply;
                   9182: }
                   9183: 
                   9184: sub modify_student_enrollment {
1.1216    raeburn  9185:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314    raeburn  9186:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9187:     my ($cdom,$cnum,$chome);
                   9188:     if (!$cid) {
1.620     albertel 9189: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9190: 	    return 'not_in_class';
                   9191: 	}
1.620     albertel 9192: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9193: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9194:     } else {
                   9195: 	($cdom,$cnum)=split(/_/,$cid);
                   9196:     }
1.620     albertel 9197:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9198:     if (!$chome) {
1.457     raeburn  9199: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9200:     }
1.455     albertel 9201:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9202:     # Make sure the user exists
1.81      www      9203:     my $uhome=&homeserver($uname,$udom);
                   9204:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9205: 	return 'error: no such user';
                   9206:     }
1.297     matthew  9207:     # Get student data if we were not given enough information
                   9208:     if (!defined($first)  || $first  eq '' || 
                   9209:         !defined($last)   || $last   eq '' || 
                   9210:         !defined($uid)    || $uid    eq '' || 
                   9211:         !defined($middle) || $middle eq '' || 
                   9212:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9213:         # They did not supply us with enough data to enroll the student, so
                   9214:         # we need to pick up more information.
1.297     matthew  9215:         my %tmp = &get('environment',
1.294     matthew  9216:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9217:                        ,$udom,$uname);
                   9218: 
1.800     albertel 9219:         #foreach my $key (keys(%tmp)) {
                   9220:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9221:         #}
1.294     matthew  9222:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9223:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9224:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9225:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9226:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9227:     }
1.556     albertel 9228:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9229:     my $user = "$uname:$udom";
                   9230:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9231:     my $reply=cput('classlist',
1.1148    raeburn  9232: 		   {$user => 
1.1314    raeburn  9233: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 9234: 		   $cdom,$cnum);
1.1148    raeburn  9235:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9236:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9237:     } else { 
1.81      www      9238: 	return 'error: '.$reply;
                   9239:     }
1.297     matthew  9240:     # Add student role to user
1.83      www      9241:     my $uurl='/'.$cid;
1.81      www      9242:     $uurl=~s/\_/\//g;
                   9243:     if ($usec) {
                   9244: 	$uurl.='/'.$usec;
                   9245:     }
1.1148    raeburn  9246:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9247:                              $selfenroll,$context);
                   9248:     if ($result ne 'ok') {
                   9249:         if ($old_entry{$user} ne '') {
                   9250:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9251:         } else {
                   9252:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9253:         }
                   9254:     }
                   9255:     return $result; 
1.21      www      9256: }
                   9257: 
1.556     albertel 9258: sub format_name {
                   9259:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9260:     my $name;
                   9261:     if ($first ne 'lastname') {
                   9262: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9263:     } else {
                   9264: 	if ($lastname=~/\S/) {
                   9265: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9266: 	    $name=~s/\s+,/,/;
                   9267: 	} else {
                   9268: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9269: 	}
                   9270:     }
                   9271:     $name=~s/^\s+//;
                   9272:     $name=~s/\s+$//;
                   9273:     $name=~s/\s+/ /g;
                   9274:     return $name;
                   9275: }
                   9276: 
1.84      www      9277: # ------------------------------------------------- Write to course preferences
                   9278: 
                   9279: sub writecoursepref {
                   9280:     my ($courseid,%prefs)=@_;
                   9281:     $courseid=~s/^\///;
                   9282:     $courseid=~s/\_/\//g;
                   9283:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9284:     my $chome=homeserver($cnum,$cdomain);
                   9285:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9286: 	return 'error: no such course';
                   9287:     }
                   9288:     my $cstring='';
1.800     albertel 9289:     foreach my $pref (keys(%prefs)) {
                   9290: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9291:     }
1.84      www      9292:     $cstring=~s/\&$//;
                   9293:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9294: }
                   9295: 
                   9296: # ---------------------------------------------------------- Make/modify course
                   9297: 
                   9298: sub createcourse {
1.741     raeburn  9299:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  9300:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      9301:     $url=&declutter($url);
                   9302:     my $cid='';
1.1028    raeburn  9303:     if ($context eq 'requestcourses') {
                   9304:         my $can_create = 0;
                   9305:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9306:         if ($udom eq $ownerdom) {
                   9307:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   9308:                                   $context)) {
                   9309:                 $can_create = 1;
                   9310:             }
                   9311:         } else {
                   9312:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9313:                                            $category);
                   9314:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   9315:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   9316:                 if (@curr > 0) {
                   9317:                     my @options = qw(approval validate autolimit);
                   9318:                     my $optregex = join('|',@options);
                   9319:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   9320:                         $can_create = 1;
                   9321:                     }
                   9322:                 }
                   9323:             }
                   9324:         }
                   9325:         if ($can_create) {
                   9326:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   9327:                 unless (&allowed('ccc',$udom)) {
                   9328:                     return 'refused'; 
                   9329:                 }
1.1017    raeburn  9330:             }
                   9331:         } else {
                   9332:             return 'refused';
                   9333:         }
1.1028    raeburn  9334:     } elsif (!&allowed('ccc',$udom)) {
                   9335:         return 'refused';
1.84      www      9336:     }
1.1011    raeburn  9337: # --------------------------------------------------------------- Get Unique ID
                   9338:     my $uname;
                   9339:     if ($cnum =~ /^$match_courseid$/) {
                   9340:         my $chome=&homeserver($cnum,$udom,'true');
                   9341:         if (($chome eq '') || ($chome eq 'no_host')) {
                   9342:             $uname = $cnum;
                   9343:         } else {
1.1038    raeburn  9344:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9345:         }
                   9346:     } else {
1.1038    raeburn  9347:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9348:     }
                   9349:     return $uname if ($uname =~ /^error/);
                   9350: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  9351:     if (!defined($course_server)) {
                   9352:         if (defined(&domain($udom,'primary'))) {
                   9353:             $course_server = &domain($udom,'primary');
                   9354:         } else {
                   9355:             $course_server = $env{'user.home'}; 
                   9356:         }
                   9357:     }
                   9358:     my %host_servers =
                   9359:         &Apache::lonnet::get_servers($udom,'library');
                   9360:     unless ($host_servers{$course_server}) {
                   9361:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  9362:     }
1.84      www      9363: # ------------------------------------------------------------- Make the course
                   9364:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  9365:                       $course_server);
1.84      www      9366:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  9367:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      9368:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9369: 	return 'error: no such course';
                   9370:     }
1.271     www      9371: # ----------------------------------------------------------------- Course made
1.516     raeburn  9372: # log existence
1.1029    raeburn  9373:     my $now = time;
1.918     raeburn  9374:     my $newcourse = {
                   9375:                     $udom.'_'.$uname => {
1.921     raeburn  9376:                                      description => $description,
                   9377:                                      inst_code   => $inst_code,
                   9378:                                      owner       => $course_owner,
                   9379:                                      type        => $crstype,
1.1029    raeburn  9380:                                      creator     => $env{'user.name'}.':'.
                   9381:                                                     $env{'user.domain'},
                   9382:                                      created     => $now,
                   9383:                                      context     => $context,
1.918     raeburn  9384:                                                 },
                   9385:                     };
1.921     raeburn  9386:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      9387: # set toplevel url
1.271     www      9388:     my $topurl=$url;
                   9389:     unless ($nonstandard) {
                   9390: # ------------------------------------------ For standard courses, make top url
                   9391:         my $mapurl=&clutter($url);
1.278     www      9392:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 9393:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      9394: <map>
                   9395: <resource id="1" type="start"></resource>
                   9396: <resource id="2" src="$mapurl"></resource>
                   9397: <resource id="3" type="finish"></resource>
                   9398: <link index="1" from="1" to="2"></link>
                   9399: <link index="2" from="2" to="3"></link>
                   9400: </map>
                   9401: ENDINITMAP
                   9402:         $topurl=&declutter(
1.638     albertel 9403:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      9404:                           );
                   9405:     }
                   9406: # ----------------------------------------------------------- Write preferences
1.84      www      9407:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  9408:                      ('description'              => $description,
                   9409:                       'url'                      => $topurl,
                   9410:                       'internal.creator'         => $env{'user.name'}.':'.
                   9411:                                                     $env{'user.domain'},
                   9412:                       'internal.created'         => $now,
                   9413:                       'internal.creationcontext' => $context)
                   9414:                     );
1.84      www      9415:     return '/'.$udom.'/'.$uname;
                   9416: }
                   9417: 
1.1011    raeburn  9418: # ------------------------------------------------------------------- Create ID
                   9419: sub generate_coursenum {
1.1038    raeburn  9420:     my ($udom,$crstype) = @_;
1.1011    raeburn  9421:     my $domdesc = &domain($udom);
                   9422:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  9423:     my $first;
                   9424:     if ($crstype eq 'Community') {
                   9425:         $first = '0';
                   9426:     } else {
                   9427:         $first = int(1+rand(9)); 
                   9428:     } 
                   9429:     my $uname=$first.
1.1011    raeburn  9430:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9431:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9432:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9433: # ----------------------------------------------- Make sure that does not exist
                   9434:     my $uhome=&homeserver($uname,$udom,'true');
                   9435:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  9436:         if ($crstype eq 'Community') {
                   9437:             $first = '0';
                   9438:         } else {
                   9439:             $first = int(1+rand(9));
                   9440:         }
                   9441:         $uname=$first.
1.1011    raeburn  9442:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9443:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9444:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9445:         $uhome=&homeserver($uname,$udom,'true');
                   9446:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   9447:             return 'error: unable to generate unique course-ID';
                   9448:         }
                   9449:     }
                   9450:     return $uname;
                   9451: }
                   9452: 
1.813     albertel 9453: sub is_course {
1.1167    droeschl 9454:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   9455:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   9456: 
                   9457:     return unless $cdom and $cnum;
                   9458: 
                   9459:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   9460:         '.');
                   9461: 
1.1219    raeburn  9462:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 9463:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 9464: }
                   9465: 
1.1015    raeburn  9466: sub store_userdata {
                   9467:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  9468:     my $result;
1.1016    raeburn  9469:     if ($datakey ne '') {
1.1013    raeburn  9470:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  9471:             if ($udom eq '' || $uname eq '') {
                   9472:                 $udom = $env{'user.domain'};
                   9473:                 $uname = $env{'user.name'};
                   9474:             }
                   9475:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  9476:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   9477:                 $result = 'error: no_host';
                   9478:             } else {
                   9479:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   9480:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   9481: 
                   9482:                 my $namevalue='';
                   9483:                 foreach my $key (keys(%{$storehash})) {
                   9484:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   9485:                 }
                   9486:                 $namevalue=~s/\&$//;
1.1224    raeburn  9487:                 unless ($namespace eq 'courserequests') {
                   9488:                     $datakey = &escape($datakey);
                   9489:                 }
1.1105    raeburn  9490:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   9491:                                   $namevalue,$uhome);
1.1013    raeburn  9492:             }
                   9493:         } else {
                   9494:             $result = 'error: data to store was not a hash reference'; 
                   9495:         }
                   9496:     } else {
                   9497:         $result= 'error: invalid requestkey'; 
                   9498:     }
                   9499:     return $result;
                   9500: }
                   9501: 
1.21      www      9502: # ---------------------------------------------------------- Assign Custom Role
                   9503: 
                   9504: sub assigncustomrole {
1.957     raeburn  9505:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9506:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  9507:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      9508: }
                   9509: 
                   9510: # ----------------------------------------------------------------- Revoke Role
                   9511: 
                   9512: sub revokerole {
1.957     raeburn  9513:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9514:     my $now=time;
1.965     raeburn  9515:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      9516: }
                   9517: 
                   9518: # ---------------------------------------------------------- Revoke Custom Role
                   9519: 
                   9520: sub revokecustomrole {
1.957     raeburn  9521:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9522:     my $now=time;
1.357     www      9523:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  9524:            $deleteflag,$selfenroll,$context);
1.17      www      9525: }
                   9526: 
1.533     banghart 9527: # ------------------------------------------------------------ Disk usage
1.535     albertel 9528: sub diskusage {
1.955     raeburn  9529:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   9530:     $directorypath =~ s/\/$//;
                   9531:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   9532:                        .&escape($getpropath).':'.&escape($uname).':'
                   9533:                        .&escape($udom),homeserver($uname,$udom));
                   9534:     if ($listing eq 'unknown_cmd') {
                   9535:         if ($getpropath) {
                   9536:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   9537:         }
                   9538:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   9539:     }
1.514     albertel 9540:     return $listing;
1.512     banghart 9541: }
                   9542: 
1.566     banghart 9543: sub is_locked {
1.1096    raeburn  9544:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 9545:     my @check;
                   9546:     my $is_locked;
1.1093    raeburn  9547:     push (@check,$file_name);
1.613     albertel 9548:     my %locked = &get('file_permissions',\@check,
1.620     albertel 9549: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 9550:     my ($tmp)=keys(%locked);
                   9551:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  9552:     
1.566     banghart 9553:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  9554:         $is_locked = 'false';
                   9555:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  9556:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  9557:                $is_locked = 'true';
1.1096    raeburn  9558:                if (ref($which) eq 'ARRAY') {
                   9559:                    push(@{$which},$entry);
                   9560:                } else {
                   9561:                    last;
                   9562:                }
1.745     raeburn  9563:            }
                   9564:        }
1.566     banghart 9565:     } else {
                   9566:         $is_locked = 'false';
                   9567:     }
1.1093    raeburn  9568:     return $is_locked;
1.566     banghart 9569: }
                   9570: 
1.759     albertel 9571: sub declutter_portfile {
                   9572:     my ($file) = @_;
1.833     albertel 9573:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 9574:     return $file;
                   9575: }
                   9576: 
1.559     banghart 9577: # ------------------------------------------------------------- Mark as Read Only
                   9578: 
                   9579: sub mark_as_readonly {
                   9580:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 9581:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9582:     my ($tmp)=keys(%current_permissions);
                   9583:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 9584:     foreach my $file (@{$files}) {
1.759     albertel 9585: 	$file = &declutter_portfile($file);
1.561     banghart 9586:         push(@{$current_permissions{$file}},$what);
1.559     banghart 9587:     }
1.613     albertel 9588:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9589:     return;
                   9590: }
                   9591: 
1.572     banghart 9592: # ------------------------------------------------------------Save Selected Files
                   9593: 
                   9594: sub save_selected_files {
                   9595:     my ($user, $path, @files) = @_;
                   9596:     my $filename = $user."savedfiles";
1.573     banghart 9597:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 9598:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 9599:     foreach my $file (@files) {
1.620     albertel 9600:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 9601:     }
                   9602:     foreach my $file (@other_files) {
1.574     banghart 9603:         print (OUT $file."\n");
1.572     banghart 9604:     }
1.574     banghart 9605:     close (OUT);
1.572     banghart 9606:     return 'ok';
                   9607: }
                   9608: 
1.574     banghart 9609: sub clear_selected_files {
                   9610:     my ($user) = @_;
                   9611:     my $filename = $user."savedfiles";
1.1117    foxr     9612:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 9613:     print (OUT undef);
                   9614:     close (OUT);
                   9615:     return ("ok");    
                   9616: }
                   9617: 
1.572     banghart 9618: sub files_in_path {
                   9619:     my ($user, $path) = @_;
                   9620:     my $filename = $user."savedfiles";
                   9621:     my %return_files;
1.1117    foxr     9622:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 9623:     while (my $line_in = <IN>) {
1.574     banghart 9624:         chomp ($line_in);
                   9625:         my @paths_and_file = split (m!/!, $line_in);
                   9626:         my $file_part = pop (@paths_and_file);
                   9627:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9628:         $path_part.='/';
                   9629:         my $path_and_file = $path_part.$file_part;
                   9630:         if ($path_part eq $path) {
                   9631:             $return_files{$file_part}= 'selected';
                   9632:         }
                   9633:     }
1.574     banghart 9634:     close (IN);
                   9635:     return (\%return_files);
1.572     banghart 9636: }
                   9637: 
                   9638: # called in portfolio select mode, to show files selected NOT in current directory
                   9639: sub files_not_in_path {
                   9640:     my ($user, $path) = @_;
                   9641:     my $filename = $user."savedfiles";
                   9642:     my @return_files;
                   9643:     my $path_part;
1.1117    foxr     9644:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 9645:     while (my $line = <IN>) {
1.572     banghart 9646:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9647:         my @paths_and_file = split(m|/|, $line);
                   9648:         my $file_part = pop(@paths_and_file);
                   9649:         chomp($file_part);
                   9650:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9651:         $path_part .= '/';
                   9652:         my $path_and_file = $path_part.$file_part;
                   9653:         if ($path_part ne $path) {
1.800     albertel 9654:             push(@return_files, ($path_and_file));
1.572     banghart 9655:         }
                   9656:     }
1.800     albertel 9657:     close(OUT);
1.574     banghart 9658:     return (@return_files);
1.572     banghart 9659: }
                   9660: 
1.1273    raeburn  9661: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   9662:  
                   9663: sub portfiles_versioning {
                   9664:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   9665:     my $portfolio_root = '/userfiles/portfolio';
                   9666:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   9667:     foreach my $file (@{$portfiles}) {
                   9668:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   9669:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   9670:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   9671:         my $getpropath = 1;
                   9672:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   9673:                                              $stu_name,$getpropath);
                   9674:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   9675:         my $new_answer = 
                   9676:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   9677:         if ($new_answer ne 'problem getting file') {
                   9678:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   9679:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   9680:                               [$symb,$env{'request.course.id'},'graded']);
                   9681:         }
                   9682:     }
                   9683: }
                   9684: 
                   9685: sub get_next_version {
                   9686:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   9687:     my $version;
                   9688:     if (ref($dir_list) eq 'ARRAY') {
                   9689:         foreach my $row (@{$dir_list}) {
                   9690:             my ($file) = split(/\&/,$row,2);
                   9691:             my ($file_name,$file_version,$file_ext) =
                   9692:                 &file_name_version_ext($file);
                   9693:             if (($file_name eq $answer_name) &&
                   9694:                 ($file_ext eq $answer_ext)) {
                   9695:                      # gets here if filename and extension match,
                   9696:                      # regardless of version
                   9697:                 if ($file_version ne '') {
                   9698:                     # a versioned file is found  so save it for later
                   9699:                     if ($file_version > $version) {
                   9700:                         $version = $file_version;
                   9701:                     }
                   9702:                 }
                   9703:             }
                   9704:         }
                   9705:     }
                   9706:     $version ++;
                   9707:     return($version);
                   9708: }
                   9709: 
                   9710: sub version_selected_portfile {
                   9711:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   9712:     my ($answer_name,$answer_ver,$answer_ext) =
                   9713:         &file_name_version_ext($file_name);
                   9714:     my $new_answer;
                   9715:     $env{'form.copy'} =
                   9716:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   9717:     if($env{'form.copy'} eq '-1') {
                   9718:         $new_answer = 'problem getting file';
                   9719:     } else {
                   9720:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   9721:         my $copy_result = 
                   9722:             &finishuserfileupload($stu_name,$domain,'copy',
                   9723:                                   '/portfolio'.$directory.$new_answer);
                   9724:     }
                   9725:     undef($env{'form.copy'});
                   9726:     return ($new_answer);
                   9727: }
                   9728: 
                   9729: sub file_name_version_ext {
                   9730:     my ($file)=@_;
                   9731:     my @file_parts = split(/\./, $file);
                   9732:     my ($name,$version,$ext);
                   9733:     if (@file_parts > 1) {
                   9734:         $ext=pop(@file_parts);
                   9735:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   9736:             $version=pop(@file_parts);
                   9737:         }
                   9738:         $name=join('.',@file_parts);
                   9739:     } else {
                   9740:         $name=join('.',@file_parts);
                   9741:     }
                   9742:     return($name,$version,$ext);
                   9743: }
                   9744: 
1.745     raeburn  9745: #----------------------------------------------Get portfolio file permissions
1.629     banghart 9746: 
1.745     raeburn  9747: sub get_portfile_permissions {
                   9748:     my ($domain,$user) = @_;
1.613     albertel 9749:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9750:     my ($tmp)=keys(%current_permissions);
                   9751:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9752:     return \%current_permissions;
                   9753: }
                   9754: 
                   9755: #---------------------------------------------Get portfolio file access controls
                   9756: 
1.749     raeburn  9757: sub get_access_controls {
1.745     raeburn  9758:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 9759:     my %access;
                   9760:     my $real_file = $file;
                   9761:     $file =~ s/\.meta$//;
1.745     raeburn  9762:     if (defined($file)) {
1.749     raeburn  9763:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   9764:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 9765:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  9766:             }
                   9767:         }
1.745     raeburn  9768:     } else {
1.749     raeburn  9769:         foreach my $key (keys(%{$current_permissions})) {
                   9770:             if ($key =~ /\0accesscontrol$/) {
                   9771:                 if (defined($group)) {
                   9772:                     if ($key !~ m-^\Q$group\E/-) {
                   9773:                         next;
                   9774:                     }
                   9775:                 }
                   9776:                 my ($fullpath) = split(/\0/,$key);
                   9777:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   9778:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   9779:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   9780:                     }
                   9781:                 }
                   9782:             }
                   9783:         }
                   9784:     }
                   9785:     return %access;
                   9786: }
                   9787: 
                   9788: sub modify_access_controls {
                   9789:     my ($file_name,$changes,$domain,$user)=@_;
                   9790:     my ($outcome,$deloutcome);
                   9791:     my %store_permissions;
                   9792:     my %new_values;
                   9793:     my %new_control;
                   9794:     my %translation;
                   9795:     my @deletions = ();
                   9796:     my $now = time;
                   9797:     if (exists($$changes{'activate'})) {
                   9798:         if (ref($$changes{'activate'}) eq 'HASH') {
                   9799:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   9800:             my $numnew = scalar(@newitems);
                   9801:             for (my $i=0; $i<$numnew; $i++) {
                   9802:                 my $newkey = $newitems[$i];
                   9803:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  9804:                 if ($newkey =~ /^\d+:/) { 
                   9805:                     $newkey =~ s/^(\d+)/$newid/;
                   9806:                     $translation{$1} = $newid;
                   9807:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   9808:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   9809:                     $translation{$1} = $newid;
                   9810:                 }
1.749     raeburn  9811:                 $new_values{$file_name."\0".$newkey} = 
                   9812:                                           $$changes{'activate'}{$newitems[$i]};
                   9813:                 $new_control{$newkey} = $now;
                   9814:             }
                   9815:         }
                   9816:     }
                   9817:     my %todelete;
                   9818:     my %changed_items;
                   9819:     foreach my $action ('delete','update') {
                   9820:         if (exists($$changes{$action})) {
                   9821:             if (ref($$changes{$action}) eq 'HASH') {
                   9822:                 foreach my $key (keys(%{$$changes{$action}})) {
                   9823:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   9824:                     if ($action eq 'delete') { 
                   9825:                         $todelete{$itemnum} = 1;
                   9826:                     } else {
                   9827:                         $changed_items{$itemnum} = $key;
                   9828:                     }
                   9829:                 }
1.745     raeburn  9830:             }
                   9831:         }
1.749     raeburn  9832:     }
                   9833:     # get lock on access controls for file.
                   9834:     my $lockhash = {
                   9835:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   9836:                                                        ':'.$env{'user.domain'},
                   9837:                    }; 
                   9838:     my $tries = 0;
                   9839:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9840:    
1.1288    damieng  9841:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  9842:         $tries ++;
1.1289    damieng  9843:         sleep(0.1);
1.749     raeburn  9844:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9845:     }
                   9846:     if ($gotlock eq 'ok') {
                   9847:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   9848:         my ($tmp)=keys(%curr_permissions);
                   9849:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   9850:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   9851:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   9852:             if (ref($curr_controls) eq 'HASH') {
                   9853:                 foreach my $control_item (keys(%{$curr_controls})) {
                   9854:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   9855:                     if (defined($todelete{$itemnum})) {
                   9856:                         push(@deletions,$file_name."\0".$control_item);
                   9857:                     } else {
                   9858:                         if (defined($changed_items{$itemnum})) {
                   9859:                             $new_control{$changed_items{$itemnum}} = $now;
                   9860:                             push(@deletions,$file_name."\0".$control_item);
                   9861:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   9862:                         } else {
                   9863:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   9864:                         }
                   9865:                     }
1.745     raeburn  9866:                 }
                   9867:             }
                   9868:         }
1.970     raeburn  9869:         my ($group);
                   9870:         if (&is_course($domain,$user)) {
                   9871:             ($group,my $file) = split(/\//,$file_name,2);
                   9872:         }
1.749     raeburn  9873:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   9874:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   9875:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   9876:         #  remove lock
                   9877:         my @del_lock = ($file_name."\0".'locked_access_records');
                   9878:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9879:         my $sqlresult =
1.970     raeburn  9880:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9881:                                     $group);
1.749     raeburn  9882:     } else {
                   9883:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9884:     }
1.749     raeburn  9885:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9886: }
                   9887: 
1.827     raeburn  9888: sub make_public_indefinitely {
1.1271    raeburn  9889:     my (@requrl) = @_;
                   9890:     return &automated_portfile_access('public',\@requrl);
                   9891: }
                   9892: 
                   9893: sub automated_portfile_access {
                   9894:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  9895:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   9896:         return 'invalid';
                   9897:     }
1.1271    raeburn  9898:     my %urls;
                   9899:     if (ref($addsref) eq 'ARRAY') {
                   9900:         foreach my $requrl (@{$addsref}) {
                   9901:             if (&is_portfolio_url($requrl)) {
                   9902:                 unless (exists($urls{$requrl})) {
                   9903:                     $urls{$requrl} = 'add';
                   9904:                 }
                   9905:             }
                   9906:         }
                   9907:     }
                   9908:     if (ref($delsref) eq 'ARRAY') {
                   9909:         foreach my $requrl (@{$delsref}) { 
                   9910:             if (&is_portfolio_url($requrl)) {
                   9911:                 unless (exists($urls{$requrl})) {
                   9912:                     $urls{$requrl} = 'delete'; 
                   9913:                 }
                   9914:             }
                   9915:         }
                   9916:     }
                   9917:     unless (keys(%urls)) {
                   9918:         return 'invalid';
                   9919:     }
                   9920:     my $ip;
                   9921:     if ($accesstype eq 'ip') {
                   9922:         if (ref($info) eq 'HASH') {
                   9923:             if ($info->{'ip'} ne '') {
                   9924:                 $ip = $info->{'ip'};
                   9925:             }
                   9926:         }
                   9927:         if ($ip eq '') {
                   9928:             return 'invalid';
                   9929:         }
                   9930:     }
                   9931:     my $errors;
1.827     raeburn  9932:     my $now = time;
1.1271    raeburn  9933:     my %current_perms;
                   9934:     foreach my $requrl (sort(keys(%urls))) {
                   9935:         my $action;
                   9936:         if ($urls{$requrl} eq 'add') {
                   9937:             $action = 'activate';
                   9938:         } else {
                   9939:             $action = 'none';
                   9940:         }
                   9941:         my $aclnum = 0;
1.827     raeburn  9942:         my (undef,$udom,$unum,$file_name,$group) =
                   9943:             &parse_portfolio_url($requrl);
1.1271    raeburn  9944:         unless (exists($current_perms{$unum.':'.$udom})) {
                   9945:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   9946:         }
                   9947:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  9948:                                                    $group,$file_name);
                   9949:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9950:             my ($num,$scope,$end,$start) = 
                   9951:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  9952:             if ($scope eq $accesstype) {
                   9953:                 if (($start <= $now) && ($end == 0)) {
                   9954:                     if ($accesstype eq 'ip') {
                   9955:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   9956:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   9957:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   9958:                                     if ($urls{$requrl} eq 'add') {
                   9959:                                         $action = 'none';
                   9960:                                         last;
                   9961:                                     } else {
                   9962:                                         $action = 'delete';
                   9963:                                         $aclnum = $num;
                   9964:                                         last;
                   9965:                                     }
                   9966:                                 }
                   9967:                             }
                   9968:                         }
                   9969:                     } elsif ($accesstype eq 'public') {
                   9970:                         if ($urls{$requrl} eq 'add') {
                   9971:                             $action = 'none';
                   9972:                             last;
                   9973:                         } else {
                   9974:                             $action = 'delete';
                   9975:                             $aclnum = $num;
                   9976:                             last;
                   9977:                         }
                   9978:                     }
                   9979:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  9980:                     $action = 'update';
                   9981:                     $aclnum = $num;
1.1271    raeburn  9982:                     last;
1.827     raeburn  9983:                 }
                   9984:             }
                   9985:         }
                   9986:         if ($action eq 'none') {
1.1271    raeburn  9987:             next;
1.827     raeburn  9988:         } else {
                   9989:             my %changes;
                   9990:             my $newend = 0;
                   9991:             my $newstart = $now;
1.1271    raeburn  9992:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  9993:             $changes{$action}{$newkey} = {
1.1271    raeburn  9994:                 type => $accesstype,
1.827     raeburn  9995:                 time => {
                   9996:                     start => $newstart,
                   9997:                     end   => $newend,
                   9998:                 },
                   9999:             };
1.1271    raeburn  10000:             if ($accesstype eq 'ip') {
                   10001:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   10002:             }
1.827     raeburn  10003:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10004:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  10005:             unless ($outcome eq 'ok') {
                   10006:                 $errors .= $outcome.' ';
                   10007:             }
1.827     raeburn  10008:         }
1.1271    raeburn  10009:     }
                   10010:     if ($errors) {
                   10011:         $errors =~ s/\s$//;
                   10012:         return $errors;
1.827     raeburn  10013:     } else {
1.1271    raeburn  10014:         return 'ok';
1.827     raeburn  10015:     }
                   10016: }
                   10017: 
1.745     raeburn  10018: #------------------------------------------------------Get Marked as Read Only
                   10019: 
                   10020: sub get_marked_as_readonly {
                   10021:     my ($domain,$user,$what,$group) = @_;
                   10022:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10023:     my @readonly_files;
1.629     banghart 10024:     my $cmp1=$what;
                   10025:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10026:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10027:         if (defined($group)) {
                   10028:             if ($file_name !~ m-^\Q$group\E/-) {
                   10029:                 next;
                   10030:             }
                   10031:         }
1.561     banghart 10032:         if (ref($value) eq "ARRAY"){
                   10033:             foreach my $stored_what (@{$value}) {
1.629     banghart 10034:                 my $cmp2=$stored_what;
1.759     albertel 10035:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10036:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10037:                 }
1.629     banghart 10038:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10039:                     push(@readonly_files, $file_name);
1.745     raeburn  10040:                     last;
1.563     banghart 10041:                 } elsif (!defined($what)) {
                   10042:                     push(@readonly_files, $file_name);
1.745     raeburn  10043:                     last;
1.561     banghart 10044:                 }
                   10045:             }
1.745     raeburn  10046:         }
1.561     banghart 10047:     }
                   10048:     return @readonly_files;
                   10049: }
1.577     banghart 10050: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10051: 
1.577     banghart 10052: sub get_marked_as_readonly_hash {
1.745     raeburn  10053:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10054:     my %readonly_files;
1.745     raeburn  10055:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10056:         if (defined($group)) {
                   10057:             if ($file_name !~ m-^\Q$group\E/-) {
                   10058:                 next;
                   10059:             }
                   10060:         }
1.577     banghart 10061:         if (ref($value) eq "ARRAY"){
                   10062:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10063:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10064:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10065:                         if ($lock_descriptor eq 'graded') {
                   10066:                             $readonly_files{$file_name} = 'graded';
                   10067:                         } elsif ($lock_descriptor eq 'handback') {
                   10068:                             $readonly_files{$file_name} = 'handback';
                   10069:                         } else {
                   10070:                             if (!exists($readonly_files{$file_name})) {
                   10071:                                 $readonly_files{$file_name} = 'locked';
                   10072:                             }
                   10073:                         }
1.745     raeburn  10074:                     }
1.750     banghart 10075:                 } 
1.577     banghart 10076:             }
                   10077:         } 
                   10078:     }
                   10079:     return %readonly_files;
                   10080: }
1.559     banghart 10081: # ------------------------------------------------------------ Unmark as Read Only
                   10082: 
                   10083: sub unmark_as_readonly {
1.629     banghart 10084:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10085:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10086:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10087:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10088:     my $symb_crs = $what;
                   10089:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10090:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10091:     my ($tmp)=keys(%current_permissions);
                   10092:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10093:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10094:     foreach my $file (@readonly_files) {
1.759     albertel 10095: 	my $clean_file = &declutter_portfile($file);
                   10096: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10097: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10098:         my @new_locks;
                   10099:         my @del_keys;
                   10100:         if (ref($current_locks) eq "ARRAY"){
                   10101:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10102:                 my $compare=$locker;
1.749     raeburn  10103:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10104:                     $compare=join('',@{$locker});
1.746     raeburn  10105:                     if ($compare ne $symb_crs) {
                   10106:                         push(@new_locks, $locker);
                   10107:                     }
1.563     banghart 10108:                 }
                   10109:             }
1.650     albertel 10110:             if (scalar(@new_locks) > 0) {
1.563     banghart 10111:                 $current_permissions{$file} = \@new_locks;
                   10112:             } else {
                   10113:                 push(@del_keys, $file);
1.613     albertel 10114:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10115:                 delete($current_permissions{$file});
1.563     banghart 10116:             }
                   10117:         }
1.561     banghart 10118:     }
1.613     albertel 10119:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10120:     return;
                   10121: }
1.512     banghart 10122: 
1.17      www      10123: # ------------------------------------------------------------ Directory lister
                   10124: 
                   10125: sub dirlist {
1.955     raeburn  10126:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10127:     $uri=~s/^\///;
                   10128:     $uri=~s/\/$//;
1.253     stredwic 10129:     my ($udom, $uname);
1.955     raeburn  10130:     if ($getuserdir) {
1.253     stredwic 10131:         $udom = $userdomain;
                   10132:         $uname = $username;
1.955     raeburn  10133:     } else {
                   10134:         (undef,$udom,$uname)=split(/\//,$uri);
                   10135:         if(defined($userdomain)) {
                   10136:             $udom = $userdomain;
                   10137:         }
                   10138:         if(defined($username)) {
                   10139:             $uname = $username;
                   10140:         }
1.253     stredwic 10141:     }
1.955     raeburn  10142:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10143: 
1.955     raeburn  10144:     $dirRoot = $perlvar{'lonDocRoot'};
                   10145:     if (defined($getpropath)) {
                   10146:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10147:         $dirRoot =~ s/\/$//;
1.955     raeburn  10148:     } elsif (defined($getuserdir)) {
                   10149:         my $subdir=$uname.'__';
                   10150:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10151:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10152:                    ."/$udom/$subdir/$uname";
                   10153:     } elsif (defined($alternateRoot)) {
                   10154:         $dirRoot = $alternateRoot;
1.751     banghart 10155:     }
1.253     stredwic 10156: 
                   10157:     if($udom) {
                   10158:         if($uname) {
1.1135    raeburn  10159:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10160:             if ($uhome eq 'no_host') {
                   10161:                 return ([],'no_host');
                   10162:             }
1.955     raeburn  10163:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10164:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10165:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10166:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10167:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10168:             } else {
                   10169:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10170:             }
1.605     matthew  10171:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10172:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10173:                 @listing_results = split(/:/,$listing);
                   10174:             } else {
                   10175:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10176:             }
1.1135    raeburn  10177:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10178:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10179:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10180:                 return ([],$listing);
                   10181:             } else {
                   10182:                 return (\@listing_results);
1.1135    raeburn  10183:             }
1.955     raeburn  10184:         } elsif(!$alternateRoot) {
1.1136    raeburn  10185:             my (%allusers,%listerror);
1.841     albertel 10186: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10187:  	    foreach my $tryserver (keys(%servers)) {
                   10188:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10189:                                   &escape($udom),$tryserver);
                   10190:                 if ($listing eq 'unknown_cmd') {
                   10191: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10192: 				      $udom, $tryserver);
                   10193:                 } else {
                   10194:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10195:                 }
1.841     albertel 10196: 		if ($listing eq 'unknown_cmd') {
                   10197: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10198: 				      $udom, $tryserver);
                   10199: 		    @listing_results = split(/:/,$listing);
                   10200: 		} else {
                   10201: 		    @listing_results =
                   10202: 			map { &unescape($_); } split(/:/,$listing);
                   10203: 		}
1.1136    raeburn  10204:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10205:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10206:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10207:                     $listerror{$tryserver} = $listing;
                   10208:                 } else {
1.841     albertel 10209: 		    foreach my $line (@listing_results) {
                   10210: 			my ($entry) = split(/&/,$line,2);
                   10211: 			$allusers{$entry} = 1;
                   10212: 		    }
                   10213: 		}
1.253     stredwic 10214:             }
1.1136    raeburn  10215:             my @alluserslist=();
1.800     albertel 10216:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10217:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10218:             }
1.1318    droeschl 10219: 
                   10220:             if (!%listerror) {
                   10221:                 # no errors
                   10222:                 return (\@alluserslist);
                   10223:             } elsif (scalar(keys(%servers)) == 1) {
                   10224:                 # one library server, one error 
                   10225:                 my ($key) = keys(%listerror);
                   10226:                 return (\@alluserslist, $listerror{$key});
                   10227:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10228:                 # con_lost indicates that we might miss data from at least one
                   10229:                 # library server
                   10230:                 return (\@alluserslist, 'con_lost');
                   10231:             } else {
                   10232:                 # multiple library servers and no con_lost -> data should be
                   10233:                 # complete. 
                   10234:                 return (\@alluserslist);
                   10235:             }
                   10236: 
1.253     stredwic 10237:         } else {
1.1136    raeburn  10238:             return ([],'missing username');
1.253     stredwic 10239:         }
1.955     raeburn  10240:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10241:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10242:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10243:         return (\@all_domains);
1.955     raeburn  10244:     } else {
1.1136    raeburn  10245:         return ([],'missing domain');
1.275     stredwic 10246:     }
                   10247: }
                   10248: 
                   10249: # --------------------------------------------- GetFileTimestamp
                   10250: # This function utilizes dirlist and returns the date stamp for
                   10251: # when it was last modified.  It will also return an error of -1
                   10252: # if an error occurs
                   10253: 
                   10254: sub GetFileTimestamp {
1.955     raeburn  10255:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10256:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10257:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10258:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10259:                                     undef,$getuserdir);
                   10260:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10261:         return -1;
                   10262:     }
                   10263:     if (ref($fileref) eq 'ARRAY') {
                   10264:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10265:         # @stats contains first the filename, then the stat output
                   10266:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10267:     } else {
                   10268:         return -1;
1.253     stredwic 10269:     }
1.26      www      10270: }
                   10271: 
1.712     albertel 10272: sub stat_file {
                   10273:     my ($uri) = @_;
1.787     albertel 10274:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10275: 
1.955     raeburn  10276:     my ($udom,$uname,$file);
1.712     albertel 10277:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10278: 	($udom,$uname,$file) =
1.811     albertel 10279: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10280: 	$file = 'userfiles/'.$file;
                   10281:     }
                   10282:     if ($uri =~ m-^/res/-) {
                   10283: 	($udom,$uname) = 
1.807     albertel 10284: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10285: 	$file = $uri;
                   10286:     }
                   10287: 
                   10288:     if (!$udom || !$uname || !$file) {
                   10289: 	# unable to handle the uri
                   10290: 	return ();
                   10291:     }
1.956     raeburn  10292:     my $getpropath;
                   10293:     if ($file =~ /^userfiles\//) {
                   10294:         $getpropath = 1;
                   10295:     }
1.1136    raeburn  10296:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10297:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10298:         return ();
                   10299:     } else {
                   10300:         if (ref($listref) eq 'ARRAY') {
                   10301:             my @stats = split('&',$listref->[0]);
                   10302: 	    shift(@stats); #filename is first
                   10303: 	    return @stats;
                   10304:         }
1.712     albertel 10305:     }
                   10306:     return ();
                   10307: }
                   10308: 
1.1313    raeburn  10309: # --------------------------------------------------------- recursedirs
                   10310: # Recursive function to traverse either a specific user's Authoring Space
                   10311: # or corresponding Published Resource Space, and populate the hash ref:
                   10312: # $dirhashref with URLs of all directories, and if $filehashref hash
                   10313: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
                   10314: # or .rights files in resource space, and .meta, .save, .log, and .bak
                   10315: # files in Authoring Space.
                   10316: #
                   10317: # Inputs:
                   10318: #
                   10319: # $is_home - true if current server is home server for user's space
                   10320: # $context - either: priv, or res respectively for Authoring or Resource Space.
                   10321: # $docroot - Document root (i.e., /home/httpd/html
                   10322: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
                   10323: # $relpath - Current path (relative to top level).
                   10324: # $dirhashref - reference to hash to populate with URLs of directories (Required)
                   10325: # $filehashref - reference to hash to populate with URLs of files (Optional)
                   10326: #
                   10327: # Returns: nothing
                   10328: #
                   10329: # Side Effects: populates $dirhashref, and $filehashref (if provided).
                   10330: #
                   10331: # Currently used by interface/londocs.pm to create linked select boxes for
                   10332: # directory and filename to import a Course "Author" resource into a course, and
                   10333: # also to create linked select boxes for Authoring Space and Directory to choose
                   10334: # save location for creation of a new "standard" problem from the Course Editor.
                   10335: #
                   10336: 
                   10337: sub recursedirs {
                   10338:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
                   10339:     return unless (ref($dirhashref) eq 'HASH');
                   10340:     my $currpath = $docroot.$toppath;
                   10341:     if ($relpath) {
                   10342:         $currpath .= "/$relpath";
                   10343:     }
                   10344:     my $savefile;
                   10345:     if (ref($filehashref)) {
                   10346:         $savefile = 1;
                   10347:     }
                   10348:     if ($is_home) {
                   10349:         if (opendir(my $dirh,$currpath)) {
                   10350:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
                   10351:                 next if ($item eq '');
                   10352:                 if (-d "$currpath/$item") {
                   10353:                     my $newpath;
                   10354:                     if ($relpath) {
                   10355:                         $newpath = "$relpath/$item";
                   10356:                     } else {
                   10357:                         $newpath = $item;
                   10358:                     }
                   10359:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   10360:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   10361:                 } elsif ($savefile) {
                   10362:                     if ($context eq 'priv') {
                   10363:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   10364:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   10365:                         }
                   10366:                     } else {
                   10367:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
                   10368:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   10369:                         }
                   10370:                     }
                   10371:                 }
                   10372:             }
                   10373:             closedir($dirh);
                   10374:         }
                   10375:     } else {
                   10376:         my ($dirlistref,$listerror) =
                   10377:             &dirlist($toppath.$relpath);
                   10378:         my @dir_lines;
                   10379:         my $dirptr=16384;
                   10380:         if (ref($dirlistref) eq 'ARRAY') {
                   10381:             foreach my $dir_line (sort
                   10382:                               {
                   10383:                                   my ($afile)=split('&',$a,2);
                   10384:                                   my ($bfile)=split('&',$b,2);
                   10385:                                   return (lc($afile) cmp lc($bfile));
                   10386:                               } (@{$dirlistref})) {
                   10387:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
                   10388:                     split(/\&/,$dir_line,16);
                   10389:                 $item =~ s/\s+$//;
                   10390:                 next if (($item =~ /^\.\.?$/) || ($obs));
                   10391:                 if ($dirptr&$testdir) {
                   10392:                     my $newpath;
                   10393:                     if ($relpath) {
                   10394:                         $newpath = "$relpath/$item";
                   10395:                     } else {
                   10396:                         $relpath = '/';
                   10397:                         $newpath = $item;
                   10398:                     }
                   10399:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   10400:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   10401:                 } elsif ($savefile) {
                   10402:                     if ($context eq 'priv') {
                   10403:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   10404:                             $filehashref->{$relpath}{$item} = 1;
                   10405:                         }
                   10406:                     } else {
                   10407:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
                   10408:                             $filehashref->{$relpath}{$item} = 1;
                   10409:                         }
                   10410:                     }
                   10411:                 }
                   10412:             }
                   10413:         }
                   10414:     }
                   10415:     return;
                   10416: }
                   10417: 
1.26      www      10418: # -------------------------------------------------------- Value of a Condition
                   10419: 
1.713     albertel 10420: # gets the value of a specific preevaluated condition
                   10421: #    stored in the string  $env{user.state.<cid>}
                   10422: # or looks up a condition reference in the bighash and if if hasn't
                   10423: # already been evaluated recurses into docondval to get the value of
                   10424: # the condition, then memoizing it to 
                   10425: #   $env{user.state.<cid>.<condition>}
1.40      www      10426: sub directcondval {
                   10427:     my $number=shift;
1.620     albertel 10428:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 10429: 	&Apache::lonuserstate::evalstate();
                   10430:     }
1.713     albertel 10431:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   10432: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   10433:     } elsif ($number =~ /^_/) {
                   10434: 	my $sub_condition;
                   10435: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10436: 		&GDBM_READER(),0640)) {
                   10437: 	    $sub_condition=$bighash{'conditions'.$number};
                   10438: 	    untie(%bighash);
                   10439: 	}
                   10440: 	my $value = &docondval($sub_condition);
1.949     raeburn  10441: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 10442: 	return $value;
                   10443:     }
1.620     albertel 10444:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   10445:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      10446:     } else {
                   10447:        return 2;
                   10448:     }
                   10449: }
                   10450: 
1.713     albertel 10451: # get the collection of conditions for this resource
1.26      www      10452: sub condval {
                   10453:     my $condidx=shift;
1.54      www      10454:     my $allpathcond='';
1.713     albertel 10455:     foreach my $cond (split(/\|/,$condidx)) {
                   10456: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   10457: 	    $allpathcond.=
                   10458: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   10459: 	}
1.191     harris41 10460:     }
1.54      www      10461:     $allpathcond=~s/\|$//;
1.713     albertel 10462:     return &docondval($allpathcond);
                   10463: }
                   10464: 
                   10465: #evaluates an expression of conditions
                   10466: sub docondval {
                   10467:     my ($allpathcond) = @_;
                   10468:     my $result=0;
                   10469:     if ($env{'request.course.id'}
                   10470: 	&& defined($allpathcond)) {
                   10471: 	my $operand='|';
                   10472: 	my @stack;
                   10473: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   10474: 	    if ($chunk eq '(') {
                   10475: 		push @stack,($operand,$result);
                   10476: 	    } elsif ($chunk eq ')') {
                   10477: 		my $before=pop @stack;
                   10478: 		if (pop @stack eq '&') {
                   10479: 		    $result=$result>$before?$before:$result;
                   10480: 		} else {
                   10481: 		    $result=$result>$before?$result:$before;
                   10482: 		}
                   10483: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   10484: 		$operand=$chunk;
                   10485: 	    } else {
                   10486: 		my $new=directcondval($chunk);
                   10487: 		if ($operand eq '&') {
                   10488: 		    $result=$result>$new?$new:$result;
                   10489: 		} else {
                   10490: 		    $result=$result>$new?$result:$new;
                   10491: 		}
                   10492: 	    }
                   10493: 	}
1.26      www      10494:     }
                   10495:     return $result;
1.421     albertel 10496: }
                   10497: 
                   10498: # ---------------------------------------------------- Devalidate courseresdata
                   10499: 
                   10500: sub devalidatecourseresdata {
                   10501:     my ($coursenum,$coursedomain)=@_;
                   10502:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10503:     &devalidate_cache_new('courseres',$hashid);
1.28      www      10504: }
                   10505: 
1.763     www      10506: 
1.200     www      10507: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     10508: #
                   10509: #  Parameters:
                   10510: #      $coursenum    - Number of the course.
                   10511: #      $coursedomain - Domain at which the course was created.
                   10512: #  Returns:
                   10513: #     A hash of the course parameters along (I think) with timestamps
                   10514: #     and version info.
1.877     foxr     10515: 
1.624     albertel 10516: sub get_courseresdata {
                   10517:     my ($coursenum,$coursedomain)=@_;
1.200     www      10518:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   10519:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10520:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 10521:     my %dumpreply;
1.417     albertel 10522:     unless (defined($cached)) {
1.624     albertel 10523: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 10524: 	$result=\%dumpreply;
1.251     albertel 10525: 	my ($tmp) = keys(%dumpreply);
                   10526: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 10527: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 10528: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   10529: 	    return $tmp;
1.416     albertel 10530: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 10531: 	    $result=undef;
1.599     albertel 10532: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 10533: 	}
                   10534:     }
1.624     albertel 10535:     return $result;
                   10536: }
                   10537: 
1.633     albertel 10538: sub devalidateuserresdata {
                   10539:     my ($uname,$udom)=@_;
                   10540:     my $hashid="$udom:$uname";
                   10541:     &devalidate_cache_new('userres',$hashid);
                   10542: }
                   10543: 
1.624     albertel 10544: sub get_userresdata {
                   10545:     my ($uname,$udom)=@_;
                   10546:     #most student don\'t have any data set, check if there is some data
                   10547:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   10548: 
                   10549:     my $hashid="$udom:$uname";
                   10550:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   10551:     if (!defined($cached)) {
                   10552: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   10553: 	$result=\%resourcedata;
                   10554: 	&do_cache_new('userres',$hashid,$result,600);
                   10555:     }
                   10556:     my ($tmp)=keys(%$result);
                   10557:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   10558: 	return $result;
                   10559:     }
                   10560:     #error 2 occurs when the .db doesn't exist
                   10561:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  10562:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   10563: 	    &logthis("<font color=\"blue\">WARNING:".
                   10564: 		     " Trying to get resource data for ".
                   10565: 		     $uname." at ".$udom.": ".
                   10566: 		     $tmp."</font>");
                   10567:         }
1.624     albertel 10568:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 10569: 	#&EXT_cache_set($udom,$uname);
                   10570: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 10571: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 10572:     }
                   10573:     return $tmp;
                   10574: }
1.879     foxr     10575: #----------------------------------------------- resdata - return resource data
                   10576: #  Purpose:
                   10577: #    Return resource data for either users or for a course.
                   10578: #  Parameters:
                   10579: #     $name      - Course/user name.
                   10580: #     $domain    - Name of the domain the user/course is registered on.
1.1311    raeburn  10581: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  10582: #     $mapp      - decluttered URL of enclosing map  
                   10583: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   10584: #     $recurseup - Ref to array of map URLs, starting with map containing
                   10585: #                  $mapp up through hierarchy of nested maps to top level map.  
                   10586: #     $courseid  - CourseID (first part of param identifier).
                   10587: #     $modifier  - Middle part of param identifier.
                   10588: #     $what      - Last part of param identifier.
1.879     foxr     10589: #     @which     - Array of names of resources desired.
                   10590: #  Returns:
                   10591: #     The value of the first reasource in @which that is found in the
                   10592: #     resource hash.
                   10593: #  Exceptional Conditions:
                   10594: #     If the $type passed in is not valid (not the string 'course' or 
                   10595: #     'user', an undefined  reference is returned.
                   10596: #     If none of the resources are found, an undef is returned
1.624     albertel 10597: sub resdata {
1.1301    raeburn  10598:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   10599:         $modifier,$what,@which)=@_;
1.624     albertel 10600:     my $result;
                   10601:     if ($type eq 'course') {
                   10602: 	$result=&get_courseresdata($name,$domain);
                   10603:     } elsif ($type eq 'user') {
                   10604: 	$result=&get_userresdata($name,$domain);
                   10605:     }
                   10606:     if (!ref($result)) { return $result; }    
1.251     albertel 10607:     foreach my $item (@which) {
1.1301    raeburn  10608:         if ($item->[1] eq 'course') {
                   10609:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   10610:                 unless ($$recursed) {
1.1302    raeburn  10611:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  10612:                     $$recursed = 1;
                   10613:                 }
                   10614:                 foreach my $item (@${recurseup}) {
                   10615:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   10616:                     last if (defined($result->{$norecursechk}));
                   10617:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   10618:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   10619:                 }
                   10620:             }
                   10621:         }
                   10622:         if (defined($result->{$item->[0]})) {
1.927     albertel 10623: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 10624: 	}
1.250     albertel 10625:     }
1.291     albertel 10626:     return undef;
1.200     www      10627: }
                   10628: 
1.1298    raeburn  10629: sub get_domain_ltitools {
                   10630:     my ($cdom) = @_;
                   10631:     my %ltitools;
                   10632:     my ($result,$cached)=&is_cached_new('ltitools',$cdom);
                   10633:     if (defined($cached)) {
                   10634:         if (ref($result) eq 'HASH') {
                   10635:             %ltitools = %{$result};
                   10636:         }
                   10637:     } else {
                   10638:         my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
                   10639:         if (ref($domconfig{'ltitools'}) eq 'HASH') {
                   10640:             %ltitools = %{$domconfig{'ltitools'}};
                   10641:         }
                   10642:         my $cachetime = 24*60*60;
                   10643:         &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
                   10644:     }
                   10645:     return %ltitools;
                   10646: }
                   10647: 
1.1236    raeburn  10648: sub get_numsuppfiles {
                   10649:     my ($cnum,$cdom,$ignorecache)=@_;
                   10650:     my $hashid=$cnum.':'.$cdom;
                   10651:     my ($suppcount,$cached);
                   10652:     unless ($ignorecache) {
                   10653:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   10654:     }
                   10655:     unless (defined($cached)) {
                   10656:         my $chome=&homeserver($cnum,$cdom);
                   10657:         unless ($chome eq 'no_host') {
                   10658:             ($suppcount,my $errors) = (0,0);
                   10659:             my $suppmap = 'supplemental.sequence';
                   10660:             ($suppcount,$errors) = 
                   10661:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   10662:         }
                   10663:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   10664:     }
                   10665:     return $suppcount;
                   10666: }
                   10667: 
1.379     matthew  10668: #
                   10669: # EXT resource caching routines
                   10670: #
                   10671: 
1.1302    raeburn  10672: {
                   10673: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   10674: #
                   10675: # The course for which we cache
                   10676: my $cachedmapkey='';
                   10677: # The cached recursive maps for this course
                   10678: my %cachedmaps=();
                   10679: # When this was last done
                   10680: my $cachedmaptime='';
                   10681: 
1.379     matthew  10682: sub clear_EXT_cache_status {
1.383     albertel 10683:     &delenv('cache.EXT.');
1.379     matthew  10684: }
                   10685: 
                   10686: sub EXT_cache_status {
                   10687:     my ($target_domain,$target_user) = @_;
1.383     albertel 10688:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 10689:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  10690:         # We know already the user has no data
                   10691:         return 1;
                   10692:     } else {
                   10693:         return 0;
                   10694:     }
                   10695: }
                   10696: 
                   10697: sub EXT_cache_set {
                   10698:     my ($target_domain,$target_user) = @_;
1.383     albertel 10699:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  10700:     #&appenv({$cachename => time});
1.379     matthew  10701: }
                   10702: 
1.28      www      10703: # --------------------------------------------------------- Value of a Variable
1.58      www      10704: sub EXT {
1.715     albertel 10705: 
1.1228    raeburn  10706:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      10707:     unless ($varname) { return ''; }
1.218     albertel 10708:     #get real user name/domain, courseid and symb
                   10709:     my $courseid;
1.359     albertel 10710:     my $publicuser;
1.427     www      10711:     if ($symbparm) {
                   10712: 	$symbparm=&get_symb_from_alias($symbparm);
                   10713:     }
1.218     albertel 10714:     if (!($uname && $udom)) {
1.790     albertel 10715:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 10716:       if (!$symbparm) {	$symbparm=$cursymb; }
                   10717:     } else {
1.620     albertel 10718: 	$courseid=$env{'request.course.id'};
1.218     albertel 10719:     }
1.48      www      10720:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   10721:     my $rest;
1.320     albertel 10722:     if (defined($therest[0])) {
1.48      www      10723:        $rest=join('.',@therest);
                   10724:     } else {
                   10725:        $rest='';
                   10726:     }
1.320     albertel 10727: 
1.57      www      10728:     my $qualifierrest=$qualifier;
                   10729:     if ($rest) { $qualifierrest.='.'.$rest; }
                   10730:     my $spacequalifierrest=$space;
                   10731:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      10732:     if ($realm eq 'user') {
1.48      www      10733: # --------------------------------------------------------------- user.resource
                   10734: 	if ($space eq 'resource') {
1.651     albertel 10735: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   10736: 		  || defined($Apache::lonhomework::parsing_a_task))
                   10737: 		 &&
1.744     albertel 10738: 		 ($symbparm eq &symbread()) ) {	
                   10739: 		# if we are in the middle of processing the resource the
                   10740: 		# get the value we are planning on committing
                   10741:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   10742:                     return $Apache::lonhomework::results{$qualifierrest};
                   10743:                 } else {
                   10744:                     return $Apache::lonhomework::history{$qualifierrest};
                   10745:                 }
1.335     albertel 10746: 	    } else {
1.359     albertel 10747: 		my %restored;
1.620     albertel 10748: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 10749: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   10750: 		} else {
                   10751: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   10752: 		}
1.335     albertel 10753: 		return $restored{$qualifierrest};
                   10754: 	    }
1.48      www      10755: # ----------------------------------------------------------------- user.access
                   10756:         } elsif ($space eq 'access') {
1.218     albertel 10757: 	    # FIXME - not supporting calls for a specific user
1.48      www      10758:             return &allowed($qualifier,$rest);
                   10759: # ------------------------------------------ user.preferences, user.environment
                   10760:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 10761: 	    if (($uname eq $env{'user.name'}) &&
                   10762: 		($udom eq $env{'user.domain'})) {
                   10763: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 10764: 	    } else {
1.359     albertel 10765: 		my %returnhash;
                   10766: 		if (!$publicuser) {
                   10767: 		    %returnhash=&userenvironment($udom,$uname,
                   10768: 						 $qualifierrest);
                   10769: 		}
1.218     albertel 10770: 		return $returnhash{$qualifierrest};
                   10771: 	    }
1.48      www      10772: # ----------------------------------------------------------------- user.course
                   10773:         } elsif ($space eq 'course') {
1.218     albertel 10774: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10775:             return $env{join('.',('request.course',$qualifier))};
1.48      www      10776: # ------------------------------------------------------------------- user.role
                   10777:         } elsif ($space eq 'role') {
1.218     albertel 10778: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10779:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      10780:             if ($qualifier eq 'value') {
                   10781: 		return $role;
                   10782:             } elsif ($qualifier eq 'extent') {
                   10783:                 return $where;
                   10784:             }
                   10785: # ----------------------------------------------------------------- user.domain
                   10786:         } elsif ($space eq 'domain') {
1.218     albertel 10787:             return $udom;
1.48      www      10788: # ------------------------------------------------------------------- user.name
                   10789:         } elsif ($space eq 'name') {
1.218     albertel 10790:             return $uname;
1.48      www      10791: # ---------------------------------------------------- Any other user namespace
1.29      www      10792:         } else {
1.359     albertel 10793: 	    my %reply;
                   10794: 	    if (!$publicuser) {
                   10795: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   10796: 	    }
                   10797: 	    return $reply{$qualifierrest};
1.48      www      10798:         }
1.236     www      10799:     } elsif ($realm eq 'query') {
                   10800: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 10801:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   10802: 						[$spacequalifierrest]);
1.620     albertel 10803: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      10804:    } elsif ($realm eq 'request') {
1.48      www      10805: # ------------------------------------------------------------- request.browser
                   10806:         if ($space eq 'browser') {
1.1145    bisitz   10807:             return $env{'browser.'.$qualifier};
1.57      www      10808: # ------------------------------------------------------------ request.filename
                   10809:         } else {
1.620     albertel 10810:             return $env{'request.'.$spacequalifierrest};
1.29      www      10811:         }
1.28      www      10812:     } elsif ($realm eq 'course') {
1.48      www      10813: # ---------------------------------------------------------- course.description
1.620     albertel 10814:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      10815:     } elsif ($realm eq 'resource') {
1.165     www      10816: 
1.620     albertel 10817: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 10818: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   10819: 	}
1.693     albertel 10820: 
1.1232    raeburn  10821:         if ($qualifier eq '') {
                   10822: 	    if ($space eq 'title') {
                   10823: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   10824: 	        return &gettitle($symbparm);
                   10825: 	    }
1.693     albertel 10826: 	
1.1232    raeburn  10827: 	    if ($space eq 'map') {
                   10828: 	        my ($map) = &decode_symb($symbparm);
                   10829: 	        return &symbread($map);
                   10830: 	    }
                   10831:             if ($space eq 'maptitle') {
                   10832:                 my ($map) = &decode_symb($symbparm);
                   10833:                 return &gettitle($map);
                   10834:             }
                   10835: 	    if ($space eq 'filename') {
                   10836: 	        if ($symbparm) {
                   10837: 		    return &clutter((&decode_symb($symbparm))[2]);
                   10838: 	        }
                   10839: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 10840: 	    }
1.1232    raeburn  10841: 
1.1233    raeburn  10842:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   10843:                 if ($space eq 'visibleparts') {
                   10844:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10845:                     my $item;
                   10846:                     if (ref($navmap)) {
                   10847:                         my $res = $navmap->getBySymb($symbparm);
                   10848:                         my $parts = $res->parts();
                   10849:                         if (ref($parts) eq 'ARRAY') {
                   10850:                             $item = join(',',@{$parts});
                   10851:                         }
                   10852:                         undef($navmap);
1.1232    raeburn  10853:                     }
1.1233    raeburn  10854:                     return $item;
1.1232    raeburn  10855:                 }
                   10856:             }
                   10857:         }
1.693     albertel 10858: 
1.1301    raeburn  10859: 	my ($section, $group, @groups, @recurseup, $recursed);
                   10860: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  10861:         if (($courseid eq '') && ($cid)) {
                   10862:             $courseid = $cid;
                   10863:         }
                   10864: 	if (($symbparm && $courseid) && 
                   10865: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      10866: 
1.218     albertel 10867: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      10868: 
1.60      www      10869: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 10870: 	    my $symbp=$symbparm;
1.1301    raeburn  10871: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 10872: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  10873:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 10874: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 10875: 	    if (($env{'user.name'} eq $uname) &&
                   10876: 		($env{'user.domain'} eq $udom)) {
                   10877: 		$section=$env{'request.course.sec'};
1.733     raeburn  10878:                 @groups = split(/:/,$env{'request.course.groups'});  
                   10879:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 10880: 	    } else {
1.539     albertel 10881: 		if (! defined($usection)) {
1.551     albertel 10882: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 10883: 		} else {
                   10884: 		    $section = $usection;
                   10885: 		}
1.733     raeburn  10886:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 10887: 	    }
                   10888: 
                   10889: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   10890: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  10891:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 10892: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   10893: 
1.593     albertel 10894: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 10895: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  10896:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 10897: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      10898: 
1.60      www      10899: # ----------------------------------------------------------- first, check user
1.624     albertel 10900: 
1.1301    raeburn  10901: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   10902:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 10903: 				       ([$courselevelr,'resource'],
                   10904: 					[$courselevelm,'map'     ],
1.1301    raeburn  10905:                                         [$courseleveli,'map'     ],
1.927     albertel 10906: 					[$courselevel, 'course'  ]));
1.931     albertel 10907: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      10908: 
1.594     albertel 10909: # ------------------------------------------------ second, check some of course
1.684     raeburn  10910:             my $coursereply;
1.691     raeburn  10911:             if (@groups > 0) {
                   10912:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  10913:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   10914:                                        $mapp,\$recursed,\@recurseup);
                   10915:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  10916:             }
1.96      www      10917: 
1.684     raeburn  10918: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 10919: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  10920: 				  'course',$mapp,\$recursed,\@recurseup,
                   10921:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 10922: 				  ([$seclevelr,   'resource'],
                   10923: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  10924:                                    [$secleveli,   'map'     ],
1.927     albertel 10925: 				   [$seclevel,    'course'  ],
                   10926: 				   [$courselevelr,'resource']));
                   10927: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      10928: 
1.60      www      10929: # ------------------------------------------------------ third, check map parms
1.218     albertel 10930: 	    my %parmhash=();
                   10931: 	    my $thisparm='';
                   10932: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 10933: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 10934: 		    &GDBM_READER(),0640)) {
1.218     albertel 10935: 		$thisparm=$parmhash{$symbparm};
                   10936: 		untie(%parmhash);
                   10937: 	    }
1.927     albertel 10938: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 10939: 	}
1.594     albertel 10940: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  10941:  
                   10942:         my $what = $spacequalifierrest;
                   10943: 	$what=~s/\./\_/;
1.282     albertel 10944: 	my $filename;
                   10945: 	if (!$symbparm) { $symbparm=&symbread(); }
                   10946: 	if ($symbparm) {
1.409     www      10947: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 10948: 	} else {
1.620     albertel 10949: 	    $filename=$env{'request.filename'};
1.282     albertel 10950: 	}
1.1301    raeburn  10951: 	my $metadata=&metadata($filename,$what);
1.927     albertel 10952: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1301    raeburn  10953: 	$metadata=&metadata($filename,'parameter_'.$what);
1.927     albertel 10954: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      10955: 
1.1301    raeburn  10956: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 10957: 	if ($symbparm && defined($courseid) && 
1.620     albertel 10958: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 10959: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   10960: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  10961: 				     'course',$mapp,\$recursed,\@recurseup,
                   10962:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 10963: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  10964:                                       [$courseleveli,'map'   ],
1.927     albertel 10965: 				      [$courselevel, 'course']));
                   10966: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 10967: 	}
1.145     www      10968: # ------------------------------------------------------------------ Cascade up
1.218     albertel 10969: 	unless ($space eq '0') {
1.336     albertel 10970: 	    my @parts=split(/_/,$space);
                   10971: 	    my $id=pop(@parts);
                   10972: 	    my $part=join('_',@parts);
                   10973: 	    if ($part eq '') { $part='0'; }
1.927     albertel 10974: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 10975: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  10976: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 10977: 	}
1.395     albertel 10978: 	if ($recurse) { return undef; }
                   10979: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 10980: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      10981: # ---------------------------------------------------- Any other user namespace
                   10982:     } elsif ($realm eq 'environment') {
                   10983: # ----------------------------------------------------------------- environment
1.620     albertel 10984: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   10985: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 10986: 	} else {
1.770     albertel 10987: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   10988: 		return '';
                   10989: 	    }
1.219     albertel 10990: 	    my %returnhash=&userenvironment($udom,$uname,
                   10991: 					    $spacequalifierrest);
                   10992: 	    return $returnhash{$spacequalifierrest};
                   10993: 	}
1.28      www      10994:     } elsif ($realm eq 'system') {
1.48      www      10995: # ----------------------------------------------------------------- system.time
                   10996: 	if ($space eq 'time') {
                   10997: 	    return time;
                   10998:         }
1.696     albertel 10999:     } elsif ($realm eq 'server') {
                   11000: # ----------------------------------------------------------------- system.time
                   11001: 	if ($space eq 'name') {
                   11002: 	    return $ENV{'SERVER_NAME'};
                   11003:         }
1.28      www      11004:     }
1.48      www      11005:     return '';
1.61      www      11006: }
                   11007: 
1.927     albertel 11008: sub get_reply {
                   11009:     my ($reply_value) = @_;
1.940     raeburn  11010:     if (ref($reply_value) eq 'ARRAY') {
                   11011:         if (wantarray) {
                   11012: 	    return @$reply_value;
                   11013:         }
                   11014:         return $reply_value->[0];
                   11015:     } else {
                   11016:         return $reply_value;
1.927     albertel 11017:     }
                   11018: }
                   11019: 
1.691     raeburn  11020: sub check_group_parms {
1.1301    raeburn  11021:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   11022:         $recursed,$recurseupref) = @_;
                   11023:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   11024:                   [$what,'course']);
                   11025:     my $coursereply;
1.691     raeburn  11026:     foreach my $group (@{$groups}) {
1.1301    raeburn  11027:         my @groupitems = ();
1.691     raeburn  11028:         foreach my $level (@levels) {
1.927     albertel 11029:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11030:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11031:         }
1.1301    raeburn  11032:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11033:                                    $env{'course.'.$courseid.'.domain'},
                   11034:                                    'course',$mapp,$recursed,$recurseupref,
                   11035:                                    $courseid,'.['.$group.'].',$what,
                   11036:                                    @groupitems);
                   11037:         last if (defined($coursereply));
1.691     raeburn  11038:     }
                   11039:     return $coursereply;
                   11040: }
                   11041: 
1.1301    raeburn  11042: sub get_map_hierarchy {
1.1302    raeburn  11043:     my ($mapname,$courseid) = @_;
                   11044:     my @recurseup = ();
1.1301    raeburn  11045:     if ($mapname) {
1.1302    raeburn  11046:         if (($cachedmapkey eq $courseid) &&
                   11047:             (abs($cachedmaptime-time)<5)) {
                   11048:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   11049:                 return @{$cachedmaps{$mapname}};
                   11050:             }
                   11051:         }
1.1301    raeburn  11052:         my $navmap = Apache::lonnavmaps::navmap->new();
                   11053:         if (ref($navmap)) {
                   11054:             @recurseup = $navmap->recurseup_maps($mapname);
                   11055:             undef($navmap);
1.1302    raeburn  11056:             $cachedmaps{$mapname} = \@recurseup;
                   11057:             $cachedmaptime=time;
                   11058:             $cachedmapkey=$courseid;
1.1301    raeburn  11059:         }
                   11060:     }
                   11061:     return @recurseup;
                   11062: }
                   11063: 
1.1302    raeburn  11064: }
                   11065: 
1.691     raeburn  11066: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11067:     my ($courseid,@groups) = @_;
                   11068:     @groups = sort(@groups);
1.691     raeburn  11069:     return @groups;
                   11070: }
                   11071: 
1.395     albertel 11072: sub packages_tab_default {
                   11073:     my ($uri,$varname)=@_;
                   11074:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11075: 
                   11076:     my (@extension,@specifics,$do_default);
                   11077:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11078: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11079: 	if ($pack_type eq 'default') {
                   11080: 	    $do_default=1;
                   11081: 	} elsif ($pack_type eq 'extension') {
                   11082: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11083: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11084: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11085: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11086: 	}
                   11087:     }
                   11088:     # first look for a package that matches the requested part id
                   11089:     foreach my $package (@specifics) {
                   11090: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11091: 	next if ($pack_part ne $part);
                   11092: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11093: 	    return $packagetab{"$pack_type&$name&default"};
                   11094: 	}
                   11095:     }
                   11096:     # look for any possible matching non extension_ package
                   11097:     foreach my $package (@specifics) {
                   11098: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11099: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11100: 	    return $packagetab{"$pack_type&$name&default"};
                   11101: 	}
1.585     albertel 11102: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11103: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11104: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11105: 	}
                   11106:     }
1.738     albertel 11107:     # look for any posible extension_ match
                   11108:     foreach my $package (@extension) {
                   11109: 	my ($package,$pack_type)=@{$package};
                   11110: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11111: 	    return $packagetab{"$pack_type&$name&default"};
                   11112: 	}
                   11113: 	if (defined($packagetab{$package."&$name&default"})) {
                   11114: 	    return $packagetab{$package."&$name&default"};
                   11115: 	}
                   11116:     }
                   11117:     # look for a global default setting
                   11118:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11119: 	return $packagetab{"default&$name&default"};
                   11120:     }
1.395     albertel 11121:     return undef;
                   11122: }
                   11123: 
1.334     albertel 11124: sub add_prefix_and_part {
                   11125:     my ($prefix,$part)=@_;
                   11126:     my $keyroot;
                   11127:     if (defined($prefix) && $prefix !~ /^__/) {
                   11128: 	# prefix that has a part already
                   11129: 	$keyroot=$prefix;
                   11130:     } elsif (defined($prefix)) {
                   11131: 	# prefix that is missing a part
                   11132: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11133:     } else {
                   11134: 	# no prefix at all
                   11135: 	if (defined($part)) { $keyroot='_'.$part; }
                   11136:     }
                   11137:     return $keyroot;
                   11138: }
                   11139: 
1.71      www      11140: # ---------------------------------------------------------------- Get metadata
                   11141: 
1.599     albertel 11142: my %metaentry;
1.1070    www      11143: my %importedpartids;
1.71      www      11144: sub metadata {
1.176     www      11145:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11146:     $uri=&declutter($uri);
1.288     albertel 11147:     # if it is a non metadata possible uri return quickly
1.529     albertel 11148:     if (($uri eq '') || 
                   11149: 	(($uri =~ m|^/*adm/|) && 
1.1298    raeburn  11150: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|exttools?)$})) ||
1.1108    raeburn  11151:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11152: 	return undef;
                   11153:     }
1.1261    raeburn  11154:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11155: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11156: 	return undef;
1.288     albertel 11157:     }
1.73      www      11158:     my $filename=$uri;
                   11159:     $uri=~s/\.meta$//;
1.172     www      11160: #
                   11161: # Is the metadata already cached?
1.177     www      11162: # Look at timestamp of caching
1.172     www      11163: # Everything is cached by the main uri, libraries are never directly cached
                   11164: #
1.428     albertel 11165:     if (!defined($liburi)) {
1.599     albertel 11166: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11167: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11168:     }
                   11169:     {
1.1069    www      11170: # Imported parts would go here
1.1070    www      11171:         my %importedids=();
                   11172:         my @origfileimportpartids=();
1.1069    www      11173:         my $importedparts=0;
1.172     www      11174: #
                   11175: # Is this a recursive call for a library?
                   11176: #
1.599     albertel 11177: #	if (! exists($metacache{$uri})) {
                   11178: #	    $metacache{$uri}={};
                   11179: #	}
1.924     albertel 11180: 	my $cachetime = 60*60;
1.171     www      11181:         if ($liburi) {
                   11182: 	    $liburi=&declutter($liburi);
                   11183:             $filename=$liburi;
1.401     bowersj2 11184:         } else {
1.599     albertel 11185: 	    &devalidate_cache_new('meta',$uri);
                   11186: 	    undef(%metaentry);
1.401     bowersj2 11187: 	}
1.140     www      11188:         my %metathesekeys=();
1.73      www      11189:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11190: 	my $metastring;
1.1140    www      11191: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11192: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11193: 	    $metastring = 
1.929     albertel 11194: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11195: 					  ('grade_target' => 'meta'));
                   11196: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11197: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11198:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11199: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11200: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11201: 	    $metastring=&getfile($file);
1.489     albertel 11202: 	}
1.208     albertel 11203:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11204:         my $token;
1.140     www      11205:         undef %metathesekeys;
1.71      www      11206:         while ($token=$parser->get_token) {
1.339     albertel 11207: 	    if ($token->[0] eq 'S') {
                   11208: 		if (defined($token->[2]->{'package'})) {
1.172     www      11209: #
                   11210: # This is a package - get package info
                   11211: #
1.339     albertel 11212: 		    my $package=$token->[2]->{'package'};
                   11213: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11214: 		    if (defined($token->[2]->{'id'})) { 
                   11215: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11216: 		    }
1.599     albertel 11217: 		    if ($metaentry{':packages'}) {
                   11218: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11219: 		    } else {
1.599     albertel 11220: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11221: 		    }
1.736     albertel 11222: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11223: 			my $part=$keyroot;
                   11224: 			$part=~s/^\_//;
1.736     albertel 11225: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11226: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11227: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11228: 			    # ignore package.tab specified default values
                   11229:                             # here &package_tab_default() will fetch those
                   11230: 			    if ($subp eq 'default') { next; }
1.736     albertel 11231: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11232: 			    my $unikey;
                   11233: 			    if ($pack =~ /_0$/) {
                   11234: 				$unikey='parameter_0_'.$name;
                   11235: 				$part=0;
                   11236: 			    } else {
                   11237: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11238: 			    }
1.339     albertel 11239: 			    if ($subp eq 'display') {
                   11240: 				$value.=' [Part: '.$part.']';
                   11241: 			    }
1.599     albertel 11242: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11243: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11244: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11245: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11246: 			    }
1.599     albertel 11247: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11248: 				$metaentry{':'.$unikey}=
                   11249: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11250: 			    }
1.339     albertel 11251: 			}
                   11252: 		    }
                   11253: 		} else {
1.172     www      11254: #
                   11255: # This is not a package - some other kind of start tag
1.339     albertel 11256: #
                   11257: 		    my $entry=$token->[1];
1.1068    www      11258: 		    my $unikey='';
1.175     www      11259: 
1.339     albertel 11260: 		    if ($entry eq 'import') {
1.175     www      11261: #
                   11262: # Importing a library here
1.339     albertel 11263: #
1.1067    www      11264:                         my $location=$parser->get_text('/import');
                   11265:                         my $dir=$filename;
                   11266:                         $dir=~s|[^/]*$||;
                   11267:                         $location=&filelocation($dir,$location);
1.1069    www      11268:                        
1.1068    www      11269:                         my $importmode=$token->[2]->{'importmode'};
                   11270:                         if ($importmode eq 'problem') {
1.1069    www      11271: # Import as problem/response
1.1068    www      11272:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11273:                         } elsif ($importmode eq 'part') {
                   11274: # Import as part(s)
1.1069    www      11275:                            $importedparts=1;
                   11276: # We need to get the original file and the imported file to get the part order correct
                   11277: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   11278: # Load and inspect original file
1.1070    www      11279:                            if ($#origfileimportpartids<0) {
                   11280:                               undef(%importedpartids);
                   11281:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11282:                               my $origfile=&getfile($origfilelocation);
                   11283:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11284:                            }
                   11285: 
1.1069    www      11286: # Load and inspect imported file
                   11287:                            my $impfile=&getfile($location);
                   11288:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11289:                            if ($#impfilepartids>=0) {
                   11290: # This problem had parts
1.1070    www      11291:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11292:                            } else {
                   11293: # Importing by turning a single problem into a problem part
                   11294: # It gets the import-tags ID as part-ID
                   11295:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11296:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11297:                            }
1.1068    www      11298:                         } else {
                   11299: # Normal import
                   11300:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11301:                            if (defined($token->[2]->{'id'})) {
                   11302:                               $unikey.='_'.$token->[2]->{'id'};
                   11303:                            }
1.1067    www      11304:                         }
                   11305: 
1.339     albertel 11306: 			if ($depthcount<20) {
1.736     albertel 11307: 			    my $metadata = 
                   11308: 				&metadata($uri,'keys', $location,$unikey,
                   11309: 					  $depthcount+1);
                   11310: 			    foreach my $meta (split(',',$metadata)) {
                   11311: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   11312: 				$metathesekeys{$meta}=1;
1.339     albertel 11313: 			    }
1.1068    www      11314: 			
                   11315:                         }
1.1067    www      11316: 		    } else {
                   11317: #
                   11318: # Not importing, some other kind of non-package, non-library start tag
                   11319: # 
                   11320:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11321:                         if (defined($token->[2]->{'id'})) {
                   11322:                             $unikey.='_'.$token->[2]->{'id'};
                   11323:                         }
1.339     albertel 11324: 			if (defined($token->[2]->{'name'})) { 
                   11325: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   11326: 			}
                   11327: 			$metathesekeys{$unikey}=1;
1.736     albertel 11328: 			foreach my $param (@{$token->[3]}) {
                   11329: 			    $metaentry{':'.$unikey.'.'.$param} =
                   11330: 				$token->[2]->{$param};
1.339     albertel 11331: 			}
                   11332: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 11333: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 11334: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   11335: 		 # only ws inside the tag, and not in default, so use default
                   11336: 		 # as value
1.599     albertel 11337: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 11338: 			} elsif ( $internaltext =~ /\S/ ) {
                   11339: 		  # something interesting inside the tag
                   11340: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 11341: 			} else {
1.908     albertel 11342: 		  # no interesting values, don't set a default
1.339     albertel 11343: 			}
1.172     www      11344: # end of not-a-package not-a-library import
1.339     albertel 11345: 		    }
1.172     www      11346: # end of not-a-package start tag
1.339     albertel 11347: 		}
1.172     www      11348: # the next is the end of "start tag"
1.339     albertel 11349: 	    }
                   11350: 	}
1.483     albertel 11351: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 11352: 	$extension = lc($extension);
                   11353: 	if ($extension eq 'htm') { $extension='html'; }
                   11354: 
1.737     albertel 11355: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 11356: 	    #no specific packages #how's our extension
                   11357: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 11358: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 11359: 					 \%metathesekeys);
                   11360: 	}
1.883     albertel 11361: 
                   11362: 	if (!exists($metaentry{':packages'})
                   11363: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 11364: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 11365: 		#no specific packages well let's get default then
                   11366: 		if ($key!~/^default&/) { next; }
1.488     albertel 11367: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 11368: 					     \%metathesekeys);
                   11369: 	    }
                   11370: 	}
1.338     www      11371: # are there custom rights to evaluate
1.599     albertel 11372: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 11373: 
1.338     www      11374:     #
                   11375:     # Importing a rights file here
1.339     albertel 11376:     #
                   11377: 	    unless ($depthcount) {
1.599     albertel 11378: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 11379: 		my $dir=$filename;
                   11380: 		$dir=~s|[^/]*$||;
                   11381: 		$location=&filelocation($dir,$location);
1.736     albertel 11382: 		my $rights_metadata =
                   11383: 		    &metadata($uri,'keys',$location,'_rights',
                   11384: 			      $depthcount+1);
                   11385: 		foreach my $rights (split(',',$rights_metadata)) {
                   11386: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   11387: 		    $metathesekeys{$rights}=1;
1.339     albertel 11388: 		}
                   11389: 	    }
                   11390: 	}
1.737     albertel 11391: 	# uniqifiy package listing
                   11392: 	my %seen;
                   11393: 	my @uniq_packages =
                   11394: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   11395: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   11396: 
1.1070    www      11397:         if ($importedparts) {
                   11398: # We had imported parts and need to rebuild partorder
                   11399:            $metaentry{':partorder'}='';
                   11400:            $metathesekeys{'partorder'}=1;
                   11401:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   11402:                if ($origfileimportpartids[$index] eq 'part') {
                   11403: # original part, part of the problem
                   11404:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   11405:                } else {
                   11406: # we have imported parts at this position
                   11407:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   11408:                }
                   11409:            }
                   11410:            $metaentry{':partorder'}=~s/^\,//;
                   11411:         }
                   11412: 
1.737     albertel 11413: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 11414: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  11415: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 11416: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      11417: # this is the end of "was not already recently cached
1.71      www      11418:     }
1.599     albertel 11419:     return $metaentry{':'.$what};
1.261     albertel 11420: }
                   11421: 
1.488     albertel 11422: sub metadata_create_package_def {
1.483     albertel 11423:     my ($uri,$key,$package,$metathesekeys)=@_;
                   11424:     my ($pack,$name,$subp)=split(/\&/,$key);
                   11425:     if ($subp eq 'default') { next; }
                   11426:     
1.599     albertel 11427:     if (defined($metaentry{':packages'})) {
                   11428: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 11429:     } else {
1.599     albertel 11430: 	$metaentry{':packages'}=$package;
1.483     albertel 11431:     }
                   11432:     my $value=$packagetab{$key};
                   11433:     my $unikey;
                   11434:     $unikey='parameter_0_'.$name;
1.599     albertel 11435:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 11436:     $$metathesekeys{$unikey}=1;
1.599     albertel 11437:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11438: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 11439:     }
1.599     albertel 11440:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   11441: 	$metaentry{':'.$unikey}=
                   11442: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 11443:     }
                   11444: }
                   11445: 
1.261     albertel 11446: sub metadata_generate_part0 {
                   11447:     my ($metadata,$metacache,$uri) = @_;
                   11448:     my %allnames;
1.737     albertel 11449:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 11450: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 11451: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   11452: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 11453: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 11454: 	    $allnames{$name}=$part;
                   11455: 	  }
                   11456: 	}
                   11457:     }
                   11458:     foreach my $name (keys(%allnames)) {
                   11459:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 11460:       my $key=":parameter_0_$name";
1.261     albertel 11461:       $$metacache{"$key.part"}='0';
                   11462:       $$metacache{"$key.name"}=$name;
1.428     albertel 11463:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 11464: 					   $allnames{$name}.'_'.$name.
                   11465: 					   '.type'};
1.428     albertel 11466:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 11467: 			     '.display'};
1.644     www      11468:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 11469:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 11470:       $$metacache{"$key.display"}=$olddis;
                   11471:     }
1.71      www      11472: }
                   11473: 
1.764     albertel 11474: # ------------------------------------------------------ Devalidate title cache
                   11475: 
                   11476: sub devalidate_title_cache {
                   11477:     my ($url)=@_;
                   11478:     if (!$env{'request.course.id'}) { return; }
                   11479:     my $symb=&symbread($url);
                   11480:     if (!$symb) { return; }
                   11481:     my $key=$env{'request.course.id'}."\0".$symb;
                   11482:     &devalidate_cache_new('title',$key);
                   11483: }
                   11484: 
1.1014    droeschl 11485: # ------------------------------------------------- Get the title of a course
                   11486: 
                   11487: sub current_course_title {
                   11488:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   11489: }
1.301     www      11490: # ------------------------------------------------- Get the title of a resource
                   11491: 
                   11492: sub gettitle {
                   11493:     my $urlsymb=shift;
                   11494:     my $symb=&symbread($urlsymb);
1.534     albertel 11495:     if ($symb) {
1.620     albertel 11496: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 11497: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 11498: 	if (defined($cached)) { 
                   11499: 	    return $result;
                   11500: 	}
1.534     albertel 11501: 	my ($map,$resid,$url)=&decode_symb($symb);
                   11502: 	my $title='';
1.907     albertel 11503: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   11504: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   11505: 	} else {
                   11506: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11507: 		    &GDBM_READER(),0640)) {
                   11508: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   11509: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   11510: 		untie(%bighash);
                   11511: 	    }
1.534     albertel 11512: 	}
                   11513: 	$title=~s/\&colon\;/\:/gs;
                   11514: 	if ($title) {
1.1159    www      11515: # Remember both $symb and $title for dynamic metadata
                   11516:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      11517:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      11518: # Cache this title and then return it
1.599     albertel 11519: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 11520: 	}
                   11521: 	$urlsymb=$url;
                   11522:     }
                   11523:     my $title=&metadata($urlsymb,'title');
                   11524:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   11525:     return $title;
1.301     www      11526: }
1.613     albertel 11527: 
1.614     albertel 11528: sub get_slot {
                   11529:     my ($which,$cnum,$cdom)=@_;
                   11530:     if (!$cnum || !$cdom) {
1.790     albertel 11531: 	(undef,my $courseid)=&whichuser();
1.620     albertel 11532: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   11533: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 11534:     }
1.703     albertel 11535:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   11536:     my %slotinfo;
                   11537:     if (exists($remembered{$key})) {
                   11538: 	$slotinfo{$which} = $remembered{$key};
                   11539:     } else {
                   11540: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   11541: 	&Apache::lonhomework::showhash(%slotinfo);
                   11542: 	my ($tmp)=keys(%slotinfo);
                   11543: 	if ($tmp=~/^error:/) { return (); }
                   11544: 	$remembered{$key} = $slotinfo{$which};
                   11545:     }
1.616     albertel 11546:     if (ref($slotinfo{$which}) eq 'HASH') {
                   11547: 	return %{$slotinfo{$which}};
                   11548:     }
                   11549:     return $slotinfo{$which};
1.614     albertel 11550: }
1.1150    raeburn  11551: 
                   11552: sub get_reservable_slots {
                   11553:     my ($cnum,$cdom,$uname,$udom) = @_;
                   11554:     my $now = time;
                   11555:     my $reservable_info;
                   11556:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   11557:     if (exists($remembered{$key})) {
                   11558:         $reservable_info = $remembered{$key};
                   11559:     } else {
                   11560:         my %resv;
                   11561:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   11562:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   11563:         $reservable_info = \%resv;
                   11564:         $remembered{$key} = $reservable_info;
                   11565:     }
                   11566:     return $reservable_info;
                   11567: }
                   11568: 
                   11569: sub get_course_slots {
                   11570:     my ($cnum,$cdom) = @_;
                   11571:     my $hashid=$cnum.':'.$cdom;
                   11572:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   11573:     if (defined($cached)) {
                   11574:         if (ref($result) eq 'HASH') {
                   11575:             return %{$result};
                   11576:         }
                   11577:     } else {
                   11578:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   11579:         my ($tmp) = keys(%slots);
                   11580:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  11581:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  11582:             return %slots;
                   11583:         }
                   11584:     }
                   11585:     return;
                   11586: }
                   11587: 
                   11588: sub devalidate_slots_cache {
                   11589:     my ($cnum,$cdom)=@_;
                   11590:     my $hashid=$cnum.':'.$cdom;
                   11591:     &devalidate_cache_new('allslots',$hashid);
                   11592: }
                   11593: 
1.1181    raeburn  11594: sub get_coursechange {
                   11595:     my ($cdom,$cnum) = @_;
                   11596:     if ($cdom eq '' || $cnum eq '') {
                   11597:         return unless ($env{'request.course.id'});
                   11598:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   11599:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11600:     }
                   11601:     my $hashid=$cdom.'_'.$cnum;
                   11602:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   11603:     if ((defined($cached)) && ($change ne '')) {
                   11604:         return $change;
                   11605:     } else {
                   11606:         my %crshash;
                   11607:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   11608:         if ($crshash{'internal.contentchange'} eq '') {
                   11609:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   11610:             if ($change eq '') {
                   11611:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   11612:                 $change = $crshash{'internal.created'};
                   11613:             }
                   11614:         } else {
                   11615:             $change = $crshash{'internal.contentchange'};
                   11616:         }
                   11617:         my $cachetime = 600;
                   11618:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   11619:     }
                   11620:     return $change;
                   11621: }
                   11622: 
                   11623: sub devalidate_coursechange_cache {
                   11624:     my ($cnum,$cdom)=@_;
                   11625:     my $hashid=$cnum.':'.$cdom;
                   11626:     &devalidate_cache_new('crschange',$hashid);
                   11627: }
                   11628: 
1.31      www      11629: # ------------------------------------------------- Update symbolic store links
                   11630: 
                   11631: sub symblist {
                   11632:     my ($mapname,%newhash)=@_;
1.438     www      11633:     $mapname=&deversion(&declutter($mapname));
1.31      www      11634:     my %hash;
1.620     albertel 11635:     if (($env{'request.course.fn'}) && (%newhash)) {
                   11636:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11637:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  11638: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 11639: 		next if ($url eq 'last_known'
                   11640: 			 && $env{'form.no_update_last_known'});
                   11641: 		$hash{declutter($url)}=&encode_symb($mapname,
                   11642: 						    $newhash{$url}->[1],
                   11643: 						    $newhash{$url}->[0]);
1.191     harris41 11644:             }
1.31      www      11645:             if (untie(%hash)) {
                   11646: 		return 'ok';
                   11647:             }
                   11648:         }
                   11649:     }
                   11650:     return 'error';
1.212     www      11651: }
                   11652: 
                   11653: # --------------------------------------------------------------- Verify a symb
                   11654: 
                   11655: sub symbverify {
1.1190    raeburn  11656:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      11657:     my $thisfn=$thisurl;
1.439     www      11658:     $thisfn=&declutter($thisfn);
1.215     www      11659: # direct jump to resource in page or to a sequence - will construct own symbs
                   11660:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   11661: # check URL part
1.409     www      11662:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      11663: 
1.431     www      11664:     unless ($url eq $thisfn) { return 0; }
1.213     www      11665: 
1.216     www      11666:     $symb=&symbclean($symb);
1.510     www      11667:     $thisurl=&deversion($thisurl);
1.439     www      11668:     $thisfn=&deversion($thisfn);
1.213     www      11669: 
                   11670:     my %bighash;
                   11671:     my $okay=0;
1.431     www      11672: 
1.620     albertel 11673:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11674:                             &GDBM_READER(),0640)) {
1.1204    raeburn  11675:         my $noclutter;
1.1032    raeburn  11676:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   11677:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  11678:             if ($map =~ m{^uploaded/.+\.page$}) {
                   11679:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   11680:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   11681:                 $noclutter = 1;
                   11682:             }
                   11683:         }
                   11684:         my $ids;
                   11685:         if ($noclutter) {
                   11686:             $ids=$bighash{'ids_'.$thisurl};
                   11687:         } else {
                   11688:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  11689:         }
1.1102    raeburn  11690:         unless ($ids) {
                   11691:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   11692:             $ids=$bighash{$idkey};
1.216     www      11693:         }
                   11694:         if ($ids) {
                   11695: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  11696:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  11697:                 $symb =~ s/\?.+$//;
1.1202    raeburn  11698:             }
1.800     albertel 11699: 	    foreach my $id (split(/\,/,$ids)) {
                   11700: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      11701:                if (
                   11702:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  11703:    eq $symb) {
                   11704:                    if (ref($encstate)) {
                   11705:                        $$encstate = $bighash{'encrypted_'.$id};
                   11706:                    }
1.620     albertel 11707: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  11708: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   11709:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  11710: 		       $okay=1;
1.1202    raeburn  11711:                        last;
1.582     albertel 11712: 		   }
                   11713: 	       }
1.216     www      11714: 	   }
                   11715:         }
1.213     www      11716: 	untie(%bighash);
                   11717:     }
                   11718:     return $okay;
1.31      www      11719: }
                   11720: 
1.210     www      11721: # --------------------------------------------------------------- Clean-up symb
                   11722: 
                   11723: sub symbclean {
                   11724:     my $symb=shift;
1.568     albertel 11725:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      11726: # remove version from map
                   11727:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      11728: 
1.210     www      11729: # remove version from URL
                   11730:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      11731: 
1.507     www      11732: # remove wrapper
                   11733: 
1.510     www      11734:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 11735:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      11736:     return $symb;
1.409     www      11737: }
                   11738: 
                   11739: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 11740: 
                   11741: sub encode_symb {
                   11742:     my ($map,$resid,$url)=@_;
                   11743:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   11744: }
1.409     www      11745: 
                   11746: sub decode_symb {
1.568     albertel 11747:     my $symb=shift;
                   11748:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   11749:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      11750:     return (&fixversion($map),$resid,&fixversion($url));
                   11751: }
                   11752: 
                   11753: sub fixversion {
                   11754:     my $fn=shift;
1.609     banghart 11755:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      11756:     my %bighash;
                   11757:     my $uri=&clutter($fn);
1.620     albertel 11758:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      11759: # is this cached?
1.599     albertel 11760:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      11761:     if (defined($cached)) { return $result; }
                   11762: # unfortunately not cached, or expired
1.620     albertel 11763:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      11764: 	    &GDBM_READER(),0640)) {
                   11765:  	if ($bighash{'version_'.$uri}) {
                   11766:  	    my $version=$bighash{'version_'.$uri};
1.444     www      11767:  	    unless (($version eq 'mostrecent') || 
                   11768: 		    ($version==&getversion($uri))) {
1.440     www      11769:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   11770:  	    }
                   11771:  	}
                   11772:  	untie %bighash;
1.413     www      11773:     }
1.599     albertel 11774:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      11775: }
                   11776: 
                   11777: sub deversion {
                   11778:     my $url=shift;
                   11779:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   11780:     return $url;
1.210     www      11781: }
                   11782: 
1.31      www      11783: # ------------------------------------------------------ Return symb list entry
                   11784: 
                   11785: sub symbread {
1.1282    raeburn  11786:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265    raeburn  11787:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1282    raeburn  11788:     if (defined($env{$cache_str})) {
                   11789:         if ($ignorecachednull) {
                   11790:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   11791:         } else {
                   11792:             return $env{$cache_str};
                   11793:         }
                   11794:     }
1.242     www      11795: # no filename provided? try from environment
1.1265    raeburn  11796:     unless ($thisfn) {
1.620     albertel 11797:         if ($env{'request.symb'}) {
                   11798: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 11799: 	}
1.620     albertel 11800: 	$thisfn=$env{'request.filename'};
1.44      www      11801:     }
1.569     albertel 11802:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      11803: # is that filename actually a symb? Verify, clean, and return
                   11804:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 11805: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 11806: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 11807: 	}
1.242     www      11808:     }
1.44      www      11809:     $thisfn=declutter($thisfn);
1.31      www      11810:     my %hash;
1.37      www      11811:     my %bighash;
                   11812:     my $syval='';
1.620     albertel 11813:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  11814:         my $targetfn = $thisfn;
1.609     banghart 11815:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  11816:             $targetfn = 'adm/wrapper/'.$thisfn;
                   11817:         }
1.687     albertel 11818: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   11819: 	    $targetfn=$1;
                   11820: 	}
1.620     albertel 11821:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11822:                       &GDBM_READER(),0640)) {
1.481     raeburn  11823: 	    $syval=$hash{$targetfn};
1.37      www      11824:             untie(%hash);
                   11825:         }
                   11826: # ---------------------------------------------------------- There was an entry
                   11827:         if ($syval) {
1.601     albertel 11828: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 11829: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  11830: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11831: 		    #return $env{$cache_str}='';
1.601     albertel 11832: 		#}    
                   11833: 		#$syval.=$1;
                   11834: 	    #}
1.37      www      11835:         } else {
                   11836: # ------------------------------------------------------- Was not in symb table
1.620     albertel 11837:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11838:                             &GDBM_READER(),0640)) {
1.37      www      11839: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      11840:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      11841:               unless ($ids) { 
                   11842:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      11843:               }
                   11844:               unless ($ids) {
                   11845: # alias?
                   11846: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      11847:               }
1.37      www      11848:               if ($ids) {
                   11849: # ------------------------------------------------------------------- Has ID(s)
                   11850:                  my @possibilities=split(/\,/,$ids);
1.39      www      11851:                  if ($#possibilities==0) {
                   11852: # ----------------------------------------------- There is only one possibility
1.37      www      11853: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 11854: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11855: 						    $resid,$thisfn);
1.1282    raeburn  11856:                      if (ref($possibles) eq 'HASH') {
                   11857:                          $possibles->{$syval} = 1;    
                   11858:                      }
                   11859:                      if ($checkforblock) {
                   11860:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   11861:                          if (@blockers) {
                   11862:                              $syval = '';
                   11863:                              return;
                   11864:                          }
                   11865:                      }
                   11866:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      11867: # ------------------------------------------ There is more than one possibility
                   11868:                      my $realpossible=0;
1.800     albertel 11869:                      foreach my $id (@possibilities) {
                   11870: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  11871:                          my $canaccess;
                   11872:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   11873:                              $canaccess = 1;
                   11874:                          } else { 
                   11875:                              $canaccess = &allowed('bre',$file);
                   11876:                          }
                   11877:                          if ($canaccess) {
                   11878:          		     my ($mapid,$resid)=split(/\./,$id);
                   11879:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   11880:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11881: 						             $resid,$thisfn);
                   11882:                                  if (ref($possibles) eq 'HASH') {
                   11883:                                      $possibles->{$syval} = 1;
                   11884:                                  }
                   11885:                                  if ($checkforblock) {
                   11886:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   11887:                                      unless (@blockers > 0) {
                   11888:                                          $syval = $poss_syval;
                   11889:                                          $realpossible++;
                   11890:                                      }
                   11891:                                  } else {
                   11892:                                      $syval = $poss_syval;
                   11893:                                      $realpossible++;
                   11894:                                  }
                   11895:                              }
1.39      www      11896: 			 }
1.191     harris41 11897:                      }
1.39      www      11898: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      11899:                  } else {
                   11900:                      $syval='';
1.37      www      11901:                  }
                   11902: 	      }
1.1282    raeburn  11903:               untie(%bighash);
1.481     raeburn  11904:            }
1.31      www      11905:         }
1.62      www      11906:         if ($syval) {
1.620     albertel 11907: 	    return $env{$cache_str}=$syval;
1.62      www      11908:         }
1.31      www      11909:     }
1.949     raeburn  11910:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11911:     return $env{$cache_str}='';
1.31      www      11912: }
                   11913: 
                   11914: # ---------------------------------------------------------- Return random seed
                   11915: 
1.32      www      11916: sub numval {
                   11917:     my $txt=shift;
                   11918:     $txt=~tr/A-J/0-9/;
                   11919:     $txt=~tr/a-j/0-9/;
                   11920:     $txt=~tr/K-T/0-9/;
                   11921:     $txt=~tr/k-t/0-9/;
                   11922:     $txt=~tr/U-Z/0-5/;
                   11923:     $txt=~tr/u-z/0-5/;
                   11924:     $txt=~s/\D//g;
1.564     albertel 11925:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      11926:     return int($txt);
1.368     albertel 11927: }
                   11928: 
1.484     albertel 11929: sub numval2 {
                   11930:     my $txt=shift;
                   11931:     $txt=~tr/A-J/0-9/;
                   11932:     $txt=~tr/a-j/0-9/;
                   11933:     $txt=~tr/K-T/0-9/;
                   11934:     $txt=~tr/k-t/0-9/;
                   11935:     $txt=~tr/U-Z/0-5/;
                   11936:     $txt=~tr/u-z/0-5/;
                   11937:     $txt=~s/\D//g;
                   11938:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11939:     my $total;
                   11940:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 11941:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 11942:     return int($total);
                   11943: }
                   11944: 
1.575     albertel 11945: sub numval3 {
                   11946:     use integer;
                   11947:     my $txt=shift;
                   11948:     $txt=~tr/A-J/0-9/;
                   11949:     $txt=~tr/a-j/0-9/;
                   11950:     $txt=~tr/K-T/0-9/;
                   11951:     $txt=~tr/k-t/0-9/;
                   11952:     $txt=~tr/U-Z/0-5/;
                   11953:     $txt=~tr/u-z/0-5/;
                   11954:     $txt=~s/\D//g;
                   11955:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11956:     my $total;
                   11957:     foreach my $val (@txts) { $total+=$val; }
                   11958:     if ($_64bit) { $total=(($total<<32)>>32); }
                   11959:     return $total;
                   11960: }
                   11961: 
1.675     albertel 11962: sub digest {
                   11963:     my ($data)=@_;
                   11964:     my $digest=&Digest::MD5::md5($data);
                   11965:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   11966:     my ($e,$f);
                   11967:     {
                   11968:         use integer;
                   11969:         $e=($a+$b);
                   11970:         $f=($c+$d);
                   11971:         if ($_64bit) {
                   11972:             $e=(($e<<32)>>32);
                   11973:             $f=(($f<<32)>>32);
                   11974:         }
                   11975:     }
                   11976:     if (wantarray) {
                   11977: 	return ($e,$f);
                   11978:     } else {
                   11979: 	my $g;
                   11980: 	{
                   11981: 	    use integer;
                   11982: 	    $g=($e+$f);
                   11983: 	    if ($_64bit) {
                   11984: 		$g=(($g<<32)>>32);
                   11985: 	    }
                   11986: 	}
                   11987: 	return $g;
                   11988:     }
                   11989: }
                   11990: 
1.368     albertel 11991: sub latest_rnd_algorithm_id {
1.675     albertel 11992:     return '64bit5';
1.366     albertel 11993: }
1.32      www      11994: 
1.503     albertel 11995: sub get_rand_alg {
                   11996:     my ($courseid)=@_;
1.790     albertel 11997:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 11998:     if ($courseid) {
1.620     albertel 11999: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12000:     }
                   12001:     return &latest_rnd_algorithm_id();
                   12002: }
                   12003: 
1.562     albertel 12004: sub validCODE {
                   12005:     my ($CODE)=@_;
                   12006:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12007:     return 0;
                   12008: }
                   12009: 
1.491     albertel 12010: sub getCODE {
1.620     albertel 12011:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12012:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12013: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12014: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12015: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12016:     }
                   12017:     return undef;
                   12018: }
1.1133    foxr     12019: #
                   12020: #  Determines the random seed for a specific context:
                   12021: #
                   12022: # parameters:
                   12023: #   symb      - in course context the symb for the seed.
                   12024: #   course_id - The course id of the form domain_coursenum.
                   12025: #   domain    - Domain for the user.
                   12026: #   course    - Course for the user.
                   12027: #   cenv      - environment of the course.
                   12028: #
                   12029: # NOTE:
                   12030: #   All parameters are picked out of the environment if missing
                   12031: #   or not defined.
                   12032: #   If a symb cannot be determined the current time is used instead.
                   12033: #
                   12034: #  For a given well defined symb, courside, domain, username,
                   12035: #  and course environment, the seed is reproducible.
                   12036: #
1.31      www      12037: sub rndseed {
1.1133    foxr     12038:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12039:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12040:     if (!defined($symb)) {
1.366     albertel 12041: 	unless ($symb=$wsymb) { return time; }
                   12042:     }
1.1146    foxr     12043:     if (!defined $courseid) { 
                   12044: 	$courseid=$wcourseid; 
                   12045:     }
                   12046:     if (!defined $domain) { $domain=$wdomain; }
                   12047:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12048: 
                   12049:     my $which;
                   12050:     if (defined($cenv->{'rndseed'})) {
                   12051: 	$which = $cenv->{'rndseed'};
                   12052:     } else {
                   12053: 	$which =&get_rand_alg($courseid);
                   12054:     }
1.491     albertel 12055:     if (defined(&getCODE())) {
1.1133    foxr     12056: 
1.675     albertel 12057: 	if ($which eq '64bit5') {
                   12058: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12059: 	} elsif ($which eq '64bit4') {
1.575     albertel 12060: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12061: 	} else {
                   12062: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12063: 	}
1.675     albertel 12064:     } elsif ($which eq '64bit5') {
                   12065: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12066:     } elsif ($which eq '64bit4') {
                   12067: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12068:     } elsif ($which eq '64bit3') {
                   12069: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12070:     } elsif ($which eq '64bit2') {
                   12071: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12072:     } elsif ($which eq '64bit') {
                   12073: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12074:     }
                   12075:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12076: }
                   12077: 
                   12078: sub rndseed_32bit {
                   12079:     my ($symb,$courseid,$domain,$username)=@_;
                   12080:     {
                   12081: 	use integer;
                   12082: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12083: 	my $symbseed=numval($symb) << 22;
                   12084: 	my $namechck=unpack("%32C*",$username) << 17;
                   12085: 	my $nameseed=numval($username) << 12;
                   12086: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12087: 	my $courseseed=unpack("%32C*",$courseid);
                   12088: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12089: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12090: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12091: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12092: 	return $num;
                   12093:     }
                   12094: }
                   12095: 
                   12096: sub rndseed_64bit {
                   12097:     my ($symb,$courseid,$domain,$username)=@_;
                   12098:     {
                   12099: 	use integer;
                   12100: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12101: 	my $symbseed=numval($symb) << 10;
                   12102: 	my $namechck=unpack("%32S*",$username);
                   12103: 	
                   12104: 	my $nameseed=numval($username) << 21;
                   12105: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12106: 	my $courseseed=unpack("%32S*",$courseid);
                   12107: 	
                   12108: 	my $num1=$symbchck+$symbseed+$namechck;
                   12109: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12110: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12111: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12112: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12113: 	return "$num1,$num2";
1.155     albertel 12114:     }
1.366     albertel 12115: }
                   12116: 
1.443     albertel 12117: sub rndseed_64bit2 {
                   12118:     my ($symb,$courseid,$domain,$username)=@_;
                   12119:     {
                   12120: 	use integer;
                   12121: 	# strings need to be an even # of cahracters long, it it is odd the
                   12122:         # last characters gets thrown away
                   12123: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12124: 	my $symbseed=numval($symb) << 10;
                   12125: 	my $namechck=unpack("%32S*",$username.' ');
                   12126: 	
                   12127: 	my $nameseed=numval($username) << 21;
1.501     albertel 12128: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12129: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12130: 	
                   12131: 	my $num1=$symbchck+$symbseed+$namechck;
                   12132: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12133: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12134: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12135: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12136: 	return "$num1,$num2";
                   12137:     }
                   12138: }
                   12139: 
                   12140: sub rndseed_64bit3 {
                   12141:     my ($symb,$courseid,$domain,$username)=@_;
                   12142:     {
                   12143: 	use integer;
                   12144: 	# strings need to be an even # of cahracters long, it it is odd the
                   12145:         # last characters gets thrown away
                   12146: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12147: 	my $symbseed=numval2($symb) << 10;
                   12148: 	my $namechck=unpack("%32S*",$username.' ');
                   12149: 	
                   12150: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12151: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12152: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12153: 	
                   12154: 	my $num1=$symbchck+$symbseed+$namechck;
                   12155: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12156: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12157: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12158: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12159: 	
1.503     albertel 12160: 	return "$num1:$num2";
1.443     albertel 12161:     }
                   12162: }
                   12163: 
1.575     albertel 12164: sub rndseed_64bit4 {
                   12165:     my ($symb,$courseid,$domain,$username)=@_;
                   12166:     {
                   12167: 	use integer;
                   12168: 	# strings need to be an even # of cahracters long, it it is odd the
                   12169:         # last characters gets thrown away
                   12170: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12171: 	my $symbseed=numval3($symb) << 10;
                   12172: 	my $namechck=unpack("%32S*",$username.' ');
                   12173: 	
                   12174: 	my $nameseed=numval3($username) << 21;
                   12175: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12176: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12177: 	
                   12178: 	my $num1=$symbchck+$symbseed+$namechck;
                   12179: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12180: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12181: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12182: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12183: 	
1.575     albertel 12184: 	return "$num1:$num2";
                   12185:     }
                   12186: }
                   12187: 
1.675     albertel 12188: sub rndseed_64bit5 {
                   12189:     my ($symb,$courseid,$domain,$username)=@_;
                   12190:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12191:     return "$num1:$num2";
                   12192: }
                   12193: 
1.366     albertel 12194: sub rndseed_CODE_64bit {
                   12195:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12196:     {
1.366     albertel 12197: 	use integer;
1.443     albertel 12198: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12199: 	my $symbseed=numval2($symb);
1.491     albertel 12200: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12201: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12202: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12203: 	my $num1=$symbseed+$CODEchck;
                   12204: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12205: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12206: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12207: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12208: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12209: 	return "$num1:$num2";
1.366     albertel 12210:     }
                   12211: }
                   12212: 
1.575     albertel 12213: sub rndseed_CODE_64bit4 {
                   12214:     my ($symb,$courseid,$domain,$username)=@_;
                   12215:     {
                   12216: 	use integer;
                   12217: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12218: 	my $symbseed=numval3($symb);
                   12219: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12220: 	my $CODEseed=numval3(&getCODE());
                   12221: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12222: 	my $num1=$symbseed+$CODEchck;
                   12223: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12224: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12225: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12226: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12227: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12228: 	return "$num1:$num2";
                   12229:     }
                   12230: }
                   12231: 
1.675     albertel 12232: sub rndseed_CODE_64bit5 {
                   12233:     my ($symb,$courseid,$domain,$username)=@_;
                   12234:     my $code = &getCODE();
                   12235:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12236:     return "$num1:$num2";
                   12237: }
                   12238: 
1.366     albertel 12239: sub setup_random_from_rndseed {
                   12240:     my ($rndseed)=@_;
1.503     albertel 12241:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  12242:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12243:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12244:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   12245:         } else {
                   12246:             &Math::Random::random_set_seed($num1,$num2);
                   12247:         }
1.366     albertel 12248:     } else {
                   12249: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12250:     }
1.36      albertel 12251: }
                   12252: 
1.474     albertel 12253: sub latest_receipt_algorithm_id {
1.835     albertel 12254:     return 'receipt3';
1.474     albertel 12255: }
                   12256: 
1.480     www      12257: sub recunique {
                   12258:     my $fucourseid=shift;
                   12259:     my $unique;
1.835     albertel 12260:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   12261: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12262: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      12263:     } else {
                   12264: 	$unique=$perlvar{'lonReceipt'};
                   12265:     }
                   12266:     return unpack("%32C*",$unique);
                   12267: }
                   12268: 
                   12269: sub recprefix {
                   12270:     my $fucourseid=shift;
                   12271:     my $prefix;
1.835     albertel 12272:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   12273: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12274: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      12275:     } else {
                   12276: 	$prefix=$perlvar{'lonHostID'};
                   12277:     }
                   12278:     return unpack("%32C*",$prefix);
                   12279: }
                   12280: 
1.76      www      12281: sub ireceipt {
1.474     albertel 12282:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 12283: 
                   12284:     my $return =&recprefix($fucourseid).'-';
                   12285: 
                   12286:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   12287: 	$env{'request.state'} eq 'construct') {
                   12288: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   12289: 	return $return;
                   12290:     }
                   12291: 
1.76      www      12292:     my $cuname=unpack("%32C*",$funame);
                   12293:     my $cudom=unpack("%32C*",$fudom);
                   12294:     my $cucourseid=unpack("%32C*",$fucourseid);
                   12295:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      12296:     my $cunique=&recunique($fucourseid);
1.474     albertel 12297:     my $cpart=unpack("%32S*",$part);
1.835     albertel 12298:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   12299: 
1.790     albertel 12300: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 12301: 			       
                   12302: 	$return.= ($cunique%$cuname+
                   12303: 		   $cunique%$cudom+
                   12304: 		   $cusymb%$cuname+
                   12305: 		   $cusymb%$cudom+
                   12306: 		   $cucourseid%$cuname+
                   12307: 		   $cucourseid%$cudom+
                   12308: 		   $cpart%$cuname+
                   12309: 		   $cpart%$cudom);
                   12310:     } else {
                   12311: 	$return.= ($cunique%$cuname+
                   12312: 		   $cunique%$cudom+
                   12313: 		   $cusymb%$cuname+
                   12314: 		   $cusymb%$cudom+
                   12315: 		   $cucourseid%$cuname+
                   12316: 		   $cucourseid%$cudom);
                   12317:     }
                   12318:     return $return;
1.76      www      12319: }
                   12320: 
                   12321: sub receipt {
1.474     albertel 12322:     my ($part)=@_;
1.790     albertel 12323:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 12324:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      12325: }
1.260     ng       12326: 
1.790     albertel 12327: sub whichuser {
                   12328:     my ($passedsymb)=@_;
                   12329:     my ($symb,$courseid,$domain,$name,$publicuser);
                   12330:     if (defined($env{'form.grade_symb'})) {
                   12331: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   12332: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   12333: 	if (!$allowed &&
                   12334: 	    exists($env{'request.course.sec'}) &&
                   12335: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   12336: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   12337: 			      '/'.$env{'request.course.sec'});
                   12338: 	}
                   12339: 	if ($allowed) {
                   12340: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   12341: 	    $courseid=$tmp_courseid;
                   12342: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   12343: 	    ($name)=&get_env_multiple('form.grade_username');
                   12344: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   12345: 	}
                   12346:     }
                   12347:     if (!$passedsymb) {
                   12348: 	$symb=&symbread();
                   12349:     } else {
                   12350: 	$symb=$passedsymb;
                   12351:     }
                   12352:     $courseid=$env{'request.course.id'};
                   12353:     $domain=$env{'user.domain'};
                   12354:     $name=$env{'user.name'};
                   12355:     if ($name eq 'public' && $domain eq 'public') {
                   12356: 	if (!defined($env{'form.username'})) {
                   12357: 	    $env{'form.username'}.=time.rand(10000000);
                   12358: 	}
                   12359: 	$name.=$env{'form.username'};
                   12360:     }
                   12361:     return ($symb,$courseid,$domain,$name,$publicuser);
                   12362: 
                   12363: }
                   12364: 
1.36      albertel 12365: # ------------------------------------------------------------ Serves up a file
1.472     albertel 12366: # returns either the contents of the file or 
                   12367: # -1 if the file doesn't exist
1.481     raeburn  12368: #
                   12369: # if the target is a file that was uploaded via DOCS, 
                   12370: # a check will be made to see if a current copy exists on the local server,
                   12371: # if it does this will be served, otherwise a copy will be retrieved from
                   12372: # the home server for the course and stored in /home/httpd/html/userfiles on
                   12373: # the local server.   
1.472     albertel 12374: 
1.36      albertel 12375: sub getfile {
1.538     albertel 12376:     my ($file) = @_;
1.609     banghart 12377:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 12378:     &repcopy($file);
                   12379:     return &readfile($file);
                   12380: }
                   12381: 
                   12382: sub repcopy_userfile {
                   12383:     my ($file)=@_;
1.1142    raeburn  12384:     my $londocroot = $perlvar{'lonDocRoot'};
                   12385:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  12386:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 12387:     my ($cdom,$cnum,$filename) = 
1.811     albertel 12388: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 12389:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   12390:     if (-e "$file") {
1.828     www      12391: # we already have a local copy, check it out
1.538     albertel 12392: 	my @fileinfo = stat($file);
1.828     www      12393: 	my $rtncode;
                   12394: 	my $info;
1.538     albertel 12395: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 12396: 	if ($lwpresp ne 'ok') {
1.828     www      12397: # there is no such file anymore, even though we had a local copy
1.482     albertel 12398: 	    if ($rtncode eq '404') {
1.538     albertel 12399: 		unlink($file);
1.482     albertel 12400: 	    }
                   12401: 	    return -1;
                   12402: 	}
                   12403: 	if ($info < $fileinfo[9]) {
1.828     www      12404: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  12405: 	    return 'ok';
1.828     www      12406: 	} else {
                   12407: # the file is outdated, get rid of it
                   12408: 	    unlink($file);
1.482     albertel 12409: 	}
1.828     www      12410:     }
                   12411: # one way or the other, at this point, we don't have the file
                   12412: # construct the correct path for the file
                   12413:     my @parts = ($cdom,$cnum); 
                   12414:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   12415: 	push @parts, split(/\//,$1);
                   12416:     }
                   12417:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   12418:     foreach my $part (@parts) {
                   12419: 	$path .= '/'.$part;
                   12420: 	if (!-e $path) {
                   12421: 	    mkdir($path,0770);
1.482     albertel 12422: 	}
                   12423:     }
1.828     www      12424: # now the path exists for sure
                   12425: # get a user agent
                   12426:     my $ua=new LWP::UserAgent;
                   12427:     my $transferfile=$file.'.in.transfer';
                   12428: # FIXME: this should flock
                   12429:     if (-e $transferfile) { return 'ok'; }
                   12430:     my $request;
                   12431:     $uri=~s/^\///;
1.980     raeburn  12432:     my $homeserver = &homeserver($cnum,$cdom);
                   12433:     my $protocol = $protocol{$homeserver};
                   12434:     $protocol = 'http' if ($protocol ne 'https');
                   12435:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      12436:     my $response=$ua->request($request,$transferfile);
                   12437: # did it work?
                   12438:     if ($response->is_error()) {
                   12439: 	unlink($transferfile);
                   12440: 	&logthis("Userfile repcopy failed for $uri");
                   12441: 	return -1;
                   12442:     }
                   12443: # worked, rename the transfer file
                   12444:     rename($transferfile,$file);
1.607     raeburn  12445:     return 'ok';
1.481     raeburn  12446: }
                   12447: 
1.517     albertel 12448: sub tokenwrapper {
                   12449:     my $uri=shift;
1.980     raeburn  12450:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 12451:     $uri=~s|^/||;
1.620     albertel 12452:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 12453:     my $token=$1;
1.552     albertel 12454:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   12455:     if ($udom && $uname && $file) {
                   12456: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  12457:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  12458:         my $homeserver = &homeserver($uname,$udom);
                   12459:         my $protocol = $protocol{$homeserver};
                   12460:         $protocol = 'http' if ($protocol ne 'https');
                   12461:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 12462:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   12463:                                '&tokenissued='.$perlvar{'lonHostID'};
                   12464:     } else {
                   12465:         return '/adm/notfound.html';
                   12466:     }
                   12467: }
                   12468: 
1.828     www      12469: # call with reqtype HEAD: get last modification time
                   12470: # call with reqtype GET: get the file contents
                   12471: # Do not call this with reqtype GET for large files! It loads everything into memory
                   12472: #
1.481     raeburn  12473: sub getuploaded {
                   12474:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   12475:     $uri=~s/^\///;
1.980     raeburn  12476:     my $homeserver = &homeserver($cnum,$cdom);
                   12477:     my $protocol = $protocol{$homeserver};
                   12478:     $protocol = 'http' if ($protocol ne 'https');
                   12479:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  12480:     my $ua=new LWP::UserAgent;
                   12481:     my $request=new HTTP::Request($reqtype,$uri);
                   12482:     my $response=$ua->request($request);
                   12483:     $$rtncode = $response->code;
1.482     albertel 12484:     if (! $response->is_success()) {
                   12485: 	return 'failed';
                   12486:     }      
                   12487:     if ($reqtype eq 'HEAD') {
1.486     www      12488: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 12489:     } elsif ($reqtype eq 'GET') {
                   12490: 	$$info = $response->content;
1.472     albertel 12491:     }
1.482     albertel 12492:     return 'ok';
1.36      albertel 12493: }
                   12494: 
1.481     raeburn  12495: sub readfile {
                   12496:     my $file = shift;
                   12497:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   12498:     my $fh;
                   12499:     open($fh,"<$file");
                   12500:     my $a='';
1.800     albertel 12501:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  12502:     return $a;
                   12503: }
                   12504: 
1.36      albertel 12505: sub filelocation {
1.590     banghart 12506:     my ($dir,$file) = @_;
                   12507:     my $location;
                   12508:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 12509: 
                   12510:     if ($file =~ m-^/adm/-) {
                   12511: 	$file=~s-^/adm/wrapper/-/-;
                   12512: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   12513:     }
1.882     albertel 12514: 
1.1139    www      12515:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  12516:         $location = $file;
1.609     banghart 12517:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 12518:         my ($udom,$uname,$filename)=
1.811     albertel 12519:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 12520:         my $home=&homeserver($uname,$udom);
                   12521:         my $is_me=0;
                   12522:         my @ids=&current_machine_ids();
                   12523:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   12524:         if ($is_me) {
1.1117    foxr     12525:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 12526:         } else {
                   12527:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   12528:   	      $udom.'/'.$uname.'/'.$filename;
                   12529:         }
1.882     albertel 12530:     } elsif ($file =~ m-^/adm/-) {
                   12531: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 12532:     } else {
                   12533:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      12534:         $file=~s:^/(res|priv)/:/:;
                   12535:         my $space=$1;
1.590     banghart 12536:         if ( !( $file =~ m:^/:) ) {
                   12537:             $location = $dir. '/'.$file;
                   12538:         } else {
1.1142    raeburn  12539:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 12540:         }
1.59      albertel 12541:     }
1.590     banghart 12542:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 12543:     while ($location=~m{/\.\./}) {
                   12544: 	if ($location =~ m{/[^/]+/\.\./}) {
                   12545: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   12546: 	} else {
                   12547: 	    $location=~ s{/\.\./}{/}g;
                   12548: 	}
                   12549:     } #remove dir/..
1.590     banghart 12550:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   12551:     return $location;
1.46      www      12552: }
1.36      albertel 12553: 
1.46      www      12554: sub hreflocation {
                   12555:     my ($dir,$file)=@_;
1.980     raeburn  12556:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 12557: 	$file=filelocation($dir,$file);
1.700     albertel 12558:     } elsif ($file=~m-^/adm/-) {
                   12559: 	$file=~s-^/adm/wrapper/-/-;
                   12560: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 12561:     }
                   12562:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   12563: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   12564:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  12565: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   12566: 	        {/uploaded/$1/$2/}x;
1.46      www      12567:     }
1.913     albertel 12568:     if ($file=~ m{^/userfiles/}) {
                   12569: 	$file =~ s{^/userfiles/}{/uploaded/};
                   12570:     }
1.462     albertel 12571:     return $file;
1.465     albertel 12572: }
                   12573: 
1.1139    www      12574: 
                   12575: 
                   12576: 
                   12577: 
1.465     albertel 12578: sub current_machine_domains {
1.853     albertel 12579:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   12580: }
                   12581: 
                   12582: sub machine_domains {
                   12583:     my ($hostname) = @_;
1.465     albertel 12584:     my @domains;
1.838     albertel 12585:     my %hostname = &all_hostnames();
1.465     albertel 12586:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  12587: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 12588: 	if ($hostname eq $name) {
1.844     albertel 12589: 	    push(@domains,&host_domain($id));
1.465     albertel 12590: 	}
                   12591:     }
                   12592:     return @domains;
                   12593: }
                   12594: 
                   12595: sub current_machine_ids {
1.853     albertel 12596:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   12597: }
                   12598: 
                   12599: sub machine_ids {
                   12600:     my ($hostname) = @_;
                   12601:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 12602:     my @ids;
1.888     albertel 12603:     my %name_to_host = &all_names();
1.889     albertel 12604:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   12605: 	return @{ $name_to_host{$hostname} };
                   12606:     }
                   12607:     return;
1.31      www      12608: }
                   12609: 
1.824     raeburn  12610: sub additional_machine_domains {
                   12611:     my @domains;
                   12612:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   12613:     while( my $line = <$fh>) {
                   12614:         $line =~ s/\s//g;
                   12615:         push(@domains,$line);
                   12616:     }
                   12617:     return @domains;
                   12618: }
                   12619: 
                   12620: sub default_login_domain {
                   12621:     my $domain = $perlvar{'lonDefDomain'};
                   12622:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   12623:     foreach my $posdom (&current_machine_domains(),
                   12624:                         &additional_machine_domains()) {
                   12625:         if (lc($posdom) eq lc($testdomain)) {
                   12626:             $domain=$posdom;
                   12627:             last;
                   12628:         }
                   12629:     }
                   12630:     return $domain;
                   12631: }
                   12632: 
1.31      www      12633: # ------------------------------------------------------------- Declutters URLs
                   12634: 
                   12635: sub declutter {
                   12636:     my $thisfn=shift;
1.569     albertel 12637:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  12638:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   12639:         $thisfn=~s{^/home/httpd/html}{};
                   12640:     }
1.31      www      12641:     $thisfn=~s/^\///;
1.697     albertel 12642:     $thisfn=~s|^adm/wrapper/||;
                   12643:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      12644:     $thisfn=~s/^res\///;
1.1172    bisitz   12645:     $thisfn=~s/^priv\///;
1.1032    raeburn  12646:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   12647:         $thisfn=~s/\?.+$//;
                   12648:     }
1.268     www      12649:     return $thisfn;
                   12650: }
                   12651: 
                   12652: # ------------------------------------------------------------- Clutter up URLs
                   12653: 
                   12654: sub clutter {
                   12655:     my $thisfn='/'.&declutter(shift);
1.887     albertel 12656:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 12657: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      12658:        $thisfn='/res'.$thisfn; 
                   12659:     }
1.1031    raeburn  12660:     if ($thisfn !~m|^/adm|) {
                   12661: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 12662: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 12663: 	} else {
                   12664: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   12665: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 12666: 	    if ($embstyle eq 'ssi'
                   12667: 		|| ($embstyle eq 'hdn')
                   12668: 		|| ($embstyle eq 'rat')
                   12669: 		|| ($embstyle eq 'prv')
                   12670: 		|| ($embstyle eq 'ign')) {
                   12671: 		#do nothing with these
                   12672: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 12673: 		|| ($embstyle eq 'emb')
                   12674: 		|| ($embstyle eq 'wrp')) {
                   12675: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 12676: 	    } elsif ($embstyle eq 'unk'
                   12677: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 12678: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 12679: 	    } else {
1.718     www      12680: #		&logthis("Got a blank emb style");
1.695     albertel 12681: 	    }
1.694     albertel 12682: 	}
1.1298    raeburn  12683:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/exttools?$}) {
                   12684:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 12685:     }
1.31      www      12686:     return $thisfn;
1.12      www      12687: }
                   12688: 
1.787     albertel 12689: sub clutter_with_no_wrapper {
                   12690:     my $uri = &clutter(shift);
                   12691:     if ($uri =~ m-^/adm/-) {
                   12692: 	$uri =~ s-^/adm/wrapper/-/-;
                   12693: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   12694:     }
                   12695:     return $uri;
                   12696: }
                   12697: 
1.557     albertel 12698: sub freeze_escape {
                   12699:     my ($value)=@_;
                   12700:     if (ref($value)) {
                   12701: 	$value=&nfreeze($value);
                   12702: 	return '__FROZEN__'.&escape($value);
                   12703:     }
                   12704:     return &escape($value);
                   12705: }
                   12706: 
1.11      www      12707: 
1.557     albertel 12708: sub thaw_unescape {
                   12709:     my ($value)=@_;
                   12710:     if ($value =~ /^__FROZEN__/) {
                   12711: 	substr($value,0,10,undef);
                   12712: 	$value=&unescape($value);
                   12713: 	return &thaw($value);
                   12714:     }
                   12715:     return &unescape($value);
                   12716: }
                   12717: 
1.436     albertel 12718: sub correct_line_ends {
                   12719:     my ($result)=@_;
                   12720:     $$result =~s/\r\n/\n/mg;
                   12721:     $$result =~s/\r/\n/mg;
1.415     albertel 12722: }
1.1       albertel 12723: # ================================================================ Main Program
                   12724: 
1.184     www      12725: sub goodbye {
1.204     albertel 12726:    &logthis("Starting Shut down");
1.443     albertel 12727: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 12728:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 12729: #converted
1.599     albertel 12730: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 12731:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   12732: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   12733: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 12734: #1.1 only
1.870     albertel 12735: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   12736: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   12737: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   12738: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   12739:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 12740:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   12741:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      12742:    &flushcourselogs();
                   12743:    &logthis("Shutting down");
                   12744: }
                   12745: 
1.852     albertel 12746: sub get_dns {
1.1210    raeburn  12747:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 12748:     if (!$ignore_cache) {
                   12749: 	my ($content,$cached)=
                   12750: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   12751: 	if ($cached) {
1.1210    raeburn  12752: 	    &$func($content,$hashref);
1.869     albertel 12753: 	    return;
                   12754: 	}
                   12755:     }
                   12756: 
                   12757:     my %alldns;
1.852     albertel 12758:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12759:     foreach my $dns (<$config>) {
                   12760: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  12761:         my $line = $1;
                   12762:         my ($host,$protocol) = split(/:/,$line);
                   12763:         if ($protocol ne 'https') {
                   12764:             $protocol = 'http';
                   12765:         }
                   12766: 	$alldns{$host} = $protocol;
1.869     albertel 12767:     }
                   12768:     while (%alldns) {
1.1263    raeburn  12769: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 12770: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  12771:         $ua->timeout(30);
1.979     raeburn  12772: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 12773: 	my $response=$ua->request($request);
1.979     raeburn  12774:         delete($alldns{$dns});
1.852     albertel 12775: 	next if ($response->is_error());
                   12776: 	my @content = split("\n",$response->content);
1.1210    raeburn  12777: 	unless ($nocache) {
1.1219    raeburn  12778: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210    raeburn  12779: 	}
                   12780: 	&$func(\@content,$hashref);
1.869     albertel 12781: 	return;
1.852     albertel 12782:     }
                   12783:     close($config);
1.871     albertel 12784:     my $which = (split('/',$url))[3];
                   12785:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   12786:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 12787:     my @content = <$config>;
1.1210    raeburn  12788:     &$func(\@content,$hashref);
                   12789:     return;
                   12790: }
                   12791: 
                   12792: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  12793: sub parse_dns_checksums_tab {
1.1210    raeburn  12794:     my ($lines,$hashref) = @_;
1.1264    raeburn  12795:     my $lonhost = $perlvar{'lonHostID'};
                   12796:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  12797:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  12798:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   12799:     my $webconfdir = '/etc/httpd/conf';
                   12800:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   12801:         $webconfdir = '/etc/apache2';
                   12802:     } elsif ($distro =~ /^sles(\d+)$/) {
                   12803:         if ($1 >= 10) {
                   12804:             $webconfdir = '/etc/apache2';
                   12805:         }
                   12806:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   12807:         if ($1 >= 10.0) {
                   12808:             $webconfdir = '/etc/apache2';
                   12809:         }
                   12810:     }
1.1210    raeburn  12811:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12812:     my (%chksum,%revnum);
                   12813:     if (ref($lines) eq 'ARRAY') {
                   12814:         chomp(@{$lines});
1.1238    raeburn  12815:         my $version = shift(@{$lines});
                   12816:         if ($version eq $release) {  
1.1210    raeburn  12817:             foreach my $line (@{$lines}) {
1.1238    raeburn  12818:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  12819:                 if ($file =~ m{^/etc/httpd/conf}) {
                   12820:                     if ($webconfdir eq '/etc/apache2') {
                   12821:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   12822:                     }
                   12823:                 }
1.1238    raeburn  12824:                 $chksum{$file} = $shasum;
                   12825:                 $revnum{$file} = $version;
1.1210    raeburn  12826:             }
                   12827:             if (ref($hashref) eq 'HASH') {
                   12828:                 %{$hashref} = (
                   12829:                                 sums     => \%chksum,
                   12830:                                 versions => \%revnum,
                   12831:                               );
                   12832:             }
                   12833:         }
                   12834:     }
1.869     albertel 12835:     return;
1.852     albertel 12836: }
1.1210    raeburn  12837: 
                   12838: sub fetch_dns_checksums {
1.1238    raeburn  12839:     my %checksums;
                   12840:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  12841:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  12842:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12843:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  12844:              \%checksums);
1.1210    raeburn  12845:     return \%checksums;
                   12846: }
                   12847: 
1.327     albertel 12848: # ------------------------------------------------------------ Read domain file
                   12849: {
1.852     albertel 12850:     my $loaded;
1.846     albertel 12851:     my %domain;
                   12852: 
1.852     albertel 12853:     sub parse_domain_tab {
                   12854: 	my ($lines) = @_;
                   12855: 	foreach my $line (@$lines) {
                   12856: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      12857: 
1.846     albertel 12858: 	    chomp($line);
1.852     albertel 12859: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 12860: 	    my %this_domain;
                   12861: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   12862: 			       'lang_def', 'city', 'longi', 'lati',
                   12863: 			       'primary') {
                   12864: 		$this_domain{$field} = shift(@elements);
                   12865: 	    }
                   12866: 	    $domain{$name} = \%this_domain;
1.852     albertel 12867: 	}
                   12868:     }
1.864     albertel 12869: 
                   12870:     sub reset_domain_info {
                   12871: 	undef($loaded);
                   12872: 	undef(%domain);
                   12873:     }
                   12874: 
1.852     albertel 12875:     sub load_domain_tab {
1.1293    raeburn  12876: 	my ($ignore_cache,$nocache) = @_;
                   12877: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 12878: 	my $fh;
                   12879: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   12880: 	    my @lines = <$fh>;
                   12881: 	    &parse_domain_tab(\@lines);
1.448     albertel 12882: 	}
1.852     albertel 12883: 	close($fh);
                   12884: 	$loaded = 1;
1.327     albertel 12885:     }
1.846     albertel 12886: 
                   12887:     sub domain {
1.852     albertel 12888: 	&load_domain_tab() if (!$loaded);
                   12889: 
1.846     albertel 12890: 	my ($name,$what) = @_;
                   12891: 	return if ( !exists($domain{$name}) );
                   12892: 
                   12893: 	if (!$what) {
                   12894: 	    return $domain{$name}{'description'};
                   12895: 	}
                   12896: 	return $domain{$name}{$what};
                   12897:     }
1.974     raeburn  12898: 
                   12899:     sub domain_info {
                   12900:         &load_domain_tab() if (!$loaded);
                   12901:         return %domain;
                   12902:     }
                   12903: 
1.327     albertel 12904: }
                   12905: 
                   12906: 
1.1       albertel 12907: # ------------------------------------------------------------- Read hosts file
                   12908: {
1.838     albertel 12909:     my %hostname;
1.844     albertel 12910:     my %hostdom;
1.845     albertel 12911:     my %libserv;
1.852     albertel 12912:     my $loaded;
1.888     albertel 12913:     my %name_to_host;
1.1074    raeburn  12914:     my %internetdom;
1.1107    raeburn  12915:     my %LC_dns_serv;
1.852     albertel 12916: 
                   12917:     sub parse_hosts_tab {
                   12918: 	my ($file) = @_;
                   12919: 	foreach my $configline (@$file) {
                   12920: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  12921:             chomp($configline);
                   12922: 	    if ($configline =~ /^\^/) {
                   12923:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   12924:                     $LC_dns_serv{$1} = 1;
                   12925:                 }
                   12926:                 next;
                   12927:             }
1.1074    raeburn  12928: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 12929: 	    $name=~s/\s//g;
                   12930: 	    if ($id && $domain && $role && $name) {
                   12931: 		$hostname{$id}=$name;
1.888     albertel 12932: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 12933: 		$hostdom{$id}=$domain;
                   12934: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  12935:                 if (defined($protocol)) {
                   12936:                     if ($protocol eq 'https') {
                   12937:                         $protocol{$id} = $protocol;
                   12938:                     } else {
                   12939:                         $protocol{$id} = 'http'; 
                   12940:                     }
1.968     raeburn  12941:                 } else {
1.969     raeburn  12942:                     $protocol{$id} = 'http';
1.968     raeburn  12943:                 }
1.1074    raeburn  12944:                 if (defined($intdom)) {
                   12945:                     $internetdom{$id} = $intdom;
                   12946:                 }
1.852     albertel 12947: 	    }
                   12948: 	}
                   12949:     }
1.864     albertel 12950:     
                   12951:     sub reset_hosts_info {
1.897     albertel 12952: 	&purge_remembered();
1.864     albertel 12953: 	&reset_domain_info();
                   12954: 	&reset_hosts_ip_info();
1.892     albertel 12955: 	undef(%name_to_host);
1.864     albertel 12956: 	undef(%hostname);
                   12957: 	undef(%hostdom);
                   12958: 	undef(%libserv);
                   12959: 	undef($loaded);
                   12960:     }
1.1       albertel 12961: 
1.852     albertel 12962:     sub load_hosts_tab {
1.1293    raeburn  12963: 	my ($ignore_cache,$nocache) = @_;
                   12964: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852     albertel 12965: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12966: 	my @config = <$config>;
                   12967: 	&parse_hosts_tab(\@config);
                   12968: 	close($config);
                   12969: 	$loaded=1;
1.1       albertel 12970:     }
1.852     albertel 12971: 
1.838     albertel 12972:     sub hostname {
1.852     albertel 12973: 	&load_hosts_tab() if (!$loaded);
                   12974: 
1.838     albertel 12975: 	my ($lonid) = @_;
                   12976: 	return $hostname{$lonid};
                   12977:     }
1.845     albertel 12978: 
1.838     albertel 12979:     sub all_hostnames {
1.852     albertel 12980: 	&load_hosts_tab() if (!$loaded);
                   12981: 
1.838     albertel 12982: 	return %hostname;
                   12983:     }
1.845     albertel 12984: 
1.888     albertel 12985:     sub all_names {
1.1293    raeburn  12986:         my ($ignore_cache,$nocache) = @_;
                   12987: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 12988: 
                   12989: 	return %name_to_host;
                   12990:     }
                   12991: 
1.974     raeburn  12992:     sub all_host_domain {
                   12993:         &load_hosts_tab() if (!$loaded);
                   12994:         return %hostdom;
                   12995:     }
                   12996: 
1.845     albertel 12997:     sub is_library {
1.852     albertel 12998: 	&load_hosts_tab() if (!$loaded);
                   12999: 
1.845     albertel 13000: 	return exists($libserv{$_[0]});
                   13001:     }
                   13002: 
                   13003:     sub all_library {
1.852     albertel 13004: 	&load_hosts_tab() if (!$loaded);
                   13005: 
1.845     albertel 13006: 	return %libserv;
                   13007:     }
                   13008: 
1.1062    droeschl 13009:     sub unique_library {
                   13010: 	#2x reverse removes all hostnames that appear more than once
                   13011:         my %unique = reverse &all_library();
                   13012:         return reverse %unique;
                   13013:     }
                   13014: 
1.841     albertel 13015:     sub get_servers {
1.852     albertel 13016: 	&load_hosts_tab() if (!$loaded);
                   13017: 
1.841     albertel 13018: 	my ($domain,$type) = @_;
                   13019: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13020: 	                                          : %hostname;
                   13021: 	my %result;
1.842     albertel 13022: 	if (ref($domain) eq 'ARRAY') {
                   13023: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13024: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13025: 		    $result{$host} = $hostname;
                   13026: 		}
                   13027: 	    }
                   13028: 	} else {
                   13029: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13030: 		if ($hostdom{$host} eq $domain) {
                   13031: 		    $result{$host} = $hostname;
                   13032: 		}
1.841     albertel 13033: 	    }
                   13034: 	}
                   13035: 	return %result;
                   13036:     }
1.845     albertel 13037: 
1.1062    droeschl 13038:     sub get_unique_servers {
                   13039:         my %unique = reverse &get_servers(@_);
                   13040: 	return reverse %unique;
                   13041:     }
                   13042: 
1.844     albertel 13043:     sub host_domain {
1.852     albertel 13044: 	&load_hosts_tab() if (!$loaded);
                   13045: 
1.844     albertel 13046: 	my ($lonid) = @_;
                   13047: 	return $hostdom{$lonid};
                   13048:     }
                   13049: 
1.841     albertel 13050:     sub all_domains {
1.852     albertel 13051: 	&load_hosts_tab() if (!$loaded);
                   13052: 
1.841     albertel 13053: 	my %seen;
                   13054: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13055: 	return @uniq;
                   13056:     }
1.1074    raeburn  13057: 
                   13058:     sub internet_dom {
                   13059:         &load_hosts_tab() if (!$loaded);
                   13060: 
                   13061:         my ($lonid) = @_;
                   13062:         return $internetdom{$lonid};
                   13063:     }
1.1107    raeburn  13064: 
                   13065:     sub is_LC_dns {
                   13066:         &load_hosts_tab() if (!$loaded);
                   13067: 
                   13068:         my ($hostname) = @_;
                   13069:         return exists($LC_dns_serv{$hostname});
                   13070:     }
                   13071: 
1.1       albertel 13072: }
                   13073: 
1.847     albertel 13074: { 
                   13075:     my %iphost;
1.856     albertel 13076:     my %name_to_ip;
                   13077:     my %lonid_to_ip;
1.869     albertel 13078: 
1.847     albertel 13079:     sub get_hosts_from_ip {
                   13080: 	my ($ip) = @_;
                   13081: 	my %iphosts = &get_iphost();
                   13082: 	if (ref($iphosts{$ip})) {
                   13083: 	    return @{$iphosts{$ip}};
                   13084: 	}
                   13085: 	return;
1.839     albertel 13086:     }
1.864     albertel 13087:     
                   13088:     sub reset_hosts_ip_info {
                   13089: 	undef(%iphost);
                   13090: 	undef(%name_to_ip);
                   13091: 	undef(%lonid_to_ip);
                   13092:     }
1.856     albertel 13093: 
                   13094:     sub get_host_ip {
                   13095: 	my ($lonid) = @_;
                   13096: 	if (exists($lonid_to_ip{$lonid})) {
                   13097: 	    return $lonid_to_ip{$lonid};
                   13098: 	}
                   13099: 	my $name=&hostname($lonid);
                   13100:    	my $ip = gethostbyname($name);
                   13101: 	return if (!$ip || length($ip) ne 4);
                   13102: 	$ip=inet_ntoa($ip);
                   13103: 	$name_to_ip{$name}   = $ip;
                   13104: 	$lonid_to_ip{$lonid} = $ip;
                   13105: 	return $ip;
                   13106:     }
1.847     albertel 13107:     
                   13108:     sub get_iphost {
1.1293    raeburn  13109: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13110: 
1.869     albertel 13111: 	if (!$ignore_cache) {
                   13112: 	    if (%iphost) {
                   13113: 		return %iphost;
                   13114: 	    }
                   13115: 	    my ($ip_info,$cached)=
                   13116: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13117: 	    if ($cached) {
                   13118: 		%iphost      = %{$ip_info->[0]};
                   13119: 		%name_to_ip  = %{$ip_info->[1]};
                   13120: 		%lonid_to_ip = %{$ip_info->[2]};
                   13121: 		return %iphost;
                   13122: 	    }
                   13123: 	}
1.894     albertel 13124: 
                   13125: 	# get yesterday's info for fallback
                   13126: 	my %old_name_to_ip;
                   13127: 	my ($ip_info,$cached)=
                   13128: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13129: 	if ($cached) {
                   13130: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13131: 	}
                   13132: 
1.1293    raeburn  13133: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13134: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13135: 	    my $ip;
                   13136: 	    if (!exists($name_to_ip{$name})) {
                   13137: 		$ip = gethostbyname($name);
                   13138: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13139: 		    if (defined($old_name_to_ip{$name})) {
                   13140: 			$ip = $old_name_to_ip{$name};
                   13141: 			&logthis("Can't find $name defaulting to old $ip");
                   13142: 		    } else {
                   13143: 			&logthis("Name $name no IP found");
                   13144: 			next;
                   13145: 		    }
                   13146: 		} else {
                   13147: 		    $ip=inet_ntoa($ip);
1.847     albertel 13148: 		}
                   13149: 		$name_to_ip{$name} = $ip;
                   13150: 	    } else {
                   13151: 		$ip = $name_to_ip{$name};
1.653     albertel 13152: 	    }
1.888     albertel 13153: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13154: 		$lonid_to_ip{$id} = $ip;
                   13155: 	    }
                   13156: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13157: 	}
1.1293    raeburn  13158:         unless ($nocache) {
                   13159: 	    &do_cache_new('iphost','iphost',
                   13160: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   13161: 		          48*60*60);
                   13162:         }
1.869     albertel 13163: 
1.847     albertel 13164: 	return %iphost;
1.598     albertel 13165:     }
                   13166: 
1.992     raeburn  13167:     #
                   13168:     #  Given a DNS returns the loncapa host name for that DNS 
                   13169:     # 
                   13170:     sub host_from_dns {
                   13171:         my ($dns) = @_;
                   13172:         my @hosts;
                   13173:         my $ip;
                   13174: 
1.993     raeburn  13175:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  13176:             $ip = $name_to_ip{$dns};
                   13177:         }
                   13178:         if (!$ip) {
                   13179:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   13180:             if (length($ip) == 4) { 
                   13181: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   13182:             }
                   13183:         }
                   13184:         if ($ip) {
                   13185: 	    @hosts = get_hosts_from_ip($ip);
                   13186: 	    return $hosts[0];
                   13187:         }
                   13188:         return undef;
1.986     foxr     13189:     }
1.992     raeburn  13190: 
1.1074    raeburn  13191:     sub get_internet_names {
                   13192:         my ($lonid) = @_;
                   13193:         return if ($lonid eq '');
                   13194:         my ($idnref,$cached)=
                   13195:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   13196:         if ($cached) {
                   13197:             return $idnref;
                   13198:         }
                   13199:         my $ip = &get_host_ip($lonid);
                   13200:         my @hosts = &get_hosts_from_ip($ip);
                   13201:         my %iphost = &get_iphost();
                   13202:         my (@idns,%seen);
                   13203:         foreach my $id (@hosts) {
                   13204:             my $dom = &host_domain($id);
                   13205:             my $prim_id = &domain($dom,'primary');
                   13206:             my $prim_ip = &get_host_ip($prim_id);
                   13207:             next if ($seen{$prim_ip});
                   13208:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   13209:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   13210:                     my $intdom = &internet_dom($id);
                   13211:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   13212:                         push(@idns,$intdom);
                   13213:                     }
                   13214:                 }
                   13215:             }
                   13216:             $seen{$prim_ip} = 1;
                   13217:         }
1.1219    raeburn  13218:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  13219:     }
                   13220: 
1.986     foxr     13221: }
                   13222: 
1.1079    raeburn  13223: sub all_loncaparevs {
1.1249    raeburn  13224:     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  13225: }
                   13226: 
1.1227    raeburn  13227: # ---------------------------------------------------------- Read loncaparev table
                   13228: {
                   13229:     sub load_loncaparevs { 
                   13230:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   13231:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   13232:                 while (my $configline=<$config>) {
                   13233:                     chomp($configline);
                   13234:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   13235:                     $loncaparevs{$hostid}=$loncaparev;
                   13236:                 }
                   13237:                 close($config);
                   13238:             }
                   13239:         }
                   13240:     }
                   13241: }
                   13242: 
                   13243: # ---------------------------------------------------------- Read serverhostID table
                   13244: {
                   13245:     sub load_serverhomeIDs {
                   13246:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   13247:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   13248:                 while (my $configline=<$config>) {
                   13249:                     chomp($configline);
                   13250:                     my ($name,$id)=split(/:/,$configline);
                   13251:                     $serverhomeIDs{$name}=$id;
                   13252:                 }
                   13253:                 close($config);
                   13254:             }
                   13255:         }
                   13256:     }
                   13257: }
                   13258: 
                   13259: 
1.862     albertel 13260: BEGIN {
                   13261: 
                   13262: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   13263:     unless ($readit) {
                   13264: {
                   13265:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   13266:     %perlvar = (%perlvar,%{$configvars});
                   13267: }
                   13268: 
                   13269: 
1.1       albertel 13270: # ------------------------------------------------------ Read spare server file
                   13271: {
1.448     albertel 13272:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 13273: 
                   13274:     while (my $configline=<$config>) {
                   13275:        chomp($configline);
1.284     matthew  13276:        if ($configline) {
1.784     albertel 13277: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 13278: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 13279: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 13280:        }
                   13281:     }
1.448     albertel 13282:     close($config);
1.1       albertel 13283: }
1.11      www      13284: # ------------------------------------------------------------ Read permissions
                   13285: {
1.448     albertel 13286:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      13287: 
                   13288:     while (my $configline=<$config>) {
1.448     albertel 13289: 	chomp($configline);
                   13290: 	if ($configline) {
                   13291: 	    my ($role,$perm)=split(/ /,$configline);
                   13292: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   13293: 	}
1.11      www      13294:     }
1.448     albertel 13295:     close($config);
1.11      www      13296: }
                   13297: 
                   13298: # -------------------------------------------- Read plain texts for permissions
                   13299: {
1.448     albertel 13300:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      13301: 
                   13302:     while (my $configline=<$config>) {
1.448     albertel 13303: 	chomp($configline);
                   13304: 	if ($configline) {
1.742     raeburn  13305: 	    my ($short,@plain)=split(/:/,$configline);
                   13306:             %{$prp{$short}} = ();
                   13307: 	    if (@plain > 0) {
                   13308:                 $prp{$short}{'std'} = $plain[0];
                   13309:                 for (my $i=1; $i<@plain; $i++) {
                   13310:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   13311:                 }
                   13312:             }
1.448     albertel 13313: 	}
1.135     www      13314:     }
1.448     albertel 13315:     close($config);
1.135     www      13316: }
                   13317: 
                   13318: # ---------------------------------------------------------- Read package table
                   13319: {
1.448     albertel 13320:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      13321: 
                   13322:     while (my $configline=<$config>) {
1.483     albertel 13323: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 13324: 	chomp($configline);
                   13325: 	my ($short,$plain)=split(/:/,$configline);
                   13326: 	my ($pack,$name)=split(/\&/,$short);
                   13327: 	if ($plain ne '') {
                   13328: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   13329: 	    $packagetab{$short}=$plain; 
                   13330: 	}
1.11      www      13331:     }
1.448     albertel 13332:     close($config);
1.329     matthew  13333: }
                   13334: 
1.1073    raeburn  13335: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  13336: 
                   13337: &load_loncaparevs();
1.1073    raeburn  13338: 
1.1074    raeburn  13339: # ---------------------------------------------------------- Read serverhostID table
                   13340: 
1.1227    raeburn  13341: &load_serverhomeIDs();
                   13342: 
                   13343: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  13344: {
                   13345:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   13346:     if (-e $file) {
                   13347:         my $parser = HTML::LCParser->new($file);
                   13348:         while (my $token = $parser->get_token()) {
                   13349:             if ($token->[0] eq 'S') {
                   13350:                 my $item = $token->[1];
                   13351:                 my $name = $token->[2]{'name'};
                   13352:                 my $value = $token->[2]{'value'};
1.1285    raeburn  13353:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  13354:                 my $namematch = $token->[2]{'namematch'};
                   13355:                 if ($item eq 'parameter') {
                   13356:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   13357:                         my $release = $parser->get_text();
                   13358:                         $release =~ s/(^\s*|\s*$ )//gx;
                   13359:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   13360:                     }
                   13361:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  13362:                     my $release = $parser->get_text();
                   13363:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  13364:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  13365:                 }
                   13366:             }
                   13367:         }
                   13368:     }
1.1073    raeburn  13369: }
                   13370: 
1.1138    raeburn  13371: # ---------------------------------------------------------- Read managers table
                   13372: {
                   13373:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   13374:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   13375:             while (my $configline=<$config>) {
                   13376:                 chomp($configline);
                   13377:                 next if ($configline =~ /^\#/);
                   13378:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   13379:                     $managerstab{$configline} = 1;
                   13380:                 }
                   13381:             }
                   13382:             close($config);
                   13383:         }
                   13384:     }
                   13385: }
                   13386: 
1.329     matthew  13387: # ------------- set up temporary directory
                   13388: {
1.1117    foxr     13389:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  13390: 
1.11      www      13391: }
                   13392: 
1.794     albertel 13393: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   13394: 				'compress_threshold'=> 20_000,
                   13395:  			        });
1.185     www      13396: 
1.281     www      13397: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      13398: $dumpcount=0;
1.958     www      13399: $locknum=0;
1.22      www      13400: 
1.163     harris41 13401: &logtouch();
1.672     albertel 13402: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      13403: $readit=1;
1.564     albertel 13404:     {
                   13405: 	use integer;
                   13406: 	my $test=(2**32)+1;
1.568     albertel 13407: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 13408: 	&logthis(" Detected 64bit platform ($_64bit)");
                   13409:     }
1.195     www      13410: }
1.1       albertel 13411: }
1.179     www      13412: 
1.1       albertel 13413: 1;
1.191     harris41 13414: __END__
                   13415: 
1.243     albertel 13416: =pod
                   13417: 
1.191     harris41 13418: =head1 NAME
                   13419: 
1.243     albertel 13420: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 13421: 
                   13422: =head1 SYNOPSIS
                   13423: 
1.243     albertel 13424: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 13425: 
                   13426:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   13427: 
1.243     albertel 13428: Common parameters:
                   13429: 
                   13430: =over 4
                   13431: 
                   13432: =item *
                   13433: 
                   13434: $uname : an internal username (if $cname expecting a course Id specifically)
                   13435: 
                   13436: =item *
                   13437: 
                   13438: $udom : a domain (if $cdom expecting a course's domain specifically)
                   13439: 
                   13440: =item *
                   13441: 
                   13442: $symb : a resource instance identifier
                   13443: 
                   13444: =item *
                   13445: 
                   13446: $namespace : the name of a .db file that contains the data needed or
                   13447: being set.
                   13448: 
                   13449: =back
                   13450: 
1.394     bowersj2 13451: =head1 OVERVIEW
1.191     harris41 13452: 
1.394     bowersj2 13453: lonnet provides subroutines which interact with the
                   13454: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   13455: about classes, users, and resources.
1.243     albertel 13456: 
                   13457: For many of these objects you can also use this to store data about
                   13458: them or modify them in various ways.
1.191     harris41 13459: 
1.394     bowersj2 13460: =head2 Symbs
1.191     harris41 13461: 
1.394     bowersj2 13462: To identify a specific instance of a resource, LON-CAPA uses symbols
                   13463: or "symbs"X<symb>. These identifiers are built from the URL of the
                   13464: map, the resource number of the resource in the map, and the URL of
                   13465: the resource itself. The latter is somewhat redundant, but might help
                   13466: if maps change.
                   13467: 
                   13468: An example is
                   13469: 
                   13470:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   13471: 
                   13472: The respective map entry is
                   13473: 
                   13474:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   13475:   title="Problem 2">
                   13476:  </resource>
                   13477: 
                   13478: Symbs are used by the random number generator, as well as to store and
                   13479: restore data specific to a certain instance of for example a problem.
                   13480: 
                   13481: =head2 Storing And Retrieving Data
                   13482: 
                   13483: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   13484: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   13485: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   13486: is is the non-critical message twin of cstore. These functions are for
                   13487: handlers to store a perl hash to a user's permanent data space in an
                   13488: easy manner, and to retrieve it again on another call. It is expected
                   13489: that a handler would use this once at the beginning to retrieve data,
                   13490: and then again once at the end to send only the new data back.
                   13491: 
                   13492: The data is stored in the user's data directory on the user's
                   13493: homeserver under the ID of the course.
                   13494: 
                   13495: The hash that is returned by restore will have all of the previous
                   13496: value for all of the elements of the hash.
                   13497: 
                   13498: Example:
                   13499: 
                   13500:  #creating a hash
                   13501:  my %hash;
                   13502:  $hash{'foo'}='bar';
                   13503: 
                   13504:  #storing it
                   13505:  &Apache::lonnet::cstore(\%hash);
                   13506: 
                   13507:  #changing a value
                   13508:  $hash{'foo'}='notbar';
                   13509: 
                   13510:  #adding a new value
                   13511:  $hash{'bar'}='foo';
                   13512:  &Apache::lonnet::cstore(\%hash);
                   13513: 
                   13514:  #retrieving the hash
                   13515:  my %history=&Apache::lonnet::restore();
                   13516: 
                   13517:  #print the hash
                   13518:  foreach my $key (sort(keys(%history))) {
                   13519:    print("\%history{$key} = $history{$key}");
                   13520:  }
                   13521: 
                   13522: Will print out:
1.191     harris41 13523: 
1.394     bowersj2 13524:  %history{1:foo} = bar
                   13525:  %history{1:keys} = foo:timestamp
                   13526:  %history{1:timestamp} = 990455579
                   13527:  %history{2:bar} = foo
                   13528:  %history{2:foo} = notbar
                   13529:  %history{2:keys} = foo:bar:timestamp
                   13530:  %history{2:timestamp} = 990455580
                   13531:  %history{bar} = foo
                   13532:  %history{foo} = notbar
                   13533:  %history{timestamp} = 990455580
                   13534:  %history{version} = 2
                   13535: 
                   13536: Note that the special hash entries C<keys>, C<version> and
                   13537: C<timestamp> were added to the hash. C<version> will be equal to the
                   13538: total number of versions of the data that have been stored. The
                   13539: C<timestamp> attribute will be the UNIX time the hash was
                   13540: stored. C<keys> is available in every historical section to list which
                   13541: keys were added or changed at a specific historical revision of a
                   13542: hash.
                   13543: 
                   13544: B<Warning>: do not store the hash that restore returns directly. This
                   13545: will cause a mess since it will restore the historical keys as if the
                   13546: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 13547: 
1.394     bowersj2 13548: Calling convention:
1.191     harris41 13549: 
1.1225    raeburn  13550:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  13551:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 13552: 
1.394     bowersj2 13553: For more detailed information, see lonnet specific documentation.
1.191     harris41 13554: 
1.394     bowersj2 13555: =head1 RETURN MESSAGES
1.191     harris41 13556: 
1.394     bowersj2 13557: =over 4
1.191     harris41 13558: 
1.394     bowersj2 13559: =item * B<con_lost>: unable to contact remote host
1.191     harris41 13560: 
1.394     bowersj2 13561: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   13562: when the connection is brought back up
1.191     harris41 13563: 
1.394     bowersj2 13564: =item * B<con_failed>: unable to contact remote host and unable to save message
                   13565: for later delivery
1.191     harris41 13566: 
1.967     bisitz   13567: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 13568: 
1.394     bowersj2 13569: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 13570: that was requested
1.191     harris41 13571: 
1.243     albertel 13572: =back
1.191     harris41 13573: 
1.243     albertel 13574: =head1 PUBLIC SUBROUTINES
1.191     harris41 13575: 
1.243     albertel 13576: =head2 Session Environment Functions
1.191     harris41 13577: 
1.243     albertel 13578: =over 4
1.191     harris41 13579: 
1.394     bowersj2 13580: =item * 
                   13581: X<appenv()>
1.949     raeburn  13582: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 13583: the user envirnoment file, and will be restored for each access this
1.620     albertel 13584: user makes during this session, also modifies the %env for the current
1.949     raeburn  13585: process. Optional rolesarrayref - if defined contains a reference to an array
                   13586: of roles which are exempt from the restriction on modifying user.role entries 
                   13587: in the user's environment.db and in %env.    
1.191     harris41 13588: 
                   13589: =item *
1.394     bowersj2 13590: X<delenv()>
1.987     raeburn  13591: B<delenv($delthis,$regexp)>: removes all items from the session
                   13592: environment file that begin with $delthis. If the 
                   13593: optional second arg - $regexp - is true, $delthis is treated as a 
                   13594: regular expression, otherwise \Q$delthis\E is used. 
                   13595: The values are also deleted from the current processes %env.
1.191     harris41 13596: 
1.795     albertel 13597: =item * get_env_multiple($name) 
                   13598: 
                   13599: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   13600: values may be defined and end up as an array ref.
                   13601: 
                   13602: returns an array of values
                   13603: 
1.243     albertel 13604: =back
                   13605: 
                   13606: =head2 User Information
1.191     harris41 13607: 
1.243     albertel 13608: =over 4
1.191     harris41 13609: 
                   13610: =item *
1.394     bowersj2 13611: X<queryauthenticate()>
                   13612: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 13613: authentication scheme
                   13614: 
                   13615: =item *
1.394     bowersj2 13616: X<authenticate()>
1.1073    raeburn  13617: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 13618: authenticate user from domain's lib servers (first use the current
                   13619: one). C<$upass> should be the users password.
1.1073    raeburn  13620: $checkdefauth is optional (value is 1 if a check should be made to
                   13621:    authenticate user using default authentication method, and allow
                   13622:    account creation if username does not have account in the domain).
                   13623: $clientcancheckhost is optional (value is 1 if checking whether the
                   13624:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 13625: 
                   13626: =item *
1.394     bowersj2 13627: X<homeserver()>
                   13628: B<homeserver($uname,$udom)>: find the server which has
                   13629: the user's directory and files (there must be only one), this caches
                   13630: the answer, and also caches if there is a borken connection.
1.191     harris41 13631: 
                   13632: =item *
1.394     bowersj2 13633: X<idget()>
1.1300    raeburn  13634: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   13635: a list of student/employee IDs or clicker IDs
                   13636: (student/employee IDs are a unique resource in a domain, there must be 
                   13637: only 1 ID per username, and only 1 username per ID in a specific domain).
                   13638: clickerIDs are not necessarily unique, as students might share clickers.
                   13639: (returns hash: id=>name,id=>name)
1.191     harris41 13640: 
                   13641: =item *
1.394     bowersj2 13642: X<idrget()>
                   13643: B<idrget($udom,@unames)>: find the IDs behind a list of
                   13644: usernames (returns hash: name=>id,name=>id)
1.191     harris41 13645: 
                   13646: =item *
1.394     bowersj2 13647: X<idput()>
1.1300    raeburn  13648: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   13649: names and associated student/employee IDs or clicker IDs.
                   13650: 
                   13651: =item *
                   13652: X<iddel()>
                   13653: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   13654: student/employee ID or clicker ID username look-ups from domain.
                   13655: The homeserver ($uhome) and namespace ($namespace) are optional.
                   13656: If no $uhome is provided, it will be determined usig &homeserver()
                   13657: for each user.  If no $namespace is provided, the default is ids.
                   13658: 
                   13659: =item *
                   13660: X<updateclickers()>
                   13661: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   13662: clicker ID-to-username look-ups in clickers.db on library server.
                   13663: Permitted actions are add or del (i.e., add or delete). The 
                   13664: clickers.db contains clickerID as keys (escaped), and each corresponding
                   13665: value is an escaped comma-separated list of usernames (for whom the
                   13666: library server is the homeserver), who registered that particular ID.
                   13667: If $critical is true, the update will be sent via &critical, otherwise
                   13668: &reply() will be used.
1.191     harris41 13669: 
                   13670: =item *
1.394     bowersj2 13671: X<rolesinit()>
1.1169    droeschl 13672: B<rolesinit($udom,$username)>: get user privileges.
                   13673: returns user role, first access and timer interval hashes
1.243     albertel 13674: 
                   13675: =item *
1.1171    droeschl 13676: X<privileged()>
                   13677: B<privileged($username,$domain)>: returns a true if user has a
                   13678: privileged and active role (i.e. su or dc), false otherwise.
                   13679: 
                   13680: =item *
1.551     albertel 13681: X<getsection()>
                   13682: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 13683: course $cname, return section name/number or '' for "not in course"
                   13684: and '-1' for "no section"
                   13685: 
                   13686: =item *
1.394     bowersj2 13687: X<userenvironment()>
                   13688: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 13689: passed in @what from the requested user's environment, returns a hash
                   13690: 
1.858     raeburn  13691: =item * 
                   13692: X<userlog_query()>
1.859     albertel 13693: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   13694: activity.log file. %filters defines filters applied when parsing the
                   13695: log file. These can be start or end timestamps, or the type of action
                   13696: - log to look for Login or Logout events, check for Checkin or
                   13697: Checkout, role for role selection. The response is in the form
                   13698: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   13699: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  13700: 
1.243     albertel 13701: =back
                   13702: 
                   13703: =head2 User Roles
                   13704: 
                   13705: =over 4
                   13706: 
                   13707: =item *
                   13708: 
1.1284    raeburn  13709: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   13710: returns codes for allowed actions.
                   13711: 
                   13712: The first argument is required, all others are optional.
                   13713: 
                   13714: $priv is the privilege being checked.
                   13715: $uri contains additional information about what is being checked for access (e.g.,
                   13716: URL, course ID etc.). 
                   13717: $symb is the unique resource instance identifier in a course; if needed,
                   13718: but not provided, it will be retrieved via a call to &symbread(). 
                   13719: $role is the role for which a priv is being checked (only used if priv is evb). 
                   13720: $clientip is the user's IP address (only used when checking for access to portfolio 
                   13721: files).
                   13722: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   13723: prevents recursive calls to &allowed.
                   13724: 
1.243     albertel 13725:  F: full access
                   13726:  U,I,K: authentication modes (cxx only)
                   13727:  '': forbidden
                   13728:  1: user needs to choose course
                   13729:  2: browse allowed
1.766     albertel 13730:  A: passphrase authentication needed
1.1284    raeburn  13731:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 13732: 
                   13733: =item *
                   13734: 
1.1192    raeburn  13735: constructaccess($url,$setpriv) : check for access to construction space URL
                   13736: 
                   13737: See if the owner domain and name in the URL match those in the
                   13738: expected environment.  If so, return three element list
                   13739: ($ownername,$ownerdomain,$ownerhome).
                   13740: 
                   13741: Otherwise return the null string.
                   13742: 
                   13743: If second argument 'setpriv' is true, it assigns the privileges,
                   13744: and returns the same three element list, unless the owner has
                   13745: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   13746: in which case the null string is returned.
                   13747: 
                   13748: =item *
                   13749: 
1.243     albertel 13750: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   13751: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   13752: and course level
                   13753: 
                   13754: =item *
                   13755: 
1.988     raeburn  13756: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   13757: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  13758: $type is Course (default) or Community.
1.988     raeburn  13759: If $forcedefault evaluates to true, text returned will be default 
                   13760: text for $type. Otherwise, if this is a course, the text returned 
                   13761: will be a custom name for the role (if defined in the course's 
                   13762: environment).  If no custom name is defined the default is returned.
                   13763:    
1.832     raeburn  13764: =item *
                   13765: 
1.1219    raeburn  13766: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  13767: All arguments are optional. Returns a hash of a roles, either for
                   13768: co-author/assistant author roles for a user's Construction Space
1.906     albertel 13769: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  13770: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   13771: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   13772: For each key, value is set to colon-separated start and end times for
                   13773: the role.  If no username and domain are specified, will default to
1.934     raeburn  13774: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  13775: of role statuses (active, future or previous), roles 
                   13776: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   13777: to restrict the list of roles reported. If no array ref is 
                   13778: provided for types, will default to return only active roles.
1.834     albertel 13779: 
1.1195    raeburn  13780: =item *
                   13781: 
                   13782: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  13783: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   13784: 
                   13785: Additional optional arguments are: $type (if role checking is to be restricted 
                   13786: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  13787: available roles) or future (roles available in the future), and
                   13788: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  13789: have active Domain Coordinator role in course's domain or in additional
                   13790: domains (specified in 'Domains to check for privileged users' in course
                   13791: environment -- set via:  Course Settings -> Classlists and staff listing).
                   13792: 
                   13793: =item *
                   13794: 
                   13795: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   13796: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   13797: $possdomains and $possroles are optional array refs -- to domains to check and
                   13798: roles to check.  If $possdomains is not specified, a dump will be done of the
                   13799: users' roles.db to check for a dc or su role in any domain. This can be
                   13800: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   13801: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   13802: this then allows &privileged_by_domain() to be used, which caches the identity
                   13803: of privileged users, eliminating the need for repeated calls to &dump().
                   13804: 
                   13805: =item *
                   13806: 
                   13807: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   13808: where the outer hash keys are domains specified in the $possdomains array ref,
                   13809: next inner hash keys are privileged roles specified in the $roles array ref,
                   13810: and the innermost hash contains key = value pairs for username:domain = end:start
                   13811: for active or future "privileged" users with that role in that domain. To avoid
                   13812: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   13813: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  13814: 
1.243     albertel 13815: =back
                   13816: 
                   13817: =head2 User Modification
                   13818: 
                   13819: =over 4
                   13820: 
                   13821: =item *
                   13822: 
1.957     raeburn  13823: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 13824: user for the level given by URL.  Optional start and end dates (leave empty
                   13825: string or zero for "no date")
1.191     harris41 13826: 
                   13827: =item *
                   13828: 
1.243     albertel 13829: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   13830: change a users, password, possible return values are: ok,
                   13831: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   13832: refused
1.191     harris41 13833: 
                   13834: =item *
                   13835: 
1.243     albertel 13836: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 13837: 
                   13838: =item *
                   13839: 
1.1058    raeburn  13840: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   13841:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   13842: 
                   13843: will update user information (firstname,middlename,lastname,generation,
                   13844: permanentemail), and if forceid is true, student/employee ID also.
                   13845: A user's institutional affiliation(s) can also be updated.
                   13846: User information fields will not be overwritten with empty entries 
                   13847: unless the field is included in the $candelete array reference.
                   13848: This array is included when a single user is modified via "Manage Users",
                   13849: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 13850: 
                   13851: =item *
                   13852: 
1.286     matthew  13853: modifystudent
                   13854: 
1.957     raeburn  13855: modify a student's enrollment and identification information.
1.1235    raeburn  13856: The course id is resolved based on the current user's environment.  
                   13857: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  13858: associated with a course.
                   13859: 
1.297     matthew  13860: This call is essentially a wrapper for lonnet::modifyuser and
                   13861: lonnet::modify_student_enrollment
1.286     matthew  13862: 
                   13863: Inputs: 
                   13864: 
                   13865: =over 4
                   13866: 
1.957     raeburn  13867: =item B<$udom> Student's loncapa domain
1.286     matthew  13868: 
1.957     raeburn  13869: =item B<$uname> Student's loncapa login name
1.286     matthew  13870: 
1.964     bisitz   13871: =item B<$uid> Student/Employee ID
1.286     matthew  13872: 
1.957     raeburn  13873: =item B<$umode> Student's authentication mode
1.286     matthew  13874: 
1.957     raeburn  13875: =item B<$upass> Student's password
1.286     matthew  13876: 
1.957     raeburn  13877: =item B<$first> Student's first name
1.286     matthew  13878: 
1.957     raeburn  13879: =item B<$middle> Student's middle name
1.286     matthew  13880: 
1.957     raeburn  13881: =item B<$last> Student's last name
1.286     matthew  13882: 
1.957     raeburn  13883: =item B<$gene> Student's generation
1.286     matthew  13884: 
1.957     raeburn  13885: =item B<$usec> Student's section in course
1.286     matthew  13886: 
                   13887: =item B<$end> Unix time of the roles expiration
                   13888: 
                   13889: =item B<$start> Unix time of the roles start date
                   13890: 
                   13891: =item B<$forceid> If defined, allow $uid to be changed
                   13892: 
                   13893: =item B<$desiredhome> server to use as home server for student
                   13894: 
1.957     raeburn  13895: =item B<$email> Student's permanent e-mail address
                   13896: 
                   13897: =item B<$type> Type of enrollment (auto or manual)
                   13898: 
1.963     raeburn  13899: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   13900: 
                   13901: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  13902: 
1.963     raeburn  13903: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  13904: 
1.963     raeburn  13905: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  13906: 
1.1216    raeburn  13907: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   13908: 
                   13909: =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  13910: 
1.286     matthew  13911: =back
1.297     matthew  13912: 
                   13913: =item *
                   13914: 
                   13915: modify_student_enrollment
                   13916: 
1.1235    raeburn  13917: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  13918: 'role.request.course' must be defined for this function to proceed.
                   13919: 
                   13920: Inputs:
                   13921: 
                   13922: =over 4
                   13923: 
1.1235    raeburn  13924: =item $udom, student's domain
1.297     matthew  13925: 
1.1235    raeburn  13926: =item $uname, student's name
1.297     matthew  13927: 
1.1235    raeburn  13928: =item $uid, student's user id
1.297     matthew  13929: 
1.1235    raeburn  13930: =item $first, student's first name
1.297     matthew  13931: 
                   13932: =item $middle
                   13933: 
                   13934: =item $last
                   13935: 
                   13936: =item $gene
                   13937: 
                   13938: =item $usec
                   13939: 
                   13940: =item $end
                   13941: 
                   13942: =item $start
                   13943: 
1.957     raeburn  13944: =item $type
                   13945: 
                   13946: =item $locktype
                   13947: 
                   13948: =item $cid
                   13949: 
                   13950: =item $selfenroll
                   13951: 
                   13952: =item $context
                   13953: 
1.1216    raeburn  13954: =item $credits, number of credits student will earn from this class
                   13955: 
1.1314    raeburn  13956: =item $instsec, institutional course section code for student
                   13957: 
1.297     matthew  13958: =back
                   13959: 
1.191     harris41 13960: 
                   13961: =item *
                   13962: 
1.243     albertel 13963: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   13964: custom role; give a custom role to a user for the level given by URL.  Specify
                   13965: name and domain of role author, and role name
1.191     harris41 13966: 
                   13967: =item *
                   13968: 
1.243     albertel 13969: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 13970: 
                   13971: =item *
                   13972: 
1.243     albertel 13973: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   13974: 
                   13975: =back
                   13976: 
                   13977: =head2 Course Infomation
                   13978: 
                   13979: =over 4
1.191     harris41 13980: 
                   13981: =item *
                   13982: 
1.1118    foxr     13983: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 13984: specified course id, including all environment settings for the
                   13985: course, the description of the course will be in the hash under the
                   13986: key 'description'
1.191     harris41 13987: 
1.1118    foxr     13988: $options is an optional parameter that if supplied is a hash reference that controls
                   13989: what how this function works.  It has the following key/values:
                   13990: 
                   13991: =over 4
                   13992: 
                   13993: =item freshen_cache
                   13994: 
                   13995: If defined, and the environment cache for the course is valid, it is 
                   13996: returned in the returned hash.
                   13997: 
                   13998: =item one_time
                   13999: 
                   14000: If defined, the last cache time is set to _now_
                   14001: 
                   14002: =item user
                   14003: 
                   14004: If defined, the supplied username is used instead of the current user.
                   14005: 
                   14006: 
                   14007: =back
                   14008: 
1.191     harris41 14009: =item *
                   14010: 
1.624     albertel 14011: resdata($name,$domain,$type,@which) : request for current parameter
                   14012: setting for a specific $type, where $type is either 'course' or 'user',
                   14013: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  14014: answers for 10 minutes.
1.243     albertel 14015: 
1.877     foxr     14016: =item *
                   14017: 
                   14018: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14019: data base, returning a hash that is keyed by the resource name and has
                   14020: values that are the resource value.  I believe that the timestamps and
                   14021: versions are also returned.
                   14022: 
1.1236    raeburn  14023: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14024: supplemental content area. This routine caches the number of files for 
                   14025: 10 minutes.
                   14026: 
1.243     albertel 14027: =back
                   14028: 
                   14029: =head2 Course Modification
                   14030: 
                   14031: =over 4
1.191     harris41 14032: 
                   14033: =item *
                   14034: 
1.243     albertel 14035: writecoursepref($courseid,%prefs) : write preferences (environment
                   14036: database) for a course
1.191     harris41 14037: 
                   14038: =item *
                   14039: 
1.1011    raeburn  14040: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14041: 
                   14042: =item *
                   14043: 
1.1038    raeburn  14044: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14045: 
1.1167    droeschl 14046: =item *
                   14047: 
                   14048: is_course($courseid), is_course($cdom, $cnum)
                   14049: 
                   14050: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14051: two component version $cdom, $cnum. It checks if the specified course exists.
                   14052: 
                   14053: Returns:
                   14054:     undef if the course doesn't exist, otherwise
                   14055:     in scalar context the combined courseid.
                   14056:     in list context the two components of the course identifier, domain and 
                   14057:     courseid.    
                   14058: 
1.243     albertel 14059: =back
                   14060: 
                   14061: =head2 Resource Subroutines
                   14062: 
                   14063: =over 4
1.191     harris41 14064: 
                   14065: =item *
                   14066: 
1.243     albertel 14067: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 14068: 
                   14069: =item *
                   14070: 
1.243     albertel 14071: repcopy($filename) : subscribes to the requested file, and attempts to
                   14072: replicate from the owning library server, Might return
1.607     raeburn  14073: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   14074: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 14075: resource. Expects the local filesystem pathname
                   14076: (/home/httpd/html/res/....)
                   14077: 
                   14078: =back
                   14079: 
                   14080: =head2 Resource Information
                   14081: 
                   14082: =over 4
1.191     harris41 14083: 
                   14084: =item *
                   14085: 
1.1228    raeburn  14086: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   14087: and returns the value of a variety of different possible values,
                   14088: $varname should be a request string, and the other parameters can be
                   14089: used to specify who and what one is asking about. Ordinarily, $cid 
                   14090: does not need to be specified, as it is retrived from 
                   14091: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14092: within lonuserstate::loadmap() when initializing a course, before
                   14093: $env{'request.course.id'} has been set, so it needs to be provided
                   14094: in that one case.
1.243     albertel 14095: 
                   14096: Possible values for $varname are environment.lastname (or other item
                   14097: from the envirnment hash), user.name (or someother aspect about the
                   14098: user), resource.0.maxtries (or some other part and parameter of a
                   14099: resource)
1.204     albertel 14100: 
                   14101: =item *
                   14102: 
1.243     albertel 14103: directcondval($number) : get current value of a condition; reads from a state
                   14104: string
1.204     albertel 14105: 
                   14106: =item *
                   14107: 
1.243     albertel 14108: condval($condidx) : value of condition index based on state
1.204     albertel 14109: 
                   14110: =item *
                   14111: 
1.243     albertel 14112: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   14113: resource's metadata, $what should be either a specific key, or either
                   14114: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   14115: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   14116: 
                   14117: this function automatically caches all requests
1.191     harris41 14118: 
                   14119: =item *
                   14120: 
1.243     albertel 14121: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   14122: network of library servers; returns file handle of where SQL and regex results
                   14123: will be stored for query
1.191     harris41 14124: 
                   14125: =item *
                   14126: 
1.1282    raeburn  14127: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   14128: return symbolic list entry (all arguments optional). 
                   14129: 
                   14130: Args: filename is the filename (including path) for the file for which a symb 
                   14131: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   14132: to check access status if more than one resource was found in the bighash 
                   14133: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   14134: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   14135: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   14136: cause possible symbs to be checked to determine if they are subject to content
                   14137: blocking, if so they will not be included as possible symbs; possibles is a
                   14138: ref to a hash, which, as a side effect, will be populated with all possible 
                   14139: symbs (content blocking not tested).
                   14140:  
1.243     albertel 14141: returns the data handle
1.191     harris41 14142: 
                   14143: =item *
                   14144: 
1.1190    raeburn  14145: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   14146: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 14147: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  14148: on failure, user must be in a course, as it assumes the existence of
                   14149: the course initial hash, and uses $env('request.course.id'}.  The third
                   14150: arg is an optional reference to a scalar.  If this arg is passed in the 
                   14151: call to symbverify, it will be set to 1 if the symb has been set to be 
                   14152: encrypted; otherwise it will be null.  
1.191     harris41 14153: 
                   14154: =item *
                   14155: 
1.243     albertel 14156: symbclean($symb) : removes versions numbers from a symb, returns the
                   14157: cleaned symb
1.191     harris41 14158: 
                   14159: =item *
                   14160: 
1.243     albertel 14161: is_on_map($uri) : checks if the $uri is somewhere on the current
                   14162: course map, user must be in a course for it to work.
1.191     harris41 14163: 
                   14164: =item *
                   14165: 
1.243     albertel 14166: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 14167: 
                   14168: =item *
                   14169: 
1.243     albertel 14170: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   14171: a random seed, all arguments are optional, if they aren't sent it uses the
                   14172: environment to derive them. Note: if symb isn't sent and it can't get one
                   14173: from &symbread it will use the current time as its return value
1.191     harris41 14174: 
                   14175: =item *
                   14176: 
1.243     albertel 14177: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   14178: unfakeable, receipt
1.191     harris41 14179: 
                   14180: =item *
                   14181: 
1.620     albertel 14182: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 14183: 
                   14184: =item *
                   14185: 
1.243     albertel 14186: countacc($url) : count the number of accesses to a given URL
1.191     harris41 14187: 
                   14188: =item *
                   14189: 
1.243     albertel 14190: 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 14191: 
                   14192: =item *
                   14193: 
1.243     albertel 14194: 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 14195: 
                   14196: =item *
                   14197: 
1.243     albertel 14198: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 14199: 
                   14200: =item *
                   14201: 
1.243     albertel 14202: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   14203: forcing spreadsheet to reevaluate the resource scores next time.
                   14204: 
1.1195    raeburn  14205: =item * 
                   14206: 
1.1196    raeburn  14207: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   14208: when viewing in course context.
1.1195    raeburn  14209: 
1.1196    raeburn  14210:  input: six args -- filename (decluttered), course number, course domain,
                   14211:                     url, symb (if registered) and group (if this is a 
                   14212:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  14213: 
1.1196    raeburn  14214:  output: array of five scalars --
1.1195    raeburn  14215:          $cfile -- url for file editing if editable on current server
                   14216:          $home -- homeserver of resource (i.e., for author if published,
                   14217:                                           or course if uploaded.).
                   14218:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  14219:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   14220:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  14221: 
                   14222: =item *
                   14223: 
                   14224: is_course_upload($file,$cnum,$cdom)
                   14225: 
                   14226: Used in course context to determine if current file was uploaded to 
                   14227: the course (i.e., would be found in /userfiles/docs on the course's 
                   14228: homeserver.
                   14229: 
                   14230:   input: 3 args -- filename (decluttered), course number and course domain.
                   14231:   output: boolean -- 1 if file was uploaded.
                   14232: 
1.243     albertel 14233: =back
                   14234: 
                   14235: =head2 Storing/Retreiving Data
                   14236: 
                   14237: =over 4
1.191     harris41 14238: 
                   14239: =item *
                   14240: 
1.1269    raeburn  14241: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   14242: permanently for this url; hashref needs to be given and should be a \%hashname;
                   14243: the remaining args aren't required and if they aren't passed or are '' they will
                   14244: be derived from the env (with the exception of $laststore, which is an 
                   14245: optional arg used when a user's submission is stored in grading).
                   14246: $laststore is $version=$timestamp, where $version is the most recent version
                   14247: number retrieved for the corresponding $symb in the $namespace db file, and
                   14248: $timestamp is the timestamp for that transaction (UNIX time).
                   14249: $laststore is currently only passed when cstore() is called by 
                   14250: structuretags::finalize_storage().
1.191     harris41 14251: 
                   14252: =item *
                   14253: 
1.1269    raeburn  14254: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   14255: but uses critical subroutine
1.191     harris41 14256: 
                   14257: =item *
                   14258: 
1.243     albertel 14259: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   14260: all args are optional
1.191     harris41 14261: 
                   14262: =item *
                   14263: 
1.717     albertel 14264: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   14265: dumps the complete (or key matching regexp) namespace into a hash
                   14266: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   14267: normally &store()ed into
                   14268: 
                   14269: $range should be either an integer '100' (give me the first 100
                   14270:                                            matching records)
                   14271:               or be  two integers sperated by a - with no spaces
                   14272:                  '30-50' (give me the 30th through the 50th matching
                   14273:                           records)
                   14274: 
                   14275: 
                   14276: =item *
                   14277: 
1.1269    raeburn  14278: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 14279: replaces a &store() version of data with a replacement set of data
                   14280: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  14281: reference. If $tolog is true, the transaction is logged in the courselog
                   14282: with an action=PUTSTORE.
1.717     albertel 14283: 
                   14284: =item *
                   14285: 
1.243     albertel 14286: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   14287: works very similar to store/cstore, but all data is stored in a
                   14288: temporary location and can be reset using tmpreset, $storehash should
                   14289: be a hash reference, returns nothing on success
1.191     harris41 14290: 
                   14291: =item *
                   14292: 
1.243     albertel 14293: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   14294: similar to restore, but all data is stored in a temporary location and
                   14295: can be reset using tmpreset. Returns a hash of values on success,
                   14296: error string otherwise.
1.191     harris41 14297: 
                   14298: =item *
                   14299: 
1.243     albertel 14300: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   14301: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 14302: 
                   14303: =item *
                   14304: 
1.243     albertel 14305: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14306: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 14307: 
                   14308: =item *
                   14309: 
1.243     albertel 14310: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   14311: namesp ($udom and $uname are optional)
1.191     harris41 14312: 
                   14313: =item *
                   14314: 
1.702     albertel 14315: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 14316: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 14317: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  14318: 
1.702     albertel 14319: $range should be either an integer '100' (give me the first 100
                   14320:                                            matching records)
                   14321:               or be  two integers sperated by a - with no spaces
                   14322:                  '30-50' (give me the 30th through the 50th matching
                   14323:                           records)
1.449     matthew  14324: =item *
                   14325: 
                   14326: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   14327: $store can be a scalar, an array reference, or if the amount to be 
                   14328: incremented is > 1, a hash reference.
                   14329: 
                   14330: ($udom and $uname are optional)
1.191     harris41 14331: 
                   14332: =item *
                   14333: 
1.243     albertel 14334: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   14335: ($udom and $uname are optional)
1.191     harris41 14336: 
                   14337: =item *
                   14338: 
1.243     albertel 14339: cput($namespace,$storehash,$udom,$uname) : critical put
                   14340: ($udom and $uname are optional)
1.191     harris41 14341: 
                   14342: =item *
                   14343: 
1.748     albertel 14344: newput($namespace,$storehash,$udom,$uname) :
                   14345: 
                   14346: Attempts to store the items in the $storehash, but only if they don't
                   14347: currently exist, if this succeeds you can be certain that you have 
                   14348: successfully created a new key value pair in the $namespace db.
                   14349: 
                   14350: 
                   14351: Args:
                   14352:  $namespace: name of database to store values to
                   14353:  $storehash: hashref to store to the db
                   14354:  $udom: (optional) domain of user containing the db
                   14355:  $uname: (optional) name of user caontaining the db
                   14356: 
                   14357: Returns:
                   14358:  'ok' -> succeeded in storing all keys of $storehash
                   14359:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   14360:                         least <key> already existed in the db (other
                   14361:                         requested keys may also already exist)
1.967     bisitz   14362:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 14363:  'con_lost' -> unable to contact request server
                   14364:  'refused' -> action was not allowed by remote machine
                   14365: 
                   14366: 
                   14367: =item *
                   14368: 
1.243     albertel 14369: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14370: reference filled in from namesp (encrypts the return communication)
                   14371: ($udom and $uname are optional)
1.191     harris41 14372: 
                   14373: =item *
                   14374: 
1.243     albertel 14375: log($udom,$name,$home,$message) : write to permanent log for user; use
                   14376: critical subroutine
                   14377: 
1.806     raeburn  14378: =item *
                   14379: 
1.860     raeburn  14380: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   14381: array reference filled in from namespace found in domain level on either
                   14382: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  14383: 
                   14384: =item *
                   14385: 
1.860     raeburn  14386: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   14387: domain level either on specified domain server ($uhome) or primary domain 
                   14388: server ($udom and $uhome are optional)
1.806     raeburn  14389: 
1.943     raeburn  14390: =item * 
                   14391: 
1.1240    raeburn  14392: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   14393: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   14394: the target domain.
                   14395: 
                   14396: May also include additional key => value pairs for the following groups:
                   14397: 
                   14398: =over
                   14399: 
                   14400: =item
                   14401: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   14402: 
                   14403: =over
                   14404: 
                   14405: =item defaultquota, authorquota
                   14406: 
                   14407: =back
                   14408: 
                   14409: =item
                   14410: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   14411: portfolio for users).
                   14412: 
                   14413: =over
                   14414: 
                   14415: =item
                   14416: aboutme, blog, webdav, portfolio
                   14417: 
                   14418: =back
                   14419: 
                   14420: =item
                   14421: requestcourses: ability to request courses, and how requests are processed.
                   14422: 
                   14423: =over
                   14424: 
                   14425: =item
1.1305    raeburn  14426: official, unofficial, community, textbook, placement
1.1240    raeburn  14427: 
                   14428: =back
                   14429: 
                   14430: =item
                   14431: inststatus: types of institutional affiliation, and order in which they are displayed.
                   14432: 
                   14433: =over
                   14434: 
                   14435: =item
1.1256    raeburn  14436: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  14437: 
                   14438: =back
                   14439: 
                   14440: =item
                   14441: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   14442: for course's uploaded content.
                   14443: 
                   14444: =over
                   14445: 
                   14446: =item
1.1246    raeburn  14447: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  14448: communityquota, textbookquota, placementquota
1.1240    raeburn  14449: 
                   14450: =back
                   14451: 
                   14452: =item
                   14453: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   14454: on your servers.
                   14455: 
                   14456: =over
                   14457: 
                   14458: =item 
                   14459: remotesessions, hostedsessions
                   14460: 
                   14461: =back
                   14462: 
                   14463: =back
                   14464: 
                   14465: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   14466: utility to create a configuration.db file on a domain's primary library server 
                   14467: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   14468: -- corresponding values are authentication type (internal, krb4, krb5,
                   14469: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   14470: will be available. Values are retrieved from cache (if current), unless the
                   14471: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   14472: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   14473: 
                   14474: Typical usage:
1.943     raeburn  14475: 
1.1240    raeburn  14476: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  14477: 
1.243     albertel 14478: =back
                   14479: 
                   14480: =head2 Network Status Functions
                   14481: 
                   14482: =over 4
1.191     harris41 14483: 
                   14484: =item *
                   14485: 
1.1137    raeburn  14486: dirlist() : return directory list based on URI (first arg).
                   14487: 
                   14488: Inputs: 1 required, 5 optional.
                   14489: 
                   14490: =over
                   14491: 
                   14492: =item 
                   14493: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   14494: 
                   14495: =item
                   14496: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   14497: 
                   14498: =item
                   14499: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   14500: 
                   14501: =item
                   14502: $getpropath - boolean: 1 if prepend path using &propath(). 
                   14503: 
                   14504: =item
                   14505: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   14506: 
                   14507: =item 
                   14508: $alternateRoot - path to prepend in place of path from $uri.
                   14509: 
                   14510: =back
                   14511: 
                   14512: Returns: Array of up to two items.
                   14513: 
                   14514: =over
                   14515: 
                   14516: a reference to an array of files/subdirectories
                   14517: 
                   14518: =over
                   14519: 
                   14520: Each element in the array of files/subdirectories is a & separated list of
                   14521: item name and the result of running stat on the item.  If dirlist was requested
                   14522: for a file instead of a directory, the item name will be ''. For a directory 
                   14523: listing, if the item is a metadata file, the element will end &N&M 
                   14524: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   14525: default copyright set (1).  
                   14526: 
                   14527: =back
                   14528: 
                   14529: a scalar containing error condition (if encountered).
                   14530: 
                   14531: =over
                   14532: 
                   14533: =item 
                   14534: no_host (no homeserver identified for $username:$domain).
                   14535: 
                   14536: =item 
                   14537: no_such_host (server contacted for listing not identified as valid host).
                   14538: 
                   14539: =item 
                   14540: con_lost (connection to remote server failed).
                   14541: 
                   14542: =item 
                   14543: refused (invalid $username:$domain received on lond side).
                   14544: 
                   14545: =item 
                   14546: no_such_dir (directory at specified path on lond side does not exist). 
                   14547: 
                   14548: =item 
                   14549: empty (directory at specified path on lond side is empty).
                   14550: 
                   14551: =over
                   14552: 
                   14553: This is currently not encountered because the &ls3, &ls2, 
                   14554: &ls (_handler) routines on the lond side do not filter out
                   14555: . and .. from a directory listing. 
                   14556: 
                   14557: =back
                   14558: 
                   14559: =back
                   14560: 
                   14561: =back
1.191     harris41 14562: 
                   14563: =item *
                   14564: 
1.243     albertel 14565: spareserver() : find server with least workload from spare.tab
                   14566: 
1.986     foxr     14567: 
                   14568: =item *
                   14569: 
                   14570: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   14571: if there is no corresponding loncapa host.
                   14572: 
1.243     albertel 14573: =back
                   14574: 
1.986     foxr     14575: 
1.243     albertel 14576: =head2 Apache Request
                   14577: 
                   14578: =over 4
1.191     harris41 14579: 
                   14580: =item *
                   14581: 
1.243     albertel 14582: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   14583: localhost, posts hash
                   14584: 
                   14585: =back
                   14586: 
                   14587: =head2 Data to String to Data
                   14588: 
                   14589: =over 4
1.191     harris41 14590: 
                   14591: =item *
                   14592: 
1.243     albertel 14593: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   14594: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 14595: 
                   14596: =item *
                   14597: 
1.243     albertel 14598: hashref2str($hashref) : convert a hashref into a string complete with
                   14599: escaping and '=' and '&' separators, supports elements that are
                   14600: arrayrefs and hashrefs
1.191     harris41 14601: 
                   14602: =item *
                   14603: 
1.243     albertel 14604: arrayref2str($arrayref) : convert an arrayref into a string complete
                   14605: with escaping and '&' separators, supports elements that are arrayrefs
                   14606: and hashrefs
1.191     harris41 14607: 
                   14608: =item *
                   14609: 
1.243     albertel 14610: str2hash($string) : convert string to hash using unescaping and
                   14611: splitting on '=' and '&', supports elements that are arrayrefs and
                   14612: hashrefs
1.191     harris41 14613: 
                   14614: =item *
                   14615: 
1.243     albertel 14616: str2array($string) : convert string to hash using unescaping and
                   14617: splitting on '&', supports elements that are arrayrefs and hashrefs
                   14618: 
                   14619: =back
                   14620: 
                   14621: =head2 Logging Routines
                   14622: 
                   14623: 
                   14624: These routines allow one to make log messages in the lonnet.log and
                   14625: lonnet.perm logfiles.
1.191     harris41 14626: 
1.1119    foxr     14627: =over 4
                   14628: 
1.191     harris41 14629: =item *
                   14630: 
1.243     albertel 14631: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 14632: 
                   14633: =item *
                   14634: 
1.243     albertel 14635: logthis() : append message to the normal lonnet.log file, it gets
                   14636: preiodically rolled over and deleted.
1.191     harris41 14637: 
                   14638: =item *
                   14639: 
1.243     albertel 14640: logperm() : append a permanent message to lonnet.perm.log, this log
                   14641: file never gets deleted by any automated portion of the system, only
                   14642: messages of critical importance should go in here.
                   14643: 
1.1119    foxr     14644: 
1.243     albertel 14645: =back
                   14646: 
                   14647: =head2 General File Helper Routines
                   14648: 
                   14649: =over 4
1.191     harris41 14650: 
                   14651: =item *
                   14652: 
1.481     raeburn  14653: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   14654: (a) files in /uploaded
                   14655:   (i) If a local copy of the file exists - 
                   14656:       compares modification date of local copy with last-modified date for 
                   14657:       definitive version stored on home server for course. If local copy is 
                   14658:       stale, requests a new version from the home server and stores it. 
                   14659:       If the original has been removed from the home server, then local copy 
                   14660:       is unlinked.
                   14661:   (ii) If local copy does not exist -
                   14662:       requests the file from the home server and stores it. 
                   14663:   
                   14664:   If $caller is 'uploadrep':  
                   14665:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   14666:     for request for files originally uploaded via DOCS. 
                   14667:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   14668:   
                   14669:   Otherwise:
                   14670:      This indicates a call from the content generation phase of the request.
                   14671:      -  returns the entire contents of the file or -1.
                   14672:      
                   14673: (b) files in /res
                   14674:    - returns the entire contents of a file or -1; 
                   14675:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 14676: 
1.712     albertel 14677: 
                   14678: =item *
                   14679: 
                   14680: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   14681:                   reference
                   14682: 
                   14683: returns either a stat() list of data about the file or an empty list
                   14684: if the file doesn't exist or couldn't find out about it (connection
                   14685: problems or user unknown)
                   14686: 
1.191     harris41 14687: =item *
                   14688: 
1.243     albertel 14689: filelocation($dir,$file) : returns file system location of a file
                   14690: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   14691: directory that relative $file lookups are to looked in ($dir of /a/dir
                   14692: and a file of ../bob will become /a/bob)
1.191     harris41 14693: 
                   14694: =item *
                   14695: 
                   14696: hreflocation($dir,$file) : returns file system location or a URL; same as
                   14697: filelocation except for hrefs
                   14698: 
                   14699: =item *
                   14700: 
1.1261    raeburn  14701: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   14702: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 14703: 
1.243     albertel 14704: =back
                   14705: 
1.608     albertel 14706: =head2 Usererfile file routines (/uploaded*)
                   14707: 
                   14708: =over 4
                   14709: 
                   14710: =item *
                   14711: 
                   14712: userfileupload(): main rotine for putting a file in a user or course's
                   14713:                   filespace, arguments are,
                   14714: 
1.620     albertel 14715:  formname - required - this is the name of the element in $env where the
1.608     albertel 14716:            filename, and the contents of the file to create/modifed exist
1.620     albertel 14717:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   14718:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  14719:  context - if coursedoc, store the file in the course of the active role
                   14720:              of the current user; 
                   14721:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   14722:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 14723:  subdir - required - subdirectory to put the file in under ../userfiles/
                   14724:          if undefined, it will be placed in "unknown"
                   14725: 
                   14726:  (This routine calls clean_filename() to remove any dangerous
                   14727:  characters from the filename, and then calls finuserfileupload() to
                   14728:  complete the transaction)
                   14729: 
                   14730:  returns either the url of the uploaded file (/uploaded/....) if successful
                   14731:  and /adm/notfound.html if unsuccessful
                   14732: 
                   14733: =item *
                   14734: 
                   14735: clean_filename(): routine for cleaing a filename up for storage in
                   14736:                  userfile space, argument is:
                   14737: 
                   14738:  filename - proposed filename
                   14739: 
                   14740: returns: the new clean filename
                   14741: 
                   14742: =item *
                   14743: 
1.1090    raeburn  14744: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 14745: userspace, probably shouldn't be called directly
                   14746: 
                   14747:   docuname: username or courseid of destination for the file
                   14748:   docudom: domain of user/course of destination for the file
                   14749:   formname: same as for userfileupload()
1.1090    raeburn  14750:   fname: filename (including subdirectories) for the file
                   14751:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   14752:   allfiles: reference to hash used to store objects found by parser
                   14753:   codebase: reference to hash used for codebases of java objects found by parser
                   14754:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   14755:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   14756:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   14757:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   14758:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   14759:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  14760:   mimetype: reference to scalar to accommodate mime type determined
                   14761:             from File::MMagic if $parser = parse.
1.608     albertel 14762: 
                   14763:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  14764:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   14765:  was 'overwrite').
                   14766:  
1.608     albertel 14767: 
                   14768: =item *
                   14769: 
                   14770: renameuserfile(): renames an existing userfile to a new name
                   14771: 
                   14772:   Args:
                   14773:    docuname: username or courseid of destination for the file
                   14774:    docudom: domain of user/course of destination for the file
                   14775:    old: current file name (including any subdirs under userfiles)
                   14776:    new: desired file name (including any subdirs under userfiles)
                   14777: 
                   14778: =item *
                   14779: 
                   14780: mkdiruserfile(): creates a directory is a userfiles dir
                   14781: 
                   14782:   Args:
                   14783:    docuname: username or courseid of destination for the file
                   14784:    docudom: domain of user/course of destination for the file
                   14785:    dir: dir to create (including any subdirs under userfiles)
                   14786: 
                   14787: =item *
                   14788: 
                   14789: removeuserfile(): removes a file that exists in userfiles
                   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:    fname: filname to delete (including any subdirs under userfiles)
                   14795: 
                   14796: =item *
                   14797: 
                   14798: removeuploadedurl(): convience function for removeuserfile()
                   14799: 
                   14800:   Args:
                   14801:    url:  a full /uploaded/... url to delete
                   14802: 
1.747     albertel 14803: =item * 
                   14804: 
                   14805: get_portfile_permissions():
                   14806:   Args:
                   14807:     domain: domain of user or course contain the portfolio files
                   14808:     user: name of user or num of course contain the portfolio files
                   14809:   Returns:
                   14810:     hashref of a dump of the proper file_permissions.db
                   14811:    
                   14812: 
                   14813: =item * 
                   14814: 
                   14815: get_access_controls():
                   14816: 
                   14817: Args:
                   14818:   current_permissions: the hash ref returned from get_portfile_permissions()
                   14819:   group: (optional) the group you want the files associated with
                   14820:   file: (optional) the file you want access info on
                   14821: 
                   14822: Returns:
1.749     raeburn  14823:     a hash (keys are file names) of hashes containing
                   14824:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   14825:         values are XML containing access control settings (see below) 
1.747     albertel 14826: 
                   14827: Internal notes:
                   14828: 
1.749     raeburn  14829:  access controls are stored in file_permissions.db as key=value pairs.
                   14830:     key -> path to file/file_name\0uniqueID:scope_end_start
                   14831:         where scope -> public,guest,course,group,domains or users.
                   14832:               end -> UNIX time for end of access (0 -> no end date)
                   14833:               start -> UNIX time for start of access
                   14834: 
                   14835:     value -> XML description of access control
                   14836:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   14837:             <start></start>
                   14838:             <end></end>
                   14839: 
                   14840:             <password></password>  for scope type = guest
                   14841: 
                   14842:             <domain></domain>     for scope type = course or group
                   14843:             <number></number>
                   14844:             <roles id="">
                   14845:              <role></role>
                   14846:              <access></access>
                   14847:              <section></section>
                   14848:              <group></group>
                   14849:             </roles>
                   14850: 
                   14851:             <dom></dom>         for scope type = domains
                   14852: 
                   14853:             <users>             for scope type = users
                   14854:              <user>
                   14855:               <uname></uname>
                   14856:               <udom></udom>
                   14857:              </user>
                   14858:             </users>
                   14859:            </scope> 
                   14860:               
                   14861:  Access data is also aggregated for each file in an additional key=value pair:
                   14862:  key -> path to file/file_name\0accesscontrol 
                   14863:  value -> reference to hash
                   14864:           hash contains key = value pairs
                   14865:           where key = uniqueID:scope_end_start
                   14866:                 value = UNIX time record was last updated
                   14867: 
                   14868:           Used to improve speed of look-ups of access controls for each file.  
                   14869:  
                   14870:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   14871: 
1.1198    raeburn  14872: =item *
                   14873: 
1.749     raeburn  14874: modify_access_controls():
                   14875: 
                   14876: Modifies access controls for a portfolio file
                   14877: Args
                   14878: 1. file name
                   14879: 2. reference to hash of required changes,
                   14880: 3. domain
                   14881: 4. username
                   14882:   where domain,username are the domain of the portfolio owner 
                   14883:   (either a user or a course) 
                   14884: 
                   14885: Returns:
                   14886: 1. result of additions or updates ('ok' or 'error', with error message). 
                   14887: 2. result of deletions ('ok' or 'error', with error message).
                   14888: 3. reference to hash of any new or updated access controls.
                   14889: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   14890:    key = integer (inbound ID)
1.1198    raeburn  14891:    value = uniqueID
                   14892: 
                   14893: =item *
                   14894: 
                   14895: get_timebased_id():
                   14896: 
                   14897: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   14898: course via the Course Editor (e.g., folders, composite pages, 
                   14899: group bulletin boards).
                   14900: 
                   14901: Args: (first three required; six others optional)
                   14902: 
                   14903: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   14904:    docssequence, or name of group
                   14905: 
                   14906: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   14907:    e.g., num, boardids
                   14908: 
                   14909: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   14910:    file will be named nohist_namespace.db
                   14911: 
                   14912: 4. cdom: domain of course; default is current course domain from %env
                   14913: 
                   14914: 5. cnum: course number; default is current course number from %env
                   14915: 
                   14916: 6. idtype: set to concat if an additional digit is to be appended to the 
                   14917:    unix timestamp to form the suffix, if the plain timestamp is already
                   14918:    in use.  Default is to not do this, but simply increment the unix 
                   14919:    timestamp by 1 until a unique key is obtained.
                   14920: 
                   14921: 7. who: holder of locking key; defaults to user:domain for user.
                   14922: 
                   14923: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   14924:    retrying); default is 3.
                   14925: 
                   14926: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   14927: 
                   14928: Returns:
                   14929: 
                   14930: 1. suffix obtained (numeric)
                   14931: 
                   14932: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   14933: 
                   14934: 3. error: contains (localized) error message if an error occurred.
                   14935: 
1.747     albertel 14936: 
1.608     albertel 14937: =back
                   14938: 
1.243     albertel 14939: =head2 HTTP Helper Routines
                   14940: 
                   14941: =over 4
                   14942: 
1.191     harris41 14943: =item *
                   14944: 
                   14945: escape() : unpack non-word characters into CGI-compatible hex codes
                   14946: 
                   14947: =item *
                   14948: 
                   14949: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   14950: 
1.243     albertel 14951: =back
                   14952: 
                   14953: =head1 PRIVATE SUBROUTINES
                   14954: 
                   14955: =head2 Underlying communication routines (Shouldn't call)
                   14956: 
                   14957: =over 4
                   14958: 
                   14959: =item *
                   14960: 
                   14961: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   14962: 
                   14963: =item *
                   14964: 
                   14965: reply() : uses subreply to send a message to remote machine, logs all failures
                   14966: 
                   14967: =item *
                   14968: 
                   14969: critical() : passes a critical message to another server; if cannot
                   14970: get through then place message in connection buffer directory and
                   14971: returns con_delayed, if incapable of saving message, returns
                   14972: con_failed
                   14973: 
                   14974: =item *
                   14975: 
                   14976: reconlonc() : tries to reconnect lonc client processes.
                   14977: 
                   14978: =back
                   14979: 
                   14980: =head2 Resource Access Logging
                   14981: 
                   14982: =over 4
                   14983: 
                   14984: =item *
                   14985: 
                   14986: flushcourselogs() : flush (save) buffer logs and access logs
                   14987: 
                   14988: =item *
                   14989: 
                   14990: courselog($what) : save message for course in hash
                   14991: 
                   14992: =item *
                   14993: 
                   14994: courseacclog($what) : save message for course using &courselog().  Perform
                   14995: special processing for specific resource types (problems, exams, quizzes, etc).
                   14996: 
1.191     harris41 14997: =item *
                   14998: 
                   14999: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15000: as a PerlChildExitHandler
1.243     albertel 15001: 
                   15002: =back
                   15003: 
                   15004: =head2 Other
                   15005: 
                   15006: =over 4
                   15007: 
                   15008: =item *
                   15009: 
                   15010: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15011: 
                   15012: =back
                   15013: 
                   15014: =cut
1.877     foxr     15015: 

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