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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1334  ! raeburn     4: # $Id: lonnet.pm,v 1.1333 2017/01/05 18:44:41 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.1331    raeburn  1052:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
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 {
1.1331    raeburn  1324:     my ($uname,$udom,$caller) = @_;
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.1331    raeburn  1475:         unless ($caller eq 'login') {
                   1476:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1477:                 $is_balancer = 0;
                   1478:                 if ($uname ne '' && $udom ne '') {
                   1479:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1176    raeburn  1480:                     
1.1331    raeburn  1481:                         &appenv({'user.loadbalexempt'     => $lonhost,  
                   1482:                                  'user.loadbalcheck.time' => time});
                   1483:                     }
1.1176    raeburn  1484:                 }
1.1129    raeburn  1485:             }
                   1486:         }
                   1487:     }
                   1488:     return ($is_balancer,$otherserver);
                   1489: }
                   1490: 
1.1191    raeburn  1491: sub check_balancer_result {
                   1492:     my ($result,@hosts) = @_;
                   1493:     my ($is_balancer,$currtargets,$currrules);
                   1494:     if (ref($result) eq 'HASH') {
                   1495:         if ($result->{'lonhost'} ne '') {
                   1496:             my $currbalancer = $result->{'lonhost'};
                   1497:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1498:                 $is_balancer = 1;
                   1499:                 $currtargets = $result->{'targets'};
                   1500:                 $currrules = $result->{'rules'};
                   1501:             }
                   1502:         } else {
                   1503:             foreach my $key (keys(%{$result})) {
                   1504:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1505:                     (ref($result->{$key}) eq 'HASH')) {
                   1506:                     $is_balancer = 1;
                   1507:                     $currrules = $result->{$key}{'rules'};
                   1508:                     $currtargets = $result->{$key}{'targets'};
                   1509:                     last;
                   1510:                 }
                   1511:             }
                   1512:         }
                   1513:     }
                   1514:     return ($is_balancer,$currtargets,$currrules);
                   1515: }
                   1516: 
1.1129    raeburn  1517: sub get_loadbalancer_targets {
                   1518:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1519:     my $offloadto;
1.1175    raeburn  1520:     if ($rule_in_effect eq 'none') {
                   1521:         return [$perlvar{'lonHostID'}];
                   1522:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1523:         $offloadto = $currtargets;
                   1524:     } else {
                   1525:         if ($rule_in_effect eq 'homeserver') {
                   1526:             my $homeserver = &homeserver($uname,$udom);
                   1527:             if ($homeserver ne 'no_host') {
                   1528:                 $offloadto = [$homeserver];
                   1529:             }
                   1530:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1531:             my %domconfig =
                   1532:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1533:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1534:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1535:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1536:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1537:                     }
                   1538:                 }
                   1539:             } else {
1.1178    raeburn  1540:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1541:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1542:                 if (&hostname($remotebalancer) ne '') {
                   1543:                     $offloadto = [$remotebalancer];
                   1544:                 }
                   1545:             }
                   1546:         } elsif (&hostname($rule_in_effect) ne '') {
                   1547:             $offloadto = [$rule_in_effect];
                   1548:         }
                   1549:     }
                   1550:     return $offloadto;
                   1551: }
                   1552: 
1.1127    raeburn  1553: sub internet_dom_servers {
                   1554:     my ($dom) = @_;
                   1555:     my (%uniqservers,%servers);
                   1556:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1557:     my @machinedoms = &machine_domains($primaryserver);
                   1558:     foreach my $mdom (@machinedoms) {
                   1559:         my %currservers = %servers;
                   1560:         my %server = &get_servers($mdom);
                   1561:         %servers = (%currservers,%server);
                   1562:     }
                   1563:     my %by_hostname;
                   1564:     foreach my $id (keys(%servers)) {
                   1565:         push(@{$by_hostname{$servers{$id}}},$id);
                   1566:     }
                   1567:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1568:         if (@{$by_hostname{$hostname}} > 1) {
                   1569:             my $match = 0;
                   1570:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1571:                 if (&host_domain($id) eq $dom) {
                   1572:                     $uniqservers{$id} = $hostname;
                   1573:                     $match = 1;
                   1574:                 }
                   1575:             }
                   1576:             unless ($match) {
                   1577:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1578:             }
                   1579:         } else {
                   1580:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1581:         }
                   1582:     }
                   1583:     return %uniqservers;
                   1584: }
                   1585: 
1.1       albertel 1586: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1587: 
1.599     albertel 1588: my %homecache;
1.1       albertel 1589: sub homeserver {
1.230     stredwic 1590:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1591:     my $index="$uname:$udom";
1.426     albertel 1592: 
1.599     albertel 1593:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1594: 
                   1595:     my %servers = &get_servers($udom,'library');
                   1596:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1597:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1598: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1599: 
                   1600: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1601: 	if ($answer eq 'found') {
                   1602: 	    delete($badServerCache{$tryserver}); 
                   1603: 	    return $homecache{$index}=$tryserver;
                   1604: 	} elsif ($answer eq 'no_host') {
                   1605: 	    $badServerCache{$tryserver}=1;
                   1606: 	}
1.1       albertel 1607:     }    
                   1608:     return 'no_host';
1.70      www      1609: }
                   1610: 
1.1300    raeburn  1611: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70      www      1612: 
                   1613: sub idget {
1.1300    raeburn  1614:     my ($udom,$idsref,$namespace)=@_;
1.70      www      1615:     my %returnhash=();
1.1300    raeburn  1616:     my @ids=(); 
                   1617:     if (ref($idsref) eq 'ARRAY') {
                   1618:         @ids = @{$idsref};
                   1619:     } else {
                   1620:         return %returnhash; 
                   1621:     }
                   1622:     if ($namespace eq '') {
                   1623:         $namespace = 'ids';
                   1624:     }
1.70      www      1625:     
1.841     albertel 1626:     my %servers = &get_servers($udom,'library');
                   1627:     foreach my $tryserver (keys(%servers)) {
1.1299    raeburn  1628: 	my $idlist=join('&', map { &escape($_); } @ids);
1.1300    raeburn  1629: 	if ($namespace eq 'ids') {
                   1630: 	    $idlist=~tr/A-Z/a-z/;
                   1631: 	}
                   1632: 	my $reply;
                   1633: 	if ($namespace eq 'ids') {
                   1634: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1635: 	} else {
                   1636: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
                   1637: 	}
1.841     albertel 1638: 	my @answer=();
                   1639: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1640: 	    @answer=split(/\&/,$reply);
                   1641: 	}                    ;
                   1642: 	my $i;
                   1643: 	for ($i=0;$i<=$#ids;$i++) {
                   1644: 	    if ($answer[$i]) {
1.1299    raeburn  1645: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300    raeburn  1646: 	    }
1.841     albertel 1647: 	}
1.1300    raeburn  1648:     }
1.70      www      1649:     return %returnhash;
                   1650: }
                   1651: 
                   1652: # ------------------------------------- Find the IDs behind a list of usernames
                   1653: 
                   1654: sub idrget {
                   1655:     my ($udom,@unames)=@_;
                   1656:     my %returnhash=();
1.800     albertel 1657:     foreach my $uname (@unames) {
                   1658:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1659:     }
1.70      www      1660:     return %returnhash;
                   1661: }
                   1662: 
1.1300    raeburn  1663: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70      www      1664: 
                   1665: sub idput {
1.1300    raeburn  1666:     my ($udom,$idsref,$uhom,$namespace)=@_;
1.70      www      1667:     my %servers=();
1.1300    raeburn  1668:     my %ids=();
                   1669:     my %byid = ();
                   1670:     if (ref($idsref) eq 'HASH') {
                   1671:         %ids=%{$idsref};
                   1672:     }
                   1673:     if ($namespace eq '') {
                   1674:         $namespace = 'ids'; 
                   1675:     }
1.800     albertel 1676:     foreach my $uname (keys(%ids)) {
                   1677: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300    raeburn  1678:         if ($uhom eq '') {
                   1679:             $uhom=&homeserver($uname,$udom);
                   1680:         }
1.70      www      1681:         if ($uhom ne 'no_host') {
1.800     albertel 1682:             my $esc_unam=&escape($uname);
1.1300    raeburn  1683:             if ($namespace eq 'ids') {
                   1684:                 my $id=&escape($ids{$uname});
                   1685:                 $id=~tr/A-Z/a-z/;
                   1686:                 my $esc_unam=&escape($uname);
                   1687:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70      www      1688:             } else {
1.1300    raeburn  1689:                 my @currids = split(/,/,$ids{$uname});
                   1690:                 foreach my $id (@currids) {
                   1691:                     $byid{$uhom}{$id} .= $uname.',';
                   1692:                 }
                   1693:             }
                   1694:         }
                   1695:     }
                   1696:     if ($namespace eq 'clickers') {
                   1697:         foreach my $server (keys(%byid)) {
                   1698:             if (ref($byid{$server}) eq 'HASH') {
                   1699:                 foreach my $id (keys(%{$byid{$server}})) {
                   1700:                     $byid{$server} =~ s/,$//;
                   1701:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
                   1702:                 }
1.70      www      1703:             }
                   1704:         }
1.191     harris41 1705:     }
1.800     albertel 1706:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1707:         $servers{$server} =~ s/\&$//;
                   1708:         if ($namespace eq 'ids') {     
                   1709:             &critical('idput:'.$udom.':'.$servers{$server},$server);
                   1710:         } else {
                   1711:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
                   1712:         }
1.191     harris41 1713:     }
1.344     www      1714: }
                   1715: 
1.1300    raeburn  1716: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231    raeburn  1717: 
                   1718: sub iddel {
1.1300    raeburn  1719:     my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231    raeburn  1720:     my %result=();
1.1300    raeburn  1721:     my %ids=();
                   1722:     my %byid = ();
                   1723:     if (ref($idshashref) eq 'HASH') {
                   1724:         %ids=%{$idshashref};
                   1725:     } else {
1.1231    raeburn  1726:         return %result;
                   1727:     }
1.1300    raeburn  1728:     if ($namespace eq '') {
                   1729:         $namespace = 'ids';
                   1730:     }
1.1231    raeburn  1731:     my %servers=();
1.1300    raeburn  1732:     while (my ($id,$unamestr) = each(%ids)) {
                   1733:         if ($namespace eq 'ids') {
                   1734:             my $uhom = $uhome;
                   1735:             if ($uhom eq '') { 
                   1736:                 $uhom=&homeserver($unamestr,$udom);
                   1737:             }
                   1738:             if ($uhom ne 'no_host') {
                   1739:                 $servers{$uhom}.='&'.&escape($id);
                   1740:             }
                   1741:          } else {
                   1742:             my @curritems = split(/,/,$ids{$id});
                   1743:             foreach my $uname (@curritems) {
                   1744:                 my $uhom = $uhome;
                   1745:                 if ($uhom eq '') {
                   1746:                     $uhom=&homeserver($uname,$udom);
                   1747:                 }
                   1748:                 if ($uhom ne 'no_host') { 
                   1749:                     $byid{$uhom}{$id} .= $uname.',';
                   1750:                 }
                   1751:             }
1.1231    raeburn  1752:         }
1.1300    raeburn  1753:     }
                   1754:     if ($namespace eq 'clickers') {
                   1755:         foreach my $server (keys(%byid)) {
                   1756:             if (ref($byid{$server}) eq 'HASH') {
                   1757:                 foreach my $id (keys(%{$byid{$server}})) {
                   1758:                     $byid{$server}{$id} =~ s/,$//;
                   1759:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
                   1760:                 }
1.1231    raeburn  1761:             }
                   1762:         }
                   1763:     }
                   1764:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1765:         $servers{$server} =~ s/\&$//;
                   1766:         if ($namespace eq 'ids') {
                   1767:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1768:         } elsif ($namespace eq 'clickers') {
                   1769:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
                   1770:         }
1.1231    raeburn  1771:     }
                   1772:     return %result;
                   1773: }
                   1774: 
1.1300    raeburn  1775: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
                   1776: 
                   1777: sub updateclickers {
                   1778:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
                   1779:     my %clickers;
                   1780:     if (ref($idshashref) eq 'HASH') {
                   1781:         %clickers=%{$idshashref};
                   1782:     } else {
                   1783:         return;
                   1784:     }
                   1785:     my $items='';
                   1786:     foreach my $item (keys(%clickers)) {
                   1787:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
                   1788:     }
                   1789:     $items=~s/\&$//;
                   1790:     my $request = "updateclickers:$udom:$action:$items";
                   1791:     if ($critical) {
                   1792:         return &critical($request,$uhome);
                   1793:     } else {
                   1794:         return &reply($request,$uhome);
                   1795:     }
                   1796: }
                   1797: 
1.1023    raeburn  1798: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1799: sub dump_dom {
1.1165    droeschl 1800:     my ($namespace, $udom, $regexp) = @_;
                   1801: 
                   1802:     $udom ||= $env{'user.domain'};
                   1803: 
                   1804:     return () unless $udom;
                   1805: 
                   1806:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1807: }
                   1808: 
1.1023    raeburn  1809: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1810: 
                   1811: sub get_dom {
1.860     raeburn  1812:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267    raeburn  1813:     return if ($udom eq 'public');
1.806     raeburn  1814:     my $items='';
                   1815:     foreach my $item (@$storearr) {
                   1816:         $items.=&escape($item).'&';
                   1817:     }
                   1818:     $items=~s/\&$//;
1.860     raeburn  1819:     if (!$udom) {
                   1820:         $udom=$env{'user.domain'};
1.1267    raeburn  1821:         return if ($udom eq 'public');
1.860     raeburn  1822:         if (defined(&domain($udom,'primary'))) {
                   1823:             $uhome=&domain($udom,'primary');
                   1824:         } else {
1.874     albertel 1825:             undef($uhome);
1.860     raeburn  1826:         }
                   1827:     } else {
                   1828:         if (!$uhome) {
                   1829:             if (defined(&domain($udom,'primary'))) {
                   1830:                 $uhome=&domain($udom,'primary');
                   1831:             }
                   1832:         }
                   1833:     }
                   1834:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1835:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1836:         my %returnhash;
1.875     albertel 1837:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1838:             return %returnhash;
                   1839:         }
1.806     raeburn  1840:         my @pairs=split(/\&/,$rep);
                   1841:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1842:             return @pairs;
                   1843:         }
                   1844:         my $i=0;
                   1845:         foreach my $item (@$storearr) {
                   1846:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1847:             $i++;
                   1848:         }
                   1849:         return %returnhash;
                   1850:     } else {
1.880     banghart 1851:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1852:     }
                   1853: }
                   1854: 
                   1855: # -------------------------------------------- put items in domain db files 
                   1856: 
                   1857: sub put_dom {
1.860     raeburn  1858:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1859:     if (!$udom) {
                   1860:         $udom=$env{'user.domain'};
                   1861:         if (defined(&domain($udom,'primary'))) {
                   1862:             $uhome=&domain($udom,'primary');
                   1863:         } else {
1.874     albertel 1864:             undef($uhome);
1.860     raeburn  1865:         }
                   1866:     } else {
                   1867:         if (!$uhome) {
                   1868:             if (defined(&domain($udom,'primary'))) {
                   1869:                 $uhome=&domain($udom,'primary');
                   1870:             }
                   1871:         }
                   1872:     } 
                   1873:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1874:         my $items='';
                   1875:         foreach my $item (keys(%$storehash)) {
                   1876:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1877:         }
                   1878:         $items=~s/\&$//;
                   1879:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1880:     } else {
1.860     raeburn  1881:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1882:     }
                   1883: }
                   1884: 
1.1023    raeburn  1885: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1886: sub newput_dom {
1.1023    raeburn  1887:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1888:     my $result;
                   1889:     if (!$udom) {
                   1890:         $udom=$env{'user.domain'};
                   1891:     }
1.1023    raeburn  1892:     if ($udom) {
                   1893:         my $uname = &get_domainconfiguser($udom);
                   1894:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1895:     }
                   1896:     return $result;
                   1897: }
                   1898: 
1.1023    raeburn  1899: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1900: sub del_dom {
1.1023    raeburn  1901:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1902:     if (ref($storearr) eq 'ARRAY') {
                   1903:         if (!$udom) {
                   1904:             $udom=$env{'user.domain'};
                   1905:         }
1.1023    raeburn  1906:         if ($udom) {
                   1907:             my $uname = &get_domainconfiguser($udom); 
                   1908:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1909:         }
                   1910:     }
                   1911: }
                   1912: 
1.1023    raeburn  1913: # ----------------------------------construct domainconfig user for a domain 
                   1914: sub get_domainconfiguser {
                   1915:     my ($udom) = @_;
                   1916:     return $udom.'-domainconfig';
                   1917: }
                   1918: 
1.837     raeburn  1919: sub retrieve_inst_usertypes {
                   1920:     my ($udom) = @_;
                   1921:     my (%returnhash,@order);
1.989     raeburn  1922:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1923:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1924:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  1925:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1926:     } else {
                   1927:         if (defined(&domain($udom,'primary'))) {
                   1928:             my $uhome=&domain($udom,'primary');
                   1929:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1930:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  1931:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1932:                 return (\%returnhash,\@order);
                   1933:             }
                   1934:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1935:             my @pairs=split(/\&/,$hashitems);
                   1936:             foreach my $item (@pairs) {
                   1937:                 my ($key,$value)=split(/=/,$item,2);
                   1938:                 $key = &unescape($key);
                   1939:                 next if ($key =~ /^error: 2 /);
                   1940:                 $returnhash{$key}=&thaw_unescape($value);
                   1941:             }
                   1942:             my @esc_order = split(/\&/,$orderitems);
                   1943:             foreach my $item (@esc_order) {
                   1944:                 push(@order,&unescape($item));
                   1945:             }
                   1946:         } else {
1.1256    raeburn  1947:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1948:         }
1.1256    raeburn  1949:         return (\%returnhash,\@order);
1.837     raeburn  1950:     }
                   1951: }
                   1952: 
1.868     raeburn  1953: sub is_domainimage {
                   1954:     my ($url) = @_;
1.1306    raeburn  1955:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  1956:         if (&domain($1) ne '') {
                   1957:             return '1';
                   1958:         }
                   1959:     }
                   1960:     return;
                   1961: }
                   1962: 
1.899     raeburn  1963: sub inst_directory_query {
                   1964:     my ($srch) = @_;
                   1965:     my $udom = $srch->{'srchdomain'};
                   1966:     my %results;
                   1967:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1968:     my $outcome;
1.899     raeburn  1969:     if ($homeserver ne '') {
1.904     albertel 1970: 	my $queryid=&reply("querysend:instdirsearch:".
                   1971: 			   &escape($srch->{'srchby'}).':'.
                   1972: 			   &escape($srch->{'srchterm'}).':'.
                   1973: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1974: 	my $host=&hostname($homeserver);
                   1975: 	if ($queryid !~/^\Q$host\E\_/) {
                   1976: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1977: 	    return;
                   1978: 	}
                   1979: 	my $response = &get_query_reply($queryid);
                   1980: 	my $maxtries = 5;
                   1981: 	my $tries = 1;
                   1982: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1983: 	    $response = &get_query_reply($queryid);
                   1984: 	    $tries ++;
                   1985: 	}
                   1986: 
                   1987:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1988:             if ($response eq 'unavailable') {
                   1989:                 $outcome = $response;
                   1990:             } else {
                   1991:                 $outcome = 'ok';
                   1992:                 my @matches = split(/\n/,$response);
                   1993:                 foreach my $match (@matches) {
                   1994:                     my ($key,$value) = split(/=/,$match);
                   1995:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1996:                 }
1.899     raeburn  1997:             }
                   1998:         }
                   1999:     }
1.909     raeburn  2000:     return ($outcome,%results);
1.899     raeburn  2001: }
                   2002: 
                   2003: sub usersearch {
                   2004:     my ($srch) = @_;
                   2005:     my $dom = $srch->{'srchdomain'};
                   2006:     my %results;
                   2007:     my %libserv = &all_library();
                   2008:     my $query = 'usersearch';
                   2009:     foreach my $tryserver (keys(%libserv)) {
                   2010:         if (&host_domain($tryserver) eq $dom) {
                   2011:             my $host=&hostname($tryserver);
                   2012:             my $queryid=
1.911     raeburn  2013:                 &reply("querysend:".&escape($query).':'.
                   2014:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2015:                        &escape($srch->{'srchtype'}).':'.
                   2016:                        &escape($srch->{'srchterm'}),$tryserver);
                   2017:             if ($queryid !~/^\Q$host\E\_/) {
                   2018:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2019:                 next;
1.899     raeburn  2020:             }
                   2021:             my $reply = &get_query_reply($queryid);
                   2022:             my $maxtries = 1;
                   2023:             my $tries = 1;
                   2024:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2025:                 $reply = &get_query_reply($queryid);
                   2026:                 $tries ++;
                   2027:             }
                   2028:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2029:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2030:             } else {
1.911     raeburn  2031:                 my @matches;
                   2032:                 if ($reply =~ /\n/) {
                   2033:                     @matches = split(/\n/,$reply);
                   2034:                 } else {
                   2035:                     @matches = split(/\&/,$reply);
                   2036:                 }
1.899     raeburn  2037:                 foreach my $match (@matches) {
                   2038:                     my ($uname,$udom,%userhash);
1.911     raeburn  2039:                     foreach my $entry (split(/:/,$match)) {
                   2040:                         my ($key,$value) =
                   2041:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2042:                         $userhash{$key} = $value;
                   2043:                         if ($key eq 'username') {
                   2044:                             $uname = $value;
                   2045:                         } elsif ($key eq 'domain') {
                   2046:                             $udom = $value;
1.911     raeburn  2047:                         }
1.899     raeburn  2048:                     }
                   2049:                     $results{$uname.':'.$udom} = \%userhash;
                   2050:                 }
                   2051:             }
                   2052:         }
                   2053:     }
                   2054:     return %results;
                   2055: }
                   2056: 
1.912     raeburn  2057: sub get_instuser {
                   2058:     my ($udom,$uname,$id) = @_;
                   2059:     my $homeserver = &domain($udom,'primary');
                   2060:     my ($outcome,%results);
                   2061:     if ($homeserver ne '') {
                   2062:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2063:                            &escape($id).':'.&escape($udom),$homeserver);
                   2064:         my $host=&hostname($homeserver);
                   2065:         if ($queryid !~/^\Q$host\E\_/) {
                   2066:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2067:             return;
                   2068:         }
                   2069:         my $response = &get_query_reply($queryid);
                   2070:         my $maxtries = 5;
                   2071:         my $tries = 1;
                   2072:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2073:             $response = &get_query_reply($queryid);
                   2074:             $tries ++;
                   2075:         }
                   2076:         if (!&error($response) && $response ne 'refused') {
                   2077:             if ($response eq 'unavailable') {
                   2078:                 $outcome = $response;
                   2079:             } else {
                   2080:                 $outcome = 'ok';
                   2081:                 my @matches = split(/\n/,$response);
                   2082:                 foreach my $match (@matches) {
                   2083:                     my ($key,$value) = split(/=/,$match);
                   2084:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2085:                 }
                   2086:             }
                   2087:         }
                   2088:     }
                   2089:     my %userinfo;
                   2090:     if (ref($results{$uname}) eq 'HASH') {
                   2091:         %userinfo = %{$results{$uname}};
                   2092:     } 
                   2093:     return ($outcome,%userinfo);
                   2094: }
                   2095: 
1.1290    raeburn  2096: sub get_multiple_instusers {
                   2097:     my ($udom,$users,$caller) = @_;
                   2098:     my ($outcome,$results);
                   2099:     if (ref($users) eq 'HASH') {
                   2100:         my $count = keys(%{$users}); 
                   2101:         my $requested = &freeze_escape($users);
                   2102:         my $homeserver = &domain($udom,'primary');
                   2103:         if ($homeserver ne '') {
                   2104:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2105:             my $host=&hostname($homeserver);
                   2106:             if ($queryid !~/^\Q$host\E\_/) {
                   2107:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2108:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2109:                 return ($outcome,$results);
                   2110:             }
                   2111:             my $response = &get_query_reply($queryid);
                   2112:             my $maxtries = 5;
                   2113:             if ($count > 100) {
                   2114:                 $maxtries = 1+int($count/20);
                   2115:             }
                   2116:             my $tries = 1;
                   2117:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2118:                 $response = &get_query_reply($queryid);
                   2119:                 $tries ++;
                   2120:             }
                   2121:             if ($response eq '') {
                   2122:                 $results = {};
                   2123:                 foreach my $key (keys(%{$users})) {
                   2124:                     my ($uname,$id);
                   2125:                     if ($caller eq 'id') {
                   2126:                         $id = $key;
                   2127:                     } else {
                   2128:                         $uname = $key;
                   2129:                     }
                   2130:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291    raeburn  2131:                     $outcome = $resp;
1.1290    raeburn  2132:                     if ($resp eq 'ok') {
                   2133:                         %{$results} = (%{$results}, %info);
                   2134:                     } else {
                   2135:                         last;
                   2136:                     }
                   2137:                 }
                   2138:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2139:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2140:                     $outcome = $response;
                   2141:                 } else {
1.1291    raeburn  2142:                     ($outcome,my $userdata) = split(/=/,$response,2);
1.1290    raeburn  2143:                     if ($outcome eq 'ok') {
                   2144:                         $results = &thaw_unescape($userdata); 
                   2145:                     }
                   2146:                 }
                   2147:             }
                   2148:         }
                   2149:     }
                   2150:     return ($outcome,$results);
                   2151: }
                   2152: 
1.912     raeburn  2153: sub inst_rulecheck {
1.923     raeburn  2154:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2155:     my %returnhash;
                   2156:     if ($udom ne '') {
                   2157:         if (ref($rules) eq 'ARRAY') {
                   2158:             @{$rules} = map {&escape($_);} (@{$rules});
                   2159:             my $rulestr = join(':',@{$rules});
                   2160:             my $homeserver=&domain($udom,'primary');
                   2161:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2162:                 my $response;
                   2163:                 if ($item eq 'username') {                
                   2164:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2165:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2166:                                               $homeserver));
1.923     raeburn  2167:                 } elsif ($item eq 'id') {
                   2168:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2169:                                               ':'.&escape($id).':'.$rulestr,
                   2170:                                               $homeserver));
1.945     raeburn  2171:                 } elsif ($item eq 'selfcreate') {
                   2172:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2173:                                                &escape($udom).':'.&escape($uname).
                   2174:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2175:                 }
1.912     raeburn  2176:                 if ($response ne 'refused') {
                   2177:                     my @pairs=split(/\&/,$response);
                   2178:                     foreach my $item (@pairs) {
                   2179:                         my ($key,$value)=split(/=/,$item,2);
                   2180:                         $key = &unescape($key);
                   2181:                         next if ($key =~ /^error: 2 /);
                   2182:                         $returnhash{$key}=&thaw_unescape($value);
                   2183:                     }
                   2184:                 }
                   2185:             }
                   2186:         }
                   2187:     }
                   2188:     return %returnhash;
                   2189: }
                   2190: 
                   2191: sub inst_userrules {
1.923     raeburn  2192:     my ($udom,$check) = @_;
1.912     raeburn  2193:     my (%ruleshash,@ruleorder);
                   2194:     if ($udom ne '') {
                   2195:         my $homeserver=&domain($udom,'primary');
                   2196:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2197:             my $response;
                   2198:             if ($check eq 'id') {
                   2199:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2200:                                  $homeserver);
1.943     raeburn  2201:             } elsif ($check eq 'email') {
                   2202:                 $response=&reply('instemailrules:'.&escape($udom),
                   2203:                                  $homeserver);
1.923     raeburn  2204:             } else {
                   2205:                 $response=&reply('instuserrules:'.&escape($udom),
                   2206:                                  $homeserver);
                   2207:             }
1.912     raeburn  2208:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2209:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2210:                 ($response ne 'no_such_host')) {
                   2211:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2212:                 my @pairs=split(/\&/,$hashitems);
                   2213:                 foreach my $item (@pairs) {
                   2214:                     my ($key,$value)=split(/=/,$item,2);
                   2215:                     $key = &unescape($key);
                   2216:                     next if ($key =~ /^error: 2 /);
                   2217:                     $ruleshash{$key}=&thaw_unescape($value);
                   2218:                 }
                   2219:                 my @esc_order = split(/\&/,$orderitems);
                   2220:                 foreach my $item (@esc_order) {
                   2221:                     push(@ruleorder,&unescape($item));
                   2222:                 }
                   2223:             }
                   2224:         }
                   2225:     }
                   2226:     return (\%ruleshash,\@ruleorder);
                   2227: }
                   2228: 
1.976     raeburn  2229: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2230: 
                   2231: sub get_domain_defaults {
1.1240    raeburn  2232:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2233:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2234:     my $cachetime = 60*60*24;
1.1240    raeburn  2235:     unless ($ignore_cache) {
                   2236:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2237:         if (defined($cached)) {
                   2238:             if (ref($result) eq 'HASH') {
                   2239:                 return %{$result};
                   2240:             }
1.943     raeburn  2241:         }
                   2242:     }
                   2243:     my %domdefaults;
                   2244:     my %domconfig =
1.989     raeburn  2245:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2246:                                   'requestcourses','inststatus',
1.1183    raeburn  2247:                                   'coursedefaults','usersessions',
1.1258    raeburn  2248:                                   'requestauthor','selfenrollment',
1.1320    raeburn  2249:                                   'coursecategories','ssl','autoenroll',
1.1332    raeburn  2250:                                   'trust','helpsettings'],$domain);
1.1305    raeburn  2251:     my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943     raeburn  2252:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2253:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2254:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2255:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2256:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2257:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2258:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  2259:     } else {
                   2260:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2261:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2262:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2263:     }
1.976     raeburn  2264:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2265:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2266:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2267:         } else {
                   2268:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2269:         }
1.1177    raeburn  2270:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2271:         foreach my $item (@usertools) {
                   2272:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2273:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2274:             }
                   2275:         }
1.1229    raeburn  2276:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2277:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2278:         }
1.976     raeburn  2279:     }
1.985     raeburn  2280:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305    raeburn  2281:         foreach my $item ('official','unofficial','community','textbook','placement') {
1.985     raeburn  2282:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2283:         }
                   2284:     }
1.1183    raeburn  2285:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2286:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2287:     }
1.989     raeburn  2288:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2289:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2290:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2291:         }
                   2292:     }
1.1047    raeburn  2293:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2294:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2295:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2296:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2297:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2298:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2299:         }
1.1254    raeburn  2300:         foreach my $type (@coursetypes) {
                   2301:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2302:                 unless ($type eq 'community') {
                   2303:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2304:                 }
                   2305:             }
                   2306:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2307:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2308:             }
1.1277    raeburn  2309:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2310:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2311:                     $domdefaults{$type.'postsubtimeout'} = 
                   2312:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2313:                 }
                   2314:             }
1.1230    raeburn  2315:         }
1.1286    raeburn  2316:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2317:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2318:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2319:                 if (@clonecodes) {
                   2320:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2321:                 }
                   2322:             }
                   2323:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2324:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2325:         }
1.1047    raeburn  2326:     }
1.1073    raeburn  2327:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2328:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2329:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2330:         }
                   2331:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2332:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2333:         }
1.1279    raeburn  2334:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2335:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2336:         }
1.1073    raeburn  2337:     }
1.1254    raeburn  2338:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2339:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2340:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2341:                             'approval','limit');
                   2342:             foreach my $type (@coursetypes) {
                   2343:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2344:                     my @mgrdc = ();
                   2345:                     foreach my $item (@settings) {
                   2346:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2347:                             push(@mgrdc,$item);
                   2348:                         }
                   2349:                     }
                   2350:                     if (@mgrdc) {
                   2351:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2352:                     }
                   2353:                 }
                   2354:             }
                   2355:         }
                   2356:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2357:             foreach my $type (@coursetypes) {
                   2358:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2359:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2360:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2361:                     }
                   2362:                 }
                   2363:             }
                   2364:         }
                   2365:     }
1.1258    raeburn  2366:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2367:         $domdefaults{'catauth'} = 'std';
                   2368:         $domdefaults{'catunauth'} = 'std';
                   2369:         if ($domconfig{'coursecategories'}{'auth'}) { 
                   2370:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2371:         }
                   2372:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2373:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2374:         }
                   2375:     }
1.1315    raeburn  2376:     if (ref($domconfig{'ssl'}) eq 'HASH') {
                   2377:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
                   2378:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
                   2379:         }
                   2380:         if (ref($domconfig{'ssl'}{'connect'}) eq 'HASH') {
                   2381:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connect'};
                   2382:         }
                   2383:     }
1.1320    raeburn  2384:     if (ref($domconfig{'trust'}) eq 'HASH') {
                   2385:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
                   2386:         foreach my $prefix (@prefixes) {
                   2387:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
                   2388:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
                   2389:             }
                   2390:         }
                   2391:     }
1.1314    raeburn  2392:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2393:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2394:     }
1.1332    raeburn  2395:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2396:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2397:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2398:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2399:         }
                   2400:     }
1.1219    raeburn  2401:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2402:     return %domdefaults;
                   2403: }
                   2404: 
1.1311    raeburn  2405: sub course_portal_url {
                   2406:     my ($cnum,$cdom) = @_;
                   2407:     my $chome = &homeserver($cnum,$cdom);
                   2408:     my $hostname = &hostname($chome);
                   2409:     my $protocol = $protocol{$chome};
                   2410:     $protocol = 'http' if ($protocol ne 'https');
                   2411:     my %domdefaults = &get_domain_defaults($cdom);
                   2412:     my $firsturl;
                   2413:     if ($domdefaults{'portal_def'}) {
                   2414:         $firsturl = $domdefaults{'portal_def'};
                   2415:     } else {
                   2416:         $firsturl = $protocol.'://'.$hostname;
                   2417:     }
                   2418:     return $firsturl;
                   2419: }
                   2420: 
1.344     www      2421: # --------------------------------------------------- Assign a key to a student
                   2422: 
                   2423: sub assign_access_key {
1.364     www      2424: #
                   2425: # a valid key looks like uname:udom#comments
                   2426: # comments are being appended
                   2427: #
1.498     www      2428:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2429:     $kdom=
1.620     albertel 2430:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2431:     $knum=
1.620     albertel 2432:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2433:     $cdom=
1.620     albertel 2434:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2435:     $cnum=
1.620     albertel 2436:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2437:     $udom=$env{'user.name'} unless (defined($udom));
                   2438:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2439:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2440:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2441:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2442:                                                   # assigned to this person
                   2443:                                                   # - this should not happen,
1.345     www      2444:                                                   # unless something went wrong
                   2445:                                                   # the first time around
                   2446: # ready to assign
1.364     www      2447:         $logentry=$1.'; '.$logentry;
1.496     www      2448:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2449:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2450: # key now belongs to user
1.346     www      2451: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2452:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2453:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2454:                 return 'ok';
                   2455:             } else {
                   2456:                 return 
                   2457:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2458: 	    }
                   2459:         } else {
                   2460:             return 'error: Could not assign key, try again later.';
                   2461:         }
1.364     www      2462:     } elsif (!$existing{$ckey}) {
1.345     www      2463: # the key does not exist
                   2464: 	return 'error: The key does not exist';
                   2465:     } else {
                   2466: # the key is somebody else's
                   2467: 	return 'error: The key is already in use';
                   2468:     }
1.344     www      2469: }
                   2470: 
1.364     www      2471: # ------------------------------------------ put an additional comment on a key
                   2472: 
                   2473: sub comment_access_key {
                   2474: #
                   2475: # a valid key looks like uname:udom#comments
                   2476: # comments are being appended
                   2477: #
                   2478:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2479:     $cdom=
1.620     albertel 2480:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2481:     $cnum=
1.620     albertel 2482:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2483:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2484:     if ($existing{$ckey}) {
                   2485:         $existing{$ckey}.='; '.$logentry;
                   2486: # ready to assign
1.367     www      2487:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2488:                                                  $cdom,$cnum) eq 'ok') {
                   2489: 	    return 'ok';
                   2490:         } else {
                   2491: 	    return 'error: Count not store comment.';
                   2492:         }
                   2493:     } else {
                   2494: # the key does not exist
                   2495: 	return 'error: The key does not exist';
                   2496:     }
                   2497: }
                   2498: 
1.344     www      2499: # ------------------------------------------------------ Generate a set of keys
                   2500: 
                   2501: sub generate_access_keys {
1.364     www      2502:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2503:     $cdom=
1.620     albertel 2504:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2505:     $cnum=
1.620     albertel 2506:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2507:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2508:     unless (($cdom) && ($cnum)) { return 0; }
                   2509:     if ($number>10000) { return 0; }
                   2510:     sleep(2); # make sure don't get same seed twice
                   2511:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2512:     my $total=0;
                   2513:     for (my $i=1;$i<=$number;$i++) {
                   2514:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2515:                   sprintf("%lx",int(100000*rand)).'-'.
                   2516:                   sprintf("%lx",int(100000*rand));
                   2517:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2518:        $newkey=~s/0/h/g; # and also 0 and O
                   2519:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2520:        if ($existing{$newkey}) {
                   2521:            $i--;
                   2522:        } else {
1.364     www      2523: 	  if (&put('accesskeys',
                   2524:               { $newkey => '# generated '.localtime().
1.620     albertel 2525:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2526:                            '; '.$logentry },
                   2527: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2528:               $total++;
                   2529: 	  }
                   2530:        }
                   2531:     }
1.620     albertel 2532:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2533:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2534:     return $total;
                   2535: }
                   2536: 
                   2537: # ------------------------------------------------------- Validate an accesskey
                   2538: 
                   2539: sub validate_access_key {
                   2540:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2541:     $cdom=
1.620     albertel 2542:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2543:     $cnum=
1.620     albertel 2544:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2545:     $udom=$env{'user.domain'} unless (defined($udom));
                   2546:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2547:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2548:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2549: }
                   2550: 
                   2551: # ------------------------------------- Find the section of student in a course
1.652     albertel 2552: sub devalidate_getsection_cache {
                   2553:     my ($udom,$unam,$courseid)=@_;
                   2554:     my $hashid="$udom:$unam:$courseid";
                   2555:     &devalidate_cache_new('getsection',$hashid);
                   2556: }
1.298     matthew  2557: 
1.815     albertel 2558: sub courseid_to_courseurl {
                   2559:     my ($courseid) = @_;
                   2560:     #already url style courseid
                   2561:     return $courseid if ($courseid =~ m{^/});
                   2562: 
                   2563:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2564: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2565: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2566: 	return "/$cdom/$cnum";
                   2567:     }
                   2568: 
                   2569:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2570:     if (exists($courseinfo{'num'})) {
                   2571: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2572:     }
                   2573: 
                   2574:     return undef;
                   2575: }
                   2576: 
1.298     matthew  2577: sub getsection {
                   2578:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2579:     my $cachetime=1800;
1.551     albertel 2580: 
                   2581:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2582:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2583:     if (defined($cached)) { return $result; }
                   2584: 
1.298     matthew  2585:     my %Pending; 
                   2586:     my %Expired;
                   2587:     #
                   2588:     # Each role can either have not started yet (pending), be active, 
                   2589:     #    or have expired.
                   2590:     #
                   2591:     # If there is an active role, we are done.
                   2592:     #
                   2593:     # If there is more than one role which has not started yet, 
                   2594:     #     choose the one which will start sooner
                   2595:     # If there is one role which has not started yet, return it.
                   2596:     #
                   2597:     # If there is more than one expired role, choose the one which ended last.
                   2598:     # If there is a role which has expired, return it.
                   2599:     #
1.815     albertel 2600:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2601:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2602:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2603:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2604:         my $section=$1;
                   2605:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2606:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2607:         my $now=time;
1.548     albertel 2608:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2609:             $Expired{$end}=$section;
                   2610:             next;
                   2611:         }
1.548     albertel 2612:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2613:             $Pending{$start}=$section;
                   2614:             next;
                   2615:         }
1.599     albertel 2616:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2617:     }
                   2618:     #
                   2619:     # Presumedly there will be few matching roles from the above
                   2620:     # loop and the sorting time will be negligible.
                   2621:     if (scalar(keys(%Pending))) {
                   2622:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2623:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2624:     } 
                   2625:     if (scalar(keys(%Expired))) {
                   2626:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2627:         my $time = pop(@sorted);
1.599     albertel 2628:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2629:     }
1.599     albertel 2630:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2631: }
1.70      www      2632: 
1.599     albertel 2633: sub save_cache {
                   2634:     &purge_remembered();
1.722     albertel 2635:     #&Apache::loncommon::validate_page();
1.620     albertel 2636:     undef(%env);
1.780     albertel 2637:     undef($env_loaded);
1.599     albertel 2638: }
1.452     albertel 2639: 
1.599     albertel 2640: my $to_remember=-1;
                   2641: my %remembered;
                   2642: my %accessed;
                   2643: my $kicks=0;
                   2644: my $hits=0;
1.849     albertel 2645: sub make_key {
                   2646:     my ($name,$id) = @_;
1.872     albertel 2647:     if (length($id) > 65 
                   2648: 	&& length(&escape($id)) > 200) {
                   2649: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2650:     }
1.849     albertel 2651:     return &escape($name.':'.$id);
                   2652: }
                   2653: 
1.599     albertel 2654: sub devalidate_cache_new {
                   2655:     my ($name,$id,$debug) = @_;
                   2656:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319    damieng  2657:     my $remembered_id=$name.':'.$id;
1.849     albertel 2658:     $id=&make_key($name,$id);
1.599     albertel 2659:     $memcache->delete($id);
1.1319    damieng  2660:     delete($remembered{$remembered_id});
                   2661:     delete($accessed{$remembered_id});
1.599     albertel 2662: }
                   2663: 
                   2664: sub is_cached_new {
                   2665:     my ($name,$id,$debug) = @_;
1.1319    damieng  2666:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
                   2667:     if (exists($remembered{$remembered_id})) {
                   2668: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2669: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2670: 	$hits++;
1.1319    damieng  2671: 	return ($remembered{$remembered_id},1);
1.599     albertel 2672:     }
1.1319    damieng  2673:     $id=&make_key($name,$id);
1.599     albertel 2674:     my $value = $memcache->get($id);
                   2675:     if (!(defined($value))) {
                   2676: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2677: 	return (undef,undef);
1.416     albertel 2678:     }
1.599     albertel 2679:     if ($value eq '__undef__') {
                   2680: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2681: 	$value=undef;
                   2682:     }
1.1319    damieng  2683:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2684:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2685:     return ($value,1);
                   2686: }
                   2687: 
                   2688: sub do_cache_new {
                   2689:     my ($name,$id,$value,$time,$debug) = @_;
1.1319    damieng  2690:     my $remembered_id=$name.':'.$id;
1.849     albertel 2691:     $id=&make_key($name,$id);
1.599     albertel 2692:     my $setvalue=$value;
                   2693:     if (!defined($setvalue)) {
                   2694: 	$setvalue='__undef__';
                   2695:     }
1.623     albertel 2696:     if (!defined($time) ) {
                   2697: 	$time=600;
                   2698:     }
1.599     albertel 2699:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2700:     my $result = $memcache->set($id,$setvalue,$time);
                   2701:     if (! $result) {
1.872     albertel 2702: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2703: 	$memcache->disconnect_all();
1.872     albertel 2704:     }
1.600     albertel 2705:     # need to make a copy of $value
1.1319    damieng  2706:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2707:     return $value;
                   2708: }
                   2709: 
                   2710: sub make_room {
1.1319    damieng  2711:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2712: 
1.1319    damieng  2713:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2714:                                     : $value;
1.599     albertel 2715:     if ($to_remember<0) { return; }
1.1319    damieng  2716:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2717:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2718:     my $to_kick;
                   2719:     my $max_time=0;
                   2720:     foreach my $other (keys(%accessed)) {
                   2721: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2722: 	    $to_kick=$other;
                   2723: 	    $max_time=&tv_interval($accessed{$other});
                   2724: 	}
                   2725:     }
                   2726:     delete($remembered{$to_kick});
                   2727:     delete($accessed{$to_kick});
                   2728:     $kicks++;
                   2729:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2730:     return;
                   2731: }
                   2732: 
1.599     albertel 2733: sub purge_remembered {
1.604     albertel 2734:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2735:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2736:     undef(%remembered);
                   2737:     undef(%accessed);
1.428     albertel 2738: }
1.70      www      2739: # ------------------------------------- Read an entry from a user's environment
                   2740: 
                   2741: sub userenvironment {
                   2742:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2743:     my $items;
                   2744:     foreach my $item (@what) {
                   2745:         $items.=&escape($item).'&';
                   2746:     }
                   2747:     $items=~s/\&$//;
1.70      www      2748:     my %returnhash=();
1.1009    raeburn  2749:     my $uhome = &homeserver($unam,$udom);
                   2750:     unless ($uhome eq 'no_host') {
                   2751:         my @answer=split(/\&/, 
                   2752:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2753:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2754:             return %returnhash;
                   2755:         }
1.1009    raeburn  2756:         my $i;
                   2757:         for ($i=0;$i<=$#what;$i++) {
                   2758: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2759:         }
1.70      www      2760:     }
                   2761:     return %returnhash;
1.1       albertel 2762: }
                   2763: 
1.617     albertel 2764: # ---------------------------------------------------------- Get a studentphoto
                   2765: sub studentphoto {
                   2766:     my ($udom,$unam,$ext) = @_;
                   2767:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2768:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2769:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2770:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2771:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2772:             } else {
                   2773:                 my ($result,$perm_reqd)=
1.707     albertel 2774: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2775:                 if ($result eq 'ok') {
                   2776:                     if (!($perm_reqd eq 'yes')) {
                   2777:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2778:                     }
                   2779:                 }
                   2780:             }
                   2781:         }
                   2782:     } else {
                   2783:         my ($result,$perm_reqd) = 
1.707     albertel 2784: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2785:         if ($result eq 'ok') {
                   2786:             if (!($perm_reqd eq 'yes')) {
                   2787:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2788:             }
                   2789:         }
                   2790:     }
                   2791:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2792: }
                   2793: 
                   2794: sub retrievestudentphoto {
                   2795:     my ($udom,$unam,$ext,$type) = @_;
                   2796:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2797:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2798:     if ($ret eq 'ok') {
                   2799:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2800:         if ($type eq 'thumbnail') {
                   2801:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2802:         }
                   2803:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2804:         return $tokenurl;
                   2805:     } else {
                   2806:         if ($type eq 'thumbnail') {
                   2807:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2808:         } else { 
                   2809:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2810:         }
1.617     albertel 2811:     }
                   2812: }
                   2813: 
1.263     www      2814: # -------------------------------------------------------------------- New chat
                   2815: 
                   2816: sub chatsend {
1.724     raeburn  2817:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2818:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2819:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2820:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2821:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2822: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2823: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2824: }
                   2825: 
                   2826: # ------------------------------------------ Find current version of a resource
                   2827: 
                   2828: sub getversion {
                   2829:     my $fname=&clutter(shift);
1.1189    raeburn  2830:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2831:     return &currentversion(&filelocation('',$fname));
                   2832: }
                   2833: 
                   2834: sub currentversion {
                   2835:     my $fname=shift;
                   2836:     my $author=$fname;
                   2837:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2838:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2839:     my $home=&homeserver($uname,$udom);
1.292     www      2840:     if ($home eq 'no_host') { 
                   2841:         return -1; 
                   2842:     }
1.1112    www      2843:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2844:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2845: 	return -1;
                   2846:     }
1.1112    www      2847:     return $answer;
1.263     www      2848: }
                   2849: 
1.1111    www      2850: #
                   2851: # Return special version number of resource if set by override, empty otherwise
                   2852: #
                   2853: sub usedversion {
                   2854:     my $fname=shift;
                   2855:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2856:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2857:     if ($urlversion) { return $urlversion; }
                   2858:     return '';
                   2859: }
                   2860: 
1.1       albertel 2861: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2862: 
1.1       albertel 2863: sub subscribe {
                   2864:     my $fname=shift;
1.761     raeburn  2865:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2866:     $fname=~s/[\n\r]//g;
1.1       albertel 2867:     my $author=$fname;
                   2868:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2869:     my ($udom,$uname)=split(/\//,$author);
                   2870:     my $home=homeserver($uname,$udom);
1.335     albertel 2871:     if ($home eq 'no_host') {
                   2872:         return 'not_found';
1.1       albertel 2873:     }
                   2874:     my $answer=reply("sub:$fname",$home);
1.64      www      2875:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2876: 	$answer.=' by '.$home;
                   2877:     }
1.1       albertel 2878:     return $answer;
                   2879: }
                   2880:     
1.8       www      2881: # -------------------------------------------------------------- Replicate file
                   2882: 
                   2883: sub repcopy {
                   2884:     my $filename=shift;
1.23      www      2885:     $filename=~s/\/+/\//g;
1.1142    raeburn  2886:     my $londocroot = $perlvar{'lonDocRoot'};
                   2887:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2888:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2889:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2890: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2891: 	return &repcopy_userfile($filename);
                   2892:     }
1.532     albertel 2893:     $filename=~s/[\n\r]//g;
1.8       www      2894:     my $transname="$filename.in.transfer";
1.828     www      2895: # FIXME: this should flock
1.607     raeburn  2896:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2897:     my $remoteurl=subscribe($filename);
1.64      www      2898:     if ($remoteurl =~ /^con_lost by/) {
                   2899: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2900:            return 'unavailable';
1.8       www      2901:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2902: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2903: 	   return 'not_found';
1.64      www      2904:     } elsif ($remoteurl =~ /^rejected by/) {
                   2905: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2906:            return 'forbidden';
1.20      www      2907:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2908:            return 'ok';
1.8       www      2909:     } else {
1.290     www      2910:         my $author=$filename;
                   2911:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2912:         my ($udom,$uname)=split(/\//,$author);
                   2913:         my $home=homeserver($uname,$udom);
                   2914:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2915:            my @parts=split(/\//,$filename);
                   2916:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2917:            if ($path ne "$londocroot/res") {
1.8       www      2918:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2919: 	       return 'bad_request';
1.8       www      2920:            }
                   2921:            my $count;
                   2922:            for ($count=5;$count<$#parts;$count++) {
                   2923:                $path.="/$parts[$count]";
                   2924:                if ((-e $path)!=1) {
                   2925: 		   mkdir($path,0777);
                   2926:                }
                   2927:            }
                   2928:            my $ua=new LWP::UserAgent;
                   2929:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2930:            my $response=$ua->request($request,$transname);
                   2931:            if ($response->is_error()) {
                   2932: 	       unlink($transname);
                   2933:                my $message=$response->status_line;
1.672     albertel 2934:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2935:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2936:                return 'unavailable';
1.8       www      2937:            } else {
1.16      www      2938: 	       if ($remoteurl!~/\.meta$/) {
                   2939:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2940:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2941:                   if ($mresponse->is_error()) {
                   2942: 		      unlink($filename.'.meta');
                   2943:                       &logthis(
1.672     albertel 2944:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2945:                   }
                   2946: 	       }
1.8       www      2947:                rename($transname,$filename);
1.607     raeburn  2948:                return 'ok';
1.8       www      2949:            }
1.290     www      2950:        }
1.8       www      2951:     }
1.330     www      2952: }
                   2953: 
                   2954: # ------------------------------------------------ Get server side include body
                   2955: sub ssi_body {
1.381     albertel 2956:     my ($filelink,%form)=@_;
1.606     matthew  2957:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2958:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2959:     }
1.953     www      2960:     my $output='';
                   2961:     my $response;
1.980     raeburn  2962:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2963:        ($output,$response)=&externalssi($filelink);
1.953     www      2964:     } else {
1.1004    droeschl 2965:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2966:        $filelink .= 'inhibitmenu=yes';
1.953     www      2967:        ($output,$response)=&ssi($filelink,%form);
                   2968:     }
1.778     albertel 2969:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2970:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2971:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2972:     if (wantarray) {
                   2973:         return ($output, $response);
                   2974:     } else {
                   2975:         return $output;
                   2976:     }
1.8       www      2977: }
                   2978: 
1.15      www      2979: # --------------------------------------------------------- Server Side Include
                   2980: 
1.782     albertel 2981: sub absolute_url {
                   2982:     my ($host_name) = @_;
                   2983:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2984:     if ($host_name eq '') {
                   2985: 	$host_name = $ENV{'SERVER_NAME'};
                   2986:     }
                   2987:     return $protocol.$host_name;
                   2988: }
                   2989: 
1.942     foxr     2990: #
                   2991: #   Server side include.
                   2992: # Parameters:
                   2993: #  fn     Possibly encrypted resource name/id.
                   2994: #  form   Hash that describes how the rendering should be done
                   2995: #         and other things.
1.944     foxr     2996: # Returns:
1.950     raeburn  2997: #   Scalar context: The content of the response.
                   2998: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2999: #     
1.15      www      3000: sub ssi {
                   3001: 
1.944     foxr     3002:     my ($fn,%form)=@_;
1.15      www      3003:     my $ua=new LWP::UserAgent;
1.23      www      3004:     my $request;
1.711     albertel 3005: 
                   3006:     $form{'no_update_last_known'}=1;
1.895     albertel 3007:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3008:     if (%form) {
1.782     albertel 3009:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272    droeschl 3010:       $request->content(join('&',map { 
                   3011:             my $name = escape($_);
                   3012:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   3013:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   3014:             : &escape($form{$_}) );    
                   3015:         } keys(%form)));
1.23      www      3016:     } else {
1.782     albertel 3017:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3018:     }
                   3019: 
1.15      www      3020:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173    foxr     3021:     my $response= $ua->request($request);
1.1182    foxr     3022:     my $content = $response->content;
                   3023: 
                   3024: 
1.944     foxr     3025:     if (wantarray) {
1.1173    foxr     3026: 	return ($content, $response);
1.944     foxr     3027:     } else {
1.1173    foxr     3028: 	return $content;
1.942     foxr     3029:     }
1.324     www      3030: }
                   3031: 
                   3032: sub externalssi {
                   3033:     my ($url)=@_;
                   3034:     my $ua=new LWP::UserAgent;
                   3035:     my $request=new HTTP::Request('GET',$url);
                   3036:     my $response=$ua->request($request);
1.954     raeburn  3037:     if (wantarray) {
                   3038:         return ($response->content, $response);
                   3039:     } else {
                   3040:         return $response->content;
                   3041:     }
1.15      www      3042: }
1.254     www      3043: 
1.492     albertel 3044: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3045: 
                   3046: sub allowuploaded {
                   3047:     my ($srcurl,$url)=@_;
                   3048:     $url=&clutter(&declutter($url));
                   3049:     my $dir=$url;
                   3050:     $dir=~s/\/[^\/]+$//;
                   3051:     my %httpref=();
                   3052:     my $httpurl=&hreflocation('',$url);
                   3053:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3054:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3055: }
1.477     raeburn  3056: 
1.1193    raeburn  3057: #
                   3058: # Determine if the current user should be able to edit a particular resource,
                   3059: # when viewing in course context.
                   3060: # (a) When viewing resource used to determine if "Edit" item is included in 
                   3061: #     Functions.
                   3062: # (b) When displaying folder contents in course editor, used to determine if
                   3063: #     "Edit" link will be displayed alongside resource.
                   3064: #
1.1196    raeburn  3065: #  input: six args -- filename (decluttered), course number, course domain,
                   3066: #                   url, symb (if registered) and group (if this is a group
                   3067: #                   item -- e.g., bulletin board, group page etc.).
                   3068: #  output: array of five scalars -- 
1.1193    raeburn  3069: #          $cfile -- url for file editing if editable on current server
                   3070: #          $home -- homeserver of resource (i.e., for author if published,
                   3071: #                                           or course if uploaded.).
                   3072: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  3073: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   3074: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  3075: #
                   3076: 
                   3077: sub can_edit_resource {
1.1194    raeburn  3078:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3079:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3080: #
                   3081: # For aboutme pages user can only edit his/her own.
                   3082: #
1.1199    raeburn  3083:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  3084:         my ($sdom,$sname) = ($1,$2);
                   3085:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3086:             $home = $env{'user.home'};
                   3087:             $cfile = $resurl;
                   3088:             if ($env{'form.forceedit'}) {
                   3089:                 $forceview = 1;
                   3090:             } else {
                   3091:                 $forceedit = 1;
                   3092:             }
                   3093:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3094:         } else {
                   3095:             return;
                   3096:         }
                   3097:     }
                   3098: 
                   3099:     if ($env{'request.course.id'}) {
                   3100:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3101:         if ($group ne '') {
                   3102: # if this is a group homepage or group bulletin board, check group privs
                   3103:             my $allowed = 0;
1.1197    raeburn  3104:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3105:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  3106:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  3107:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3108:                     $allowed = 1;
                   3109:                 }
1.1197    raeburn  3110:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3111:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3112:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  3113:                     $allowed = 1;
                   3114:                 }
                   3115:             }
                   3116:             if ($allowed) {
                   3117:                 $home=&homeserver($cnum,$cdom);
                   3118:                 if ($env{'form.forceedit'}) {
                   3119:                     $forceview = 1;
                   3120:                 } else {
                   3121:                     $forceedit = 1;
                   3122:                 }
                   3123:                 $cfile = $resurl;
                   3124:             } else {
                   3125:                 return;
                   3126:             }
                   3127:         } else {
1.1208    raeburn  3128:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3129:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3130:                     return;
                   3131:                 }
                   3132:             } elsif (!$crsedit) {
1.1194    raeburn  3133: #
                   3134: # No edit allowed where CC has switched to student role.
                   3135: #
                   3136:                 return;
                   3137:             }
                   3138:         }
                   3139:     }
                   3140: 
1.1193    raeburn  3141:     if ($file ne '') {
                   3142:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  3143:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3144:                 $uploaded = 1;
                   3145:                 $incourse = 1;
1.1193    raeburn  3146:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3147:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  3148:                     if ($env{'form.forceedit'}) {
                   3149:                         $forceview = 1;
                   3150:                     } else {
                   3151:                         $forceedit = 1;
                   3152:                     }
1.1194    raeburn  3153:                 }
                   3154:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3155:                 $incourse = 1;
                   3156:                 if ($env{'form.forceedit'}) {
                   3157:                     $forceview = 1;
                   3158:                 } else {
                   3159:                     $forceedit = 1;
                   3160:                 }
                   3161:                 $cfile = $resurl;
                   3162:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   3163:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3164:                     $incourse = 1;
                   3165:                     if ($env{'form.forceedit'}) {
                   3166:                         $forceview = 1;
                   3167:                     } else {
                   3168:                         $forceedit = 1;
                   3169:                     }
                   3170:                     $cfile = $resurl;
1.1199    raeburn  3171:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  3172:                     $incourse = 1;
                   3173:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  3174:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  3175:                     $incourse = 1;
1.1199    raeburn  3176:                     if ($env{'form.forceedit'}) {
                   3177:                         $forceview = 1;
                   3178:                     } else {
                   3179:                         $forceedit = 1;
                   3180:                     }
                   3181:                     $cfile = $resurl;
1.1298    raeburn  3182:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) {
                   3183:                     $incourse = 1;
                   3184:                     if ($env{'form.forceedit'}) {
                   3185:                         $forceview = 1;
                   3186:                     } else {
                   3187:                         $forceedit = 1;
                   3188:                     }
                   3189:                     $cfile = $resurl;
1.1208    raeburn  3190:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3191:                     $incourse = 1;
                   3192:                     if ($env{'form.forceedit'}) {
                   3193:                         $forceview = 1;
                   3194:                     } else {
                   3195:                         $forceedit = 1;
                   3196:                     }
                   3197:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  3198:                 }
                   3199:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3200:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3201:                 if (&is_on_map($template)) { 
                   3202:                     $incourse = 1;
                   3203:                     $forceview = 1;
                   3204:                     $cfile = $template;
1.1193    raeburn  3205:                 }
1.1199    raeburn  3206:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($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.1298    raeburn  3214:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3215:                 $incourse = 1;
                   3216:                 if ($env{'form.forceedit'}) {
                   3217:                     $forceview = 1;
                   3218:                 } else {
                   3219:                     $forceedit = 1;
                   3220:                 }
                   3221:                 $cfile = $resurl;
1.1199    raeburn  3222:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3223:                 $incourse = 1;
                   3224:                 $forceview = 1;
                   3225:                 if ($symb) {
                   3226:                     my ($map,$id,$res)=&decode_symb($symb);
                   3227:                     $env{'request.symb'} = $symb;
                   3228:                     $cfile = &clutter($res);
                   3229:                 } else {
                   3230:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  3231:                     my $escfile = &unescape($cfile);
                   3232:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/exttools?$}) {
                   3233:                         $cfile = '/adm/wrapper'.$escfile;
                   3234:                     } else {
                   3235:                         $escfile =~ s{^http://}{};
                   3236:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3237:                     }
1.1199    raeburn  3238:                 }
1.1234    raeburn  3239:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3240:                 if ($env{'form.forceedit'}) {
                   3241:                     $forceview = 1;
                   3242:                 } else {
                   3243:                     $forceedit = 1;
                   3244:                 }
                   3245:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  3246:             }
                   3247:         }
1.1194    raeburn  3248:         if ($uploaded || $incourse) {
                   3249:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  3250:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  3251:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3252:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3253:             # Check that the user has permission to edit this resource
                   3254:             my $setpriv = 1;
                   3255:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3256:             if (defined($cfudom)) {
                   3257:                 $home=&homeserver($cfuname,$cfudom);
                   3258:                 $cfile=$file;
                   3259:             }
                   3260:         }
1.1194    raeburn  3261:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   3262:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  3263:             my @ids=&current_machine_ids();
                   3264:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3265:                 $switchserver=1;
                   3266:             }
                   3267:         }
                   3268:     }
1.1194    raeburn  3269:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  3270: }
                   3271: 
                   3272: sub is_course_upload {
                   3273:     my ($file,$cnum,$cdom) = @_;
                   3274:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3275:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  3276:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3277:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  3278:         return 1;
                   3279:     }
                   3280:     return;
                   3281: }
                   3282: 
1.1194    raeburn  3283: sub in_course {
1.1195    raeburn  3284:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3285:     if ($hideprivileged) {
                   3286:         my $skipuser;
1.1219    raeburn  3287:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3288:         my @possdoms = ($cdom);  
                   3289:         if ($coursehash{'checkforpriv'}) { 
                   3290:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   3291:         }
                   3292:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  3293:             $skipuser = 1;
                   3294:             if ($coursehash{'nothideprivileged'}) {
                   3295:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3296:                     my $user;
                   3297:                     if ($item =~ /:/) {
                   3298:                         $user = $item;
                   3299:                     } else {
                   3300:                         $user = join(':',split(/[\@]/,$item));
                   3301:                     }
                   3302:                     if ($user eq $uname.':'.$udom) {
                   3303:                         undef($skipuser);
                   3304:                         last;
                   3305:                     }
                   3306:                 }
                   3307:             }
                   3308:             if ($skipuser) {
                   3309:                 return 0;
                   3310:             }
                   3311:         }
                   3312:     }
1.1194    raeburn  3313:     $type ||= 'any';
                   3314:     if (!defined($cdom) || !defined($cnum)) {
                   3315:         my $cid  = $env{'request.course.id'};
                   3316:         $cdom = $env{'course.'.$cid.'.domain'};
                   3317:         $cnum = $env{'course.'.$cid.'.num'};
                   3318:     }
                   3319:     my $typesref;
1.1195    raeburn  3320:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3321:         $typesref = ['active','previous','future'];
                   3322:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3323:         $typesref = [$type];
                   3324:     }
                   3325:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3326:                               $typesref,undef,[$cdom]);
                   3327:     my ($tmp) = keys(%roles);
                   3328:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3329:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3330:     if (@course_roles > 0) {
                   3331:         return 1;
                   3332:     }
                   3333:     return 0;
                   3334: }
                   3335: 
1.478     albertel 3336: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3337: # input: action, courseID, current domain, intended
1.637     raeburn  3338: #        path to file, source of file, instruction to parse file for objects,
                   3339: #        ref to hash for embedded objects,
                   3340: #        ref to hash for codebase of java objects.
1.1095    raeburn  3341: #        reference to scalar to accommodate mime type determined
                   3342: #          from File::MMagic if $parser = parse.
1.637     raeburn  3343: #
1.485     raeburn  3344: # output: url to file (if action was uploaddoc), 
                   3345: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3346: #
1.478     albertel 3347: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3348: # course.
1.477     raeburn  3349: #
1.478     albertel 3350: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3351: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3352: #          course's home server.
1.477     raeburn  3353: #
1.478     albertel 3354: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3355: #          be copied from $source (current location) to 
                   3356: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3357: #         and will then be copied to
                   3358: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3359: #         course's home server.
1.485     raeburn  3360: #
1.481     raeburn  3361: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3362: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3363: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3364: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3365: #         in course's home server.
1.637     raeburn  3366: #
1.477     raeburn  3367: 
                   3368: sub process_coursefile {
1.1095    raeburn  3369:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3370:         $mimetype)=@_;
1.477     raeburn  3371:     my $fetchresult;
1.638     albertel 3372:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3373:     if ($action eq 'propagate') {
1.638     albertel 3374:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3375: 			     $home);
1.481     raeburn  3376:     } else {
1.477     raeburn  3377:         my $fpath = '';
                   3378:         my $fname = $file;
1.478     albertel 3379:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3380:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3381:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3382:         if ($action eq 'copy') {
                   3383:             if ($source eq '') {
                   3384:                 $fetchresult = 'no source file';
                   3385:                 return $fetchresult;
                   3386:             } else {
                   3387:                 my $destination = $filepath.'/'.$fname;
                   3388:                 rename($source,$destination);
                   3389:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3390:                                  $home);
1.481     raeburn  3391:             }
                   3392:         } elsif ($action eq 'uploaddoc') {
                   3393:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 3394:             print $fh $env{'form.'.$source};
1.481     raeburn  3395:             close($fh);
1.637     raeburn  3396:             if ($parser eq 'parse') {
1.1024    raeburn  3397:                 my $mm = new File::MMagic;
1.1095    raeburn  3398:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3399:                 if ($type eq 'text/html') {
1.1024    raeburn  3400:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3401:                     unless ($parse_result eq 'ok') {
                   3402:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3403:                     }
1.637     raeburn  3404:                 }
1.1095    raeburn  3405:                 if (ref($mimetype)) {
                   3406:                     $$mimetype = $type;
                   3407:                 } 
1.637     raeburn  3408:             }
1.477     raeburn  3409:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3410:                                  $home);
1.481     raeburn  3411:             if ($fetchresult eq 'ok') {
                   3412:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3413:             } else {
                   3414:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3415:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3416:                 return '/adm/notfound.html';
                   3417:             }
1.477     raeburn  3418:         }
                   3419:     }
1.485     raeburn  3420:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3421:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3422:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3423:     }
                   3424:     return $fetchresult;
                   3425: }
                   3426: 
1.637     raeburn  3427: sub build_filepath {
                   3428:     my ($fpath) = @_;
                   3429:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3430:     unless ($fpath eq '') {
                   3431:         my @parts=split('/',$fpath);
                   3432:         foreach my $part (@parts) {
                   3433:             $filepath.= '/'.$part;
                   3434:             if ((-e $filepath)!=1) {
                   3435:                 mkdir($filepath,0777);
                   3436:             }
                   3437:         }
                   3438:     }
                   3439:     return $filepath;
                   3440: }
                   3441: 
                   3442: sub store_edited_file {
1.638     albertel 3443:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3444:     my $file = $primary_url;
                   3445:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3446:     my $fpath = '';
                   3447:     my $fname = $file;
                   3448:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3449:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3450:     my $filepath = &build_filepath($fpath);
                   3451:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3452:     print $fh $content;
                   3453:     close($fh);
1.638     albertel 3454:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3455:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3456: 			  $home);
1.637     raeburn  3457:     if ($$fetchresult eq 'ok') {
                   3458:         return '/uploaded/'.$fpath.'/'.$fname;
                   3459:     } else {
1.638     albertel 3460:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3461: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3462:         return '/adm/notfound.html';
                   3463:     }
                   3464: }
                   3465: 
1.531     albertel 3466: sub clean_filename {
1.831     albertel 3467:     my ($fname,$args)=@_;
1.315     www      3468: # Replace Windows backslashes by forward slashes
1.257     www      3469:     $fname=~s/\\/\//g;
1.831     albertel 3470:     if (!$args->{'keep_path'}) {
                   3471:         # Get rid of everything but the actual filename
                   3472: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3473:     }
1.315     www      3474: # Replace spaces by underscores
                   3475:     $fname=~s/\s+/\_/g;
                   3476: # Replace all other weird characters by nothing
1.831     albertel 3477:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3478: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3479: # numbers
                   3480:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3481:     return $fname;
                   3482: }
1.1051    raeburn  3483: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3484: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3485: # image with the same aspect ratio as the original, but with dimensions which do 
                   3486: # not exceed $resizewidth and $resizeheight.
                   3487:  
1.984     neumanie 3488: sub resizeImage {
1.1051    raeburn  3489:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3490:     my $ima = Image::Magick->new;
                   3491:     my $resized;
                   3492:     if (-e $img_path) {
                   3493:         $ima->Read($img_path);
                   3494:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3495:             my $width = $ima->Get('width');
                   3496:             my $height = $ima->Get('height');
                   3497:             if ($width > $resizewidth) {
                   3498: 	        my $factor = $width/$resizewidth;
                   3499:                 my $newheight = $height/$factor;
                   3500:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3501:                 $resized = 1;
                   3502:             }
                   3503:         }
                   3504:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3505:             my $width = $ima->Get('width');
                   3506:             my $height = $ima->Get('height');
                   3507:             if ($height > $resizeheight) {
                   3508:                 my $factor = $height/$resizeheight;
                   3509:                 my $newwidth = $width/$factor;
                   3510:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3511:                 $resized = 1;
                   3512:             }
                   3513:         }
                   3514:         if ($resized) {
                   3515:             $ima->Write($img_path);
                   3516:         }
                   3517:     }
                   3518:     return;
1.977     amueller 3519: }
                   3520: 
1.608     albertel 3521: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3522: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3523: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3524: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3525: #                                    canceloverwrite, or ''. 
                   3526: #                   if 'coursedoc': upload to the current course
                   3527: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3528: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3529: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3530: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3531: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3532: #        $allfiles - reference to hash for embedded objects
                   3533: #        $codebase - reference to hash for codebase of java objects
                   3534: #        $desuname - username for permanent storage of uploaded file
                   3535: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3536: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3537: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3538: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3539: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3540: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3541: #                    from File::MMagic.
1.858     raeburn  3542: # 
1.686     albertel 3543: # output: url of file in userspace, or error: <message> 
                   3544: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3545: 
1.531     albertel 3546: sub userfileupload {
1.1090    raeburn  3547:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3548:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3549:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3550:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3551:     $fname=&clean_filename($fname);
1.1090    raeburn  3552:     # See if there is anything left
1.257     www      3553:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3554:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3555:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3556:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3557:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3558:         my $now = time;
1.1090    raeburn  3559:         my $filepath;
1.1095    raeburn  3560:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3561:              $filepath = 'tmp/helprequests/'.$now;
                   3562:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3563:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3564:                          '_'.$env{'user.domain'}.'/pending';
                   3565:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3566:             my ($docuname,$docudom);
                   3567:             if ($destudom) {
                   3568:                 $docudom = $destudom;
                   3569:             } else {
                   3570:                 $docudom = $env{'user.domain'};
                   3571:             }
                   3572:             if ($destuname) {
                   3573:                 $docuname = $destuname;
                   3574:             } else {
                   3575:                 $docuname = $env{'user.name'};
                   3576:             }
                   3577:             if (exists($env{'form.group'})) {
                   3578:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3579:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3580:             }
                   3581:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3582:             if ($context eq 'canceloverwrite') {
                   3583:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3584:                 if (-e  $tempfile) {
                   3585:                     my @info = stat($tempfile);
                   3586:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3587:                         unlink($tempfile);
                   3588:                     }
                   3589:                 }
                   3590:                 return;
1.523     raeburn  3591:             }
                   3592:         }
1.1090    raeburn  3593:         # Create the directory if not present
1.741     raeburn  3594:         my @parts=split(/\//,$filepath);
                   3595:         my $fullpath = $perlvar{'lonDaemons'};
                   3596:         for (my $i=0;$i<@parts;$i++) {
                   3597:             $fullpath .= '/'.$parts[$i];
                   3598:             if ((-e $fullpath)!=1) {
                   3599:                 mkdir($fullpath,0777);
                   3600:             }
                   3601:         }
                   3602:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3603:         print $fh $env{'form.'.$formname};
                   3604:         close($fh);
1.1090    raeburn  3605:         if ($context eq 'existingfile') {
                   3606:             my @info = stat($fullpath.'/'.$fname);
                   3607:             return ($fullpath.'/'.$fname,$info[9]);
                   3608:         } else {
                   3609:             return $fullpath.'/'.$fname;
                   3610:         }
1.523     raeburn  3611:     }
1.995     raeburn  3612:     if ($subdir eq 'scantron') {
                   3613:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3614:     } else {
1.995     raeburn  3615:         $fname="$subdir/$fname";
                   3616:     }
1.1090    raeburn  3617:     if ($context eq 'coursedoc') {
1.638     albertel 3618: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3619: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3620:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3621:             return &finishuserfileupload($docuname,$docudom,
                   3622: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3623: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3624:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3625:         } else {
1.1218    raeburn  3626:             if ($env{'form.folder'}) {
                   3627:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3628:             }
1.638     albertel 3629:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3630: 				       $fname,$formname,$parser,
1.1095    raeburn  3631: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3632:         }
1.719     banghart 3633:     } elsif (defined($destuname)) {
                   3634:         my $docuname=$destuname;
                   3635:         my $docudom=$destudom;
1.860     raeburn  3636: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3637: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3638:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3639:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3640:     } else {
1.638     albertel 3641:         my $docuname=$env{'user.name'};
                   3642:         my $docudom=$env{'user.domain'};
1.1220    raeburn  3643:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3644:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3645:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3646:         }
1.860     raeburn  3647: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3648: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3649:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3650:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3651:     }
1.271     www      3652: }
                   3653: 
                   3654: sub finishuserfileupload {
1.860     raeburn  3655:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3656:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3657:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3658:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3659:   
1.860     raeburn  3660:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3661:     $file=$fname;
                   3662:     if ($fname=~m|/|) {
                   3663:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3664: 	$path.=$fnamepath.'/';
                   3665:     }
1.259     www      3666:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3667:     my $count;
                   3668:     for ($count=4;$count<=$#parts;$count++) {
                   3669:         $filepath.="/$parts[$count]";
                   3670:         if ((-e $filepath)!=1) {
                   3671: 	    mkdir($filepath,0777);
                   3672:         }
                   3673:     }
1.984     neumanie 3674: 
1.258     www      3675: # Save the file
                   3676:     {
1.701     albertel 3677: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3678: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3679: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3680: 	    return '/adm/notfound.html';
                   3681: 	}
1.1090    raeburn  3682:         if ($context eq 'overwrite') {
1.1117    foxr     3683:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3684:             my $target = $filepath.'/'.$file;
                   3685:             if (-e $source) {
                   3686:                 my @info = stat($source);
                   3687:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3688:                     unless (&File::Copy::move($source,$target)) {
                   3689:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3690:                         return "Moving from $source failed";
                   3691:                     }
                   3692:                 } else {
                   3693:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3694:                 }
                   3695:             } else {
                   3696:                 return "Temporary file: $source missing";
                   3697:             }
                   3698:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3699: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3700: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3701: 	    return '/adm/notfound.html';
                   3702: 	}
1.570     albertel 3703: 	close(FH);
1.1051    raeburn  3704:         if ($resizewidth && $resizeheight) {
                   3705:             my $mm = new File::MMagic;
                   3706:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3707:             if ($mime_type =~ m{^image/}) {
                   3708: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3709:             }  
1.977     amueller 3710: 	}
1.258     www      3711:     }
1.1152    raeburn  3712:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3713:         if (ref($mimetype)) {
                   3714:             if ($$mimetype eq '') {
                   3715:                 my $mm = new File::MMagic;
                   3716:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3717:                 $$mimetype = $type;
                   3718:             }
                   3719:         }
                   3720:     }
1.637     raeburn  3721:     if ($parser eq 'parse') {
1.1152    raeburn  3722:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3723:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3724:                                                        $allfiles,$codebase);
                   3725:             unless ($parse_result eq 'ok') {
                   3726:                 &logthis('Failed to parse '.$filepath.$file.
                   3727: 	   	         ' for embedded media: '.$parse_result); 
                   3728:             }
1.637     raeburn  3729:         }
                   3730:     }
1.860     raeburn  3731:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3732:         my $input = $filepath.'/'.$file;
                   3733:         my $output = $filepath.'/'.'tn-'.$file;
                   3734:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3735:         system("convert -sample $thumbsize $input $output");
                   3736:         if (-e $filepath.'/'.'tn-'.$file) {
                   3737:             $fetchthumb  = 1; 
                   3738:         }
                   3739:     }
1.858     raeburn  3740:  
1.259     www      3741: # Notify homeserver to grep it
                   3742: #
1.984     neumanie 3743:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3744:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3745:     if ($fetchresult eq 'ok') {
1.860     raeburn  3746:         if ($fetchthumb) {
                   3747:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3748:             if ($thumbresult ne 'ok') {
                   3749:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3750:                          $docuhome.': '.$thumbresult);
                   3751:             }
                   3752:         }
1.259     www      3753: #
1.258     www      3754: # Return the URL to it
1.494     albertel 3755:         return '/uploaded/'.$path.$file;
1.263     www      3756:     } else {
1.494     albertel 3757:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3758: 		 ': '.$fetchresult);
1.263     www      3759:         return '/adm/notfound.html';
1.858     raeburn  3760:     }
1.493     albertel 3761: }
                   3762: 
1.637     raeburn  3763: sub extract_embedded_items {
1.961     raeburn  3764:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3765:     my @state = ();
1.1164    raeburn  3766:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3767:     my %javafiles = (
                   3768:                       codebase => '',
                   3769:                       code => '',
                   3770:                       archive => ''
                   3771:                     );
                   3772:     my %mediafiles = (
                   3773:                       src => '',
                   3774:                       movie => '',
                   3775:                      );
1.648     raeburn  3776:     my $p;
                   3777:     if ($content) {
                   3778:         $p = HTML::LCParser->new($content);
                   3779:     } else {
1.961     raeburn  3780:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3781:     }
1.641     albertel 3782:     while (my $t=$p->get_token()) {
1.640     albertel 3783: 	if ($t->[0] eq 'S') {
                   3784: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3785: 	    push(@state, $tagname);
1.648     raeburn  3786:             if (lc($tagname) eq 'allow') {
                   3787:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3788:             }
1.640     albertel 3789: 	    if (lc($tagname) eq 'img') {
                   3790: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3791: 	    }
1.886     albertel 3792: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  3793:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  3794:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3795:                 }
1.886     albertel 3796: 	    }
1.645     raeburn  3797:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3798:                 my $src;
1.645     raeburn  3799:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3800:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3801:                 } else {
1.1164    raeburn  3802:                     if ($attr->{'src'} ne '') {
                   3803:                         $src = $attr->{'src'};
                   3804:                         &add_filetype($allfiles,$src,'src');
                   3805:                     }
                   3806:                 }
                   3807:                 my $text = $p->get_trimmed_text();
                   3808:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3809:                     my @swfargs = split(/,/,$1);
                   3810:                     foreach my $item (@swfargs) {
                   3811:                         $item =~ s/["']//g;
                   3812:                         $item =~ s/^\s+//;
                   3813:                         $item =~ s/\s+$//;
                   3814:                     }
                   3815:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3816:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3817:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3818:                         } else {
                   3819:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3820:                         }
                   3821:                     }
1.645     raeburn  3822:                 }
                   3823:             }
                   3824:             if (lc($tagname) eq 'link') {
                   3825:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3826:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3827:                 }
                   3828:             }
1.640     albertel 3829: 	    if (lc($tagname) eq 'object' ||
                   3830: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3831: 		foreach my $item (keys(%javafiles)) {
                   3832: 		    $javafiles{$item} = '';
                   3833: 		}
1.1164    raeburn  3834:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3835:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3836:                 }
1.640     albertel 3837: 	    }
                   3838: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3839: 		my $name = lc($attr->{'name'});
                   3840: 		foreach my $item (keys(%javafiles)) {
                   3841: 		    if ($name eq $item) {
                   3842: 			$javafiles{$item} = $attr->{'value'};
                   3843: 			last;
                   3844: 		    }
                   3845: 		}
1.1164    raeburn  3846:                 my $pathfrom;
1.640     albertel 3847: 		foreach my $item (keys(%mediafiles)) {
                   3848: 		    if ($name eq $item) {
1.1164    raeburn  3849:                         $pathfrom = $attr->{'value'};
                   3850:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3851: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3852: 			last;
                   3853: 		    }
                   3854: 		}
1.1164    raeburn  3855:                 if ($name eq 'flashvars') {
                   3856:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3857:                 }
                   3858:                 if ($pathfrom ne '') {
                   3859:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3860:                                          $pathfrom);
                   3861:                 }
1.640     albertel 3862: 	    }
                   3863: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3864: 		foreach my $item (keys(%javafiles)) {
                   3865: 		    if ($attr->{$item}) {
                   3866: 			$javafiles{$item} = $attr->{$item};
                   3867: 			last;
                   3868: 		    }
                   3869: 		}
                   3870: 		foreach my $item (keys(%mediafiles)) {
                   3871: 		    if ($attr->{$item}) {
                   3872: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3873: 			last;
                   3874: 		    }
                   3875: 		}
1.1164    raeburn  3876:                 if (lc($tagname) eq 'embed') {
                   3877:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3878:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3879:                                              $attr->{'src'});
                   3880:                     }
                   3881:                 }
1.640     albertel 3882: 	    }
1.1243    raeburn  3883:             if (lc($tagname) eq 'iframe') {
                   3884:                 my $src = $attr->{'src'} ;
                   3885:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   3886:                     &add_filetype($allfiles,$src,'src');
                   3887:                 } elsif ($src =~ m{^/}) {
                   3888:                     if ($env{'request.course.id'}) {
                   3889:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3890:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3891:                         my $url = &hreflocation('',$fullpath);
                   3892:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   3893:                             my $relpath = $1;
                   3894:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   3895:                                 &add_filetype($allfiles,$1,'src');
                   3896:                             }
                   3897:                         }
                   3898:                     }
                   3899:                 }
                   3900:             }
1.1164    raeburn  3901:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  3902:                 pop(@state);
1.1164    raeburn  3903:             }
1.640     albertel 3904: 	} elsif ($t->[0] eq 'E') {
                   3905: 	    my ($tagname) = ($t->[1]);
                   3906: 	    if ($javafiles{'codebase'} ne '') {
                   3907: 		$javafiles{'codebase'} .= '/';
                   3908: 	    }  
                   3909: 	    if (lc($tagname) eq 'applet' ||
                   3910: 		lc($tagname) eq 'object' ||
                   3911: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3912: 		) {
                   3913: 		foreach my $item (keys(%javafiles)) {
                   3914: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3915: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3916: 			&add_filetype($allfiles,$file,$item);
                   3917: 		    }
                   3918: 		}
                   3919: 	    } 
                   3920: 	    pop @state;
                   3921: 	}
                   3922:     }
1.1164    raeburn  3923:     foreach my $id (sort(keys(%flashvars))) {
                   3924:         if ($shockwave{$id} ne '') {
                   3925:             my @pairs = split(/\&/,$flashvars{$id});
                   3926:             foreach my $pair (@pairs) {
                   3927:                 my ($key,$value) = split(/\=/,$pair);
                   3928:                 if ($key eq 'thumb') {
                   3929:                     &add_filetype($allfiles,$value,$key);
                   3930:                 } elsif ($key eq 'content') {
                   3931:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3932:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3933:                     if ($ext ne '') {
                   3934:                         &add_filetype($allfiles,$path.$value,$ext);
                   3935:                     }
                   3936:                 }
                   3937:             }
                   3938:         }
                   3939:     }
1.637     raeburn  3940:     return 'ok';
                   3941: }
                   3942: 
1.639     albertel 3943: sub add_filetype {
                   3944:     my ($allfiles,$file,$type)=@_;
                   3945:     if (exists($allfiles->{$file})) {
                   3946: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3947: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3948: 	}
                   3949:     } else {
                   3950: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3951:     }
                   3952: }
                   3953: 
1.1164    raeburn  3954: sub embedded_dependency {
                   3955:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3956:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3957:         if (($identifier ne '') &&
                   3958:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3959:             ($pathfrom ne '')) {
                   3960:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3961:             foreach my $dep (@{$related->{$identifier}}) {
                   3962:                 &add_filetype($allfiles,$path.$dep,'object');
                   3963:             }
                   3964:         }
                   3965:     }
                   3966:     return;
                   3967: }
                   3968: 
1.493     albertel 3969: sub removeuploadedurl {
1.984     neumanie 3970:     my ($url)=@_;	
                   3971:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3972:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3973: }
                   3974: 
                   3975: sub removeuserfile {
                   3976:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3977:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3978:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3979:     if ($result eq 'ok') {	
1.798     raeburn  3980:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3981:             my $metafile = $fname.'.meta';
                   3982:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3983: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3984:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3985:             my $sqlresult = 
1.823     albertel 3986:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3987:                                         'portfolio_metadata',$group,
                   3988:                                         'delete');
1.798     raeburn  3989:         }
                   3990:     }
                   3991:     return $result;
1.257     www      3992: }
1.15      www      3993: 
1.530     albertel 3994: sub mkdiruserfile {
                   3995:     my ($docuname,$docudom,$dir)=@_;
                   3996:     my $home=&homeserver($docuname,$docudom);
                   3997:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3998: }
                   3999: 
1.531     albertel 4000: sub renameuserfile {
                   4001:     my ($docuname,$docudom,$old,$new)=@_;
                   4002:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4003:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4004:                         &escape("$old").':'.&escape("$new"),$home);
                   4005:     if ($result eq 'ok') {
                   4006:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4007:             my $oldmeta = $old.'.meta';
                   4008:             my $newmeta = $new.'.meta';
                   4009:             my $metaresult = 
                   4010:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4011: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4012:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4013:             my $sqlresult = 
1.823     albertel 4014:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4015:                                         'portfolio_metadata',$group,
                   4016:                                         'delete');
1.798     raeburn  4017:         }
                   4018:     }
                   4019:     return $result;
1.531     albertel 4020: }
                   4021: 
1.14      www      4022: # ------------------------------------------------------------------------- Log
                   4023: 
                   4024: sub log {
                   4025:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4026:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4027: }
                   4028: 
                   4029: # ------------------------------------------------------------------ Course Log
1.352     www      4030: #
                   4031: # This routine flushes several buffers of non-mission-critical nature
                   4032: #
1.157     www      4033: 
                   4034: sub flushcourselogs {
1.352     www      4035:     &logthis('Flushing log buffers');
                   4036: #
                   4037: # course logs
                   4038: # This is a log of all transactions in a course, which can be used
                   4039: # for data mining purposes
                   4040: #
                   4041: # It also collects the courseid database, which lists last transaction
                   4042: # times and course titles for all courseids
                   4043: #
                   4044:     my %courseidbuffer=();
1.921     raeburn  4045:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4046:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4047: 		          &escape($courselogs{$crsid}),
                   4048: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4049: 	    delete $courselogs{$crsid};
                   4050:         } else {
                   4051:             &logthis('Failed to flush log buffer for '.$crsid);
                   4052:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4053:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4054:                         " exceeded maximum size, deleting.</font>");
                   4055:                delete $courselogs{$crsid};
                   4056:             }
1.352     www      4057:         }
1.920     raeburn  4058:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4059:             'description' => $coursedescrbuf{$crsid},
                   4060:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4061:             'type'        => $coursetypebuf{$crsid},
                   4062:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4063:         };
1.191     harris41 4064:     }
1.352     www      4065: #
                   4066: # Write course id database (reverse lookup) to homeserver of courses 
                   4067: # Is used in pickcourse
                   4068: #
1.840     albertel 4069:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4070:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4071:                                     $courseidbuffer{$crs_home},
                   4072:                                     $crs_home,'timeonly');
1.352     www      4073:     }
                   4074: #
                   4075: # File accesses
                   4076: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4077: #
1.449     matthew  4078:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4079:         if ($entry =~ /___count$/) {
                   4080:             my ($dom,$name);
1.807     albertel 4081:             ($dom,$name,undef)=
1.811     albertel 4082: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4083:             if (! defined($dom) || $dom eq '' || 
                   4084:                 ! defined($name) || $name eq '') {
1.620     albertel 4085:                 my $cid = $env{'request.course.id'};
                   4086:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4087:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4088:             }
1.450     matthew  4089:             my $value = $accesshash{$entry};
                   4090:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4091:             my %temphash=($url => $value);
1.449     matthew  4092:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4093:             if ($result eq 'ok') {
                   4094:                 delete $accesshash{$entry};
                   4095:             }
                   4096:         } else {
1.811     albertel 4097:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4098:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4099:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4100:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4101:                 delete $accesshash{$entry};
                   4102:             }
1.185     www      4103:         }
1.191     harris41 4104:     }
1.352     www      4105: #
                   4106: # Roles
                   4107: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4108: #
1.800     albertel 4109:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4110:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4111: 	    split(/\:/,$entry);
                   4112:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4113:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4114:                 $rudom,$runame) eq 'ok') {
                   4115: 	    delete $userrolehash{$entry};
                   4116:         }
                   4117:     }
1.662     raeburn  4118: #
1.1334  ! raeburn  4119: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4120: #
                   4121:     my %domrolebuffer = ();
1.1000    raeburn  4122:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4123:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4124:         if ($domrolebuffer{$rudom}) {
                   4125:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4126:                       '='.&escape($domainrolehash{$entry});
                   4127:         } else {
                   4128:             $domrolebuffer{$rudom}.=&escape($entry).
                   4129:                       '='.&escape($domainrolehash{$entry});
                   4130:         }
                   4131:         delete $domainrolehash{$entry};
                   4132:     }
                   4133:     foreach my $dom (keys(%domrolebuffer)) {
1.1324    raeburn  4134: 	my %servers;
                   4135: 	if (defined(&domain($dom,'primary'))) {
                   4136: 	    my $primary=&domain($dom,'primary');
                   4137: 	    my $hostname=&hostname($primary);
                   4138: 	    $servers{$primary} = $hostname;
                   4139: 	} else { 
                   4140: 	    %servers = &get_servers($dom,'library');
                   4141: 	}
1.841     albertel 4142: 	foreach my $tryserver (keys(%servers)) {
1.1324    raeburn  4143: 	    if (&reply('domroleput:'.$dom.':'.
                   4144: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4145: 		last;
                   4146: 	    } else {  
1.841     albertel 4147: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4148: 	    }
1.662     raeburn  4149:         }
                   4150:     }
1.186     www      4151:     $dumpcount++;
1.157     www      4152: }
                   4153: 
                   4154: sub courselog {
                   4155:     my $what=shift;
1.158     www      4156:     $what=time.':'.$what;
1.620     albertel 4157:     unless ($env{'request.course.id'}) { return ''; }
                   4158:     $coursedombuf{$env{'request.course.id'}}=
                   4159:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4160:     $coursenumbuf{$env{'request.course.id'}}=
                   4161:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4162:     $coursehombuf{$env{'request.course.id'}}=
                   4163:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4164:     $coursedescrbuf{$env{'request.course.id'}}=
                   4165:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4166:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4167:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4168:     $courseownerbuf{$env{'request.course.id'}}=
                   4169:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4170:     $coursetypebuf{$env{'request.course.id'}}=
                   4171:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4172:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4173: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4174:     } else {
1.620     albertel 4175: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4176:     }
1.620     albertel 4177:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4178: 	&flushcourselogs();
                   4179:     }
1.158     www      4180: }
                   4181: 
                   4182: sub courseacclog {
                   4183:     my $fnsymb=shift;
1.620     albertel 4184:     unless ($env{'request.course.id'}) { return ''; }
                   4185:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4186:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4187:         $what.=':POST';
1.583     matthew  4188:         # FIXME: Probably ought to escape things....
1.800     albertel 4189: 	foreach my $key (keys(%env)) {
                   4190:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4191:                 my $formitem = $1;
                   4192:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4193:                     $what.=':'.$formitem.'='.$env{$key};
                   4194:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4195:                     $what.=':'.$formitem.'='.$env{$key};
                   4196:                 }
1.158     www      4197:             }
1.191     harris41 4198:         }
1.583     matthew  4199:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4200:         # FIXME: We should not be depending on a form parameter that someone
                   4201:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4202:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4203:             $what.= ':POST';
                   4204:             # FIXME: Probably ought to escape things....
                   4205:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4206:                                  'crsdiscuss') {
1.620     albertel 4207:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4208:             }
                   4209:         }
1.158     www      4210:     }
                   4211:     &courselog($what);
1.149     www      4212: }
                   4213: 
1.185     www      4214: sub countacc {
                   4215:     my $url=&declutter(shift);
1.458     matthew  4216:     return if (! defined($url) || $url eq '');
1.620     albertel 4217:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4218: #
                   4219: # Mark that this url was used in this course
                   4220: #
1.620     albertel 4221:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4222: #
                   4223: # Increase the access count for this resource in this child process
                   4224: #
1.281     www      4225:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4226:     $accesshash{$key}++;
1.185     www      4227: }
1.349     www      4228: 
1.361     www      4229: sub linklog {
                   4230:     my ($from,$to)=@_;
                   4231:     $from=&declutter($from);
                   4232:     $to=&declutter($to);
                   4233:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4234:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4235: }
1.1160    www      4236: 
                   4237: sub statslog {
                   4238:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4239:     if ($users<2) { return; }
                   4240:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4241:             'course'       => $env{'request.course.id'},
                   4242:             'sections'     => '"all"',
                   4243:             'num_students' => $users,
                   4244:             'part'         => $part,
                   4245:             'symb'         => $symb,
                   4246:             'mean_tries'   => $av_attempts,
                   4247:             'deg_of_diff'  => $degdiff});
                   4248:     foreach my $key (keys(%dynstore)) {
                   4249:         $accesshash{$key}=$dynstore{$key};
                   4250:     }
                   4251: }
1.361     www      4252:   
1.349     www      4253: sub userrolelog {
                   4254:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4255:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4256:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4257:        $userrolehash
                   4258:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4259:                     =$tend.':'.$tstart;
1.662     raeburn  4260:     }
1.1169    droeschl 4261:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4262:        $userrolehash
                   4263:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4264:                     =$tend.':'.$tstart;
                   4265:     }
1.1334  ! raeburn  4266:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4267:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4268:        $domainrolehash
                   4269:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4270:                     = $tend.':'.$tstart;
                   4271:     }
1.351     www      4272: }
                   4273: 
1.957     raeburn  4274: sub courserolelog {
                   4275:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  4276:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4277:         my $cdom = $1;
                   4278:         my $cnum = $2;
                   4279:         my $sec = $3;
                   4280:         my $namespace = 'rolelog';
                   4281:         my %storehash = (
                   4282:                            role    => $trole,
                   4283:                            start   => $tstart,
                   4284:                            end     => $tend,
                   4285:                            selfenroll => $selfenroll,
                   4286:                            context    => $context,
                   4287:                         );
                   4288:         if ($trole eq 'gr') {
                   4289:             $namespace = 'groupslog';
                   4290:             $storehash{'group'} = $sec;
                   4291:         } else {
                   4292:             $storehash{'section'} = $sec;
                   4293:         }
1.1188    raeburn  4294:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4295:                    $domain,$cnum,$cdom);
1.1184    raeburn  4296:         if (($trole ne 'st') || ($sec ne '')) {
                   4297:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4298:         }
                   4299:     }
                   4300:     return;
                   4301: }
                   4302: 
1.1184    raeburn  4303: sub domainrolelog {
                   4304:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4305:     if ($area =~ m{^/($match_domain)/$}) {
                   4306:         my $cdom = $1;
                   4307:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4308:         my $namespace = 'rolelog';
                   4309:         my %storehash = (
                   4310:                            role    => $trole,
                   4311:                            start   => $tstart,
                   4312:                            end     => $tend,
                   4313:                            context => $context,
                   4314:                         );
1.1188    raeburn  4315:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4316:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  4317:     }
                   4318:     return;
                   4319: 
                   4320: }
                   4321: 
                   4322: sub coauthorrolelog {
                   4323:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4324:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4325:         my $audom = $1;
                   4326:         my $auname = $2;
                   4327:         my $namespace = 'rolelog';
                   4328:         my %storehash = (
                   4329:                            role    => $trole,
                   4330:                            start   => $tstart,
                   4331:                            end     => $tend,
                   4332:                            context => $context,
                   4333:                         );
1.1188    raeburn  4334:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4335:                    $domain,$auname,$audom);
1.1184    raeburn  4336:     }
                   4337:     return;
                   4338: }
                   4339: 
1.351     www      4340: sub get_course_adv_roles {
1.948     raeburn  4341:     my ($cid,$codes) = @_;
1.620     albertel 4342:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4343:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4344:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4345:     my %nothide=();
1.800     albertel 4346:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4347:         if ($user !~ /:/) {
                   4348: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4349:         } else {
                   4350:             $nothide{$user}=1;
                   4351:         }
1.470     www      4352:     }
1.1219    raeburn  4353:     my @possdoms = ($coursehash{'domain'});
                   4354:     if ($coursehash{'checkforpriv'}) {
                   4355:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4356:     }
1.351     www      4357:     my %returnhash=();
                   4358:     my %dumphash=
                   4359:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4360:     my $now=time;
1.997     raeburn  4361:     my %privileged;
1.1000    raeburn  4362:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4363: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4364:         if (($tstart) && ($tstart<0)) { next; }
                   4365:         if (($tend) && ($tend<$now)) { next; }
                   4366:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4367:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4368: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  4369:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4370:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4371: 	if ($role eq 'cr') { next; }
1.948     raeburn  4372:         if ($codes) {
                   4373:             if ($section) { $role .= ':'.$section; }
                   4374:             if ($returnhash{$role}) {
                   4375:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4376:             } else {
                   4377:                 $returnhash{$role}=$username.':'.$domain;
                   4378:             }
1.351     www      4379:         } else {
1.988     raeburn  4380:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4381:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4382:             if ($returnhash{$key}) {
                   4383: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4384:             } else {
                   4385:                 $returnhash{$key}=$username.':'.$domain;
                   4386:             }
1.351     www      4387:         }
1.948     raeburn  4388:     }
1.400     www      4389:     return %returnhash;
                   4390: }
                   4391: 
                   4392: sub get_my_roles {
1.937     raeburn  4393:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4394:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4395:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4396:     my (%dumphash,%nothide);
1.1086    raeburn  4397:     if ($context eq 'userroles') {
1.1166    raeburn  4398:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4399:     } else {
1.1219    raeburn  4400:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4401:         if ($hidepriv) {
                   4402:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4403:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4404:                 if ($user !~ /:/) {
                   4405:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4406:                 } else {
                   4407:                     $nothide{$user} = 1;
                   4408:                 }
                   4409:             }
                   4410:         }
1.858     raeburn  4411:     }
1.400     www      4412:     my %returnhash=();
                   4413:     my $now=time;
1.999     raeburn  4414:     my %privileged;
1.800     albertel 4415:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4416:         my ($role,$tend,$tstart);
                   4417:         if ($context eq 'userroles') {
1.1149    raeburn  4418:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4419: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4420:         } else {
                   4421:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4422:         }
1.400     www      4423:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4424:         my $status = 'active';
1.939     raeburn  4425:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4426:             $status = 'previous';
                   4427:         } 
                   4428:         if (($tstart) && ($now<$tstart)) {
                   4429:             $status = 'future';
                   4430:         }
                   4431:         if (ref($types) eq 'ARRAY') {
                   4432:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4433:                 next;
                   4434:             } 
                   4435:         } else {
                   4436:             if ($status ne 'active') {
                   4437:                 next;
                   4438:             }
                   4439:         }
1.867     raeburn  4440:         my ($rolecode,$username,$domain,$section,$area);
                   4441:         if ($context eq 'userroles') {
1.1186    raeburn  4442:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4443:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4444:         } else {
                   4445:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4446:         }
1.832     raeburn  4447:         if (ref($roledoms) eq 'ARRAY') {
                   4448:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4449:                 next;
                   4450:             }
                   4451:         }
                   4452:         if (ref($roles) eq 'ARRAY') {
                   4453:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4454:                 if ($role =~ /^cr\//) {
                   4455:                     if (!grep(/^cr$/,@{$roles})) {
                   4456:                         next;
                   4457:                     }
1.1104    raeburn  4458:                 } elsif ($role =~ /^gr\//) {
                   4459:                     if (!grep(/^gr$/,@{$roles})) {
                   4460:                         next;
                   4461:                     }
1.922     raeburn  4462:                 } else {
                   4463:                     next;
                   4464:                 }
1.832     raeburn  4465:             }
1.867     raeburn  4466:         }
1.937     raeburn  4467:         if ($hidepriv) {
1.1219    raeburn  4468:             my @privroles = ('dc','su');
1.999     raeburn  4469:             if ($context eq 'userroles') {
1.1219    raeburn  4470:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4471:             } else {
1.1219    raeburn  4472:                 my $possdoms = [$domain];
                   4473:                 if (ref($roledoms) eq 'ARRAY') {
                   4474:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  4475:                 }
1.1219    raeburn  4476:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4477:                     if (!$nothide{$username.':'.$domain}) {
                   4478:                         next;
                   4479:                     }
                   4480:                 }
1.937     raeburn  4481:             }
                   4482:         }
1.933     raeburn  4483:         if ($withsec) {
                   4484:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4485:                 $tstart.':'.$tend;
                   4486:         } else {
                   4487:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4488:         }
1.832     raeburn  4489:     }
1.373     www      4490:     return %returnhash;
1.399     www      4491: }
                   4492: 
1.1333    raeburn  4493: sub get_all_adhocroles {
                   4494:     my ($dom) = @_;
                   4495:     my @roles_by_num = ();
                   4496:     my %domdefaults = &get_domain_defaults($dom);
                   4497:     my (%description,%access_in_dom,%access_info);
                   4498:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   4499:         my $count = 0;
                   4500:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   4501:         my %ordered;
                   4502:         foreach my $role (sort(keys(%domcurrent))) {
                   4503:             my ($order,$desc,$access_in_dom);
                   4504:             if (ref($domcurrent{$role}) eq 'HASH') {
                   4505:                 $order = $domcurrent{$role}{'order'};
                   4506:                 $desc = $domcurrent{$role}{'desc'};
                   4507:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   4508:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   4509:             }
                   4510:             if ($order eq '') {
                   4511:                 $order = $count;
                   4512:             }
                   4513:             $ordered{$order} = $role;
                   4514:             if ($desc ne '') {
                   4515:                 $description{$role} = $desc;
                   4516:             } else {
                   4517:                 $description{$role}= $role;
                   4518:             }
                   4519:             $count++;
                   4520:         }
                   4521:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   4522:             push(@roles_by_num,$ordered{$item});
                   4523:         }
                   4524:     }
                   4525:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   4526: }
                   4527: 
1.1332    raeburn  4528: sub get_my_adhocroles {
1.1333    raeburn  4529:     my ($cid,$checkreg) = @_;
                   4530:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   4531:     if ($env{'request.course.id'} eq $cid) {
                   4532:         $cdom = $env{'course.'.$cid.'.domain'};
                   4533:         $cnum = $env{'course.'.$cid.'.num'};
                   4534:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   4535:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   4536:         $cdom = $1;
                   4537:         $cnum = $2;
                   4538:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   4539:                                      $cdom,$cnum);
                   4540:     }
                   4541:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   4542:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4543:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   4544:         if ($rosterhash{$user} ne '') {
                   4545:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   4546:             return ([],{}) if ($type eq 'auto');
                   4547:         }
                   4548:     }
                   4549:     if (($cdom ne '') && ($cnum ne ''))  {
1.1334  ! raeburn  4550:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332    raeburn  4551:             my $then=$env{'user.login.time'};
                   4552:             my $update=$env{'user.update.time'};
                   4553:             my $liverole = 1;
1.1334  ! raeburn  4554:             foreach my $role ('dh','da') {
        !          4555:                 if ($env{"user.role.$role./$cdom/"}) {
        !          4556:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom"});
        !          4557:                     my $limit = $update;
        !          4558:                     if ($env{'request.role'} eq "$role./$cdom/") {
        !          4559:                         $limit = $then;
        !          4560:                     }
        !          4561:                     if ($tstart && $tstart>$limit) { $liverole = 0; }
        !          4562:                     if ($tend   && $tend  <$limit) { $liverole = 0; }
        !          4563:                     last if ($liverole);
        !          4564:                 }
1.1332    raeburn  4565:             }
                   4566:             if ($liverole) {
                   4567:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333    raeburn  4568:                     my ($accessref,$accessinfo,%access_in_dom);
                   4569:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   4570:                     if (ref($roles_by_num) eq 'ARRAY') {
                   4571:                         if (@{$roles_by_num}) {
1.1332    raeburn  4572:                             my %settings;
                   4573:                             if ($env{'request.course.id'} eq $cid) {
                   4574:                                 foreach my $envkey (keys(%env)) {
                   4575:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   4576:                                         $settings{$1} = $env{$envkey};
                   4577:                                     }
                   4578:                                 }
                   4579:                             } else {
                   4580:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   4581:                             }
                   4582:                             my %setincrs;
                   4583:                             if ($settings{'internal.adhocaccess'}) {
                   4584:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   4585:                             }
                   4586:                             my @statuses;
                   4587:                             if ($env{'environment.inststatus'}) {
                   4588:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   4589:                             }
                   4590:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333    raeburn  4591:                             if (ref($accessref) eq 'HASH') {
                   4592:                                 %access_in_dom = %{$accessref};
                   4593:                             }
                   4594:                             foreach my $role (@{$roles_by_num}) {
1.1332    raeburn  4595:                                 my ($curraccess,@okstatus,@personnel);
                   4596:                                 if ($setincrs{$role}) {
                   4597:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   4598:                                     if ($curraccess eq 'status') {
                   4599:                                         @okstatus = split(/\&/,$rest);
                   4600:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4601:                                         @personnel = split(/\&/,$rest);
                   4602:                                     }
                   4603:                                 } else {
                   4604:                                     $curraccess = $access_in_dom{$role};
1.1333    raeburn  4605:                                     if (ref($accessinfo) eq 'HASH') {
                   4606:                                         if ($curraccess eq 'status') {
                   4607:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4608:                                                 @okstatus = @{$accessinfo->{$role}};
                   4609:                                             }
                   4610:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4611:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4612:                                                 @personnel = @{$accessinfo->{$role}};
                   4613:                                             }
1.1332    raeburn  4614:                                         }
                   4615:                                     }
                   4616:                                 }
                   4617:                                 if ($curraccess eq 'none') {
                   4618:                                     next;
                   4619:                                 } elsif ($curraccess eq 'all') {
                   4620:                                     push(@possroles,$role);
                   4621:                                 } elsif ($curraccess eq 'status') {
                   4622:                                     if (@okstatus) {
                   4623:                                         if (!@statuses) {
                   4624:                                             if (grep(/^default$/,@okstatus)) {
                   4625:                                                 push(@possroles,$role);
                   4626:                                             }
                   4627:                                         } else {
                   4628:                                             foreach my $status (@okstatus) {
                   4629:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   4630:                                                     push(@possroles,$role);
                   4631:                                                     last;
                   4632:                                                 }
                   4633:                                             }
                   4634:                                         }
                   4635:                                     }
                   4636:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4637:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   4638:                                         if ($curraccess eq 'exc') {
                   4639:                                             push(@possroles,$role);
                   4640:                                         }
                   4641:                                     } elsif ($curraccess eq 'inc') {
                   4642:                                         push(@possroles,$role);
                   4643:                                     }
                   4644:                                 }
                   4645:                             }
                   4646:                         }
                   4647:                     }
                   4648:                 }
                   4649:             }
                   4650:         }
                   4651:     }
1.1333    raeburn  4652:     unless (ref($description) eq 'HASH') {
                   4653:         if (ref($roles_by_num) eq 'ARRAY') {
                   4654:             my %desc;
                   4655:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   4656:             $description = \%desc;
                   4657:         } else {
                   4658:             $description = {};
                   4659:         }
                   4660:     }
                   4661:     return (\@possroles,$description);
1.1332    raeburn  4662: }
                   4663: 
1.399     www      4664: # ----------------------------------------------------- Frontpage Announcements
                   4665: #
                   4666: #
                   4667: 
                   4668: sub postannounce {
                   4669:     my ($server,$text)=@_;
1.844     albertel 4670:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4671:     unless ($text=~/\w/) { $text=''; }
                   4672:     return &reply('setannounce:'.&escape($text),$server);
                   4673: }
                   4674: 
                   4675: sub getannounce {
1.448     albertel 4676: 
                   4677:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4678: 	my $announcement='';
1.800     albertel 4679: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4680: 	close($fh);
1.399     www      4681: 	if ($announcement=~/\w/) { 
                   4682: 	    return 
                   4683:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4684:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4685: 	} else {
                   4686: 	    return '';
                   4687: 	}
                   4688:     } else {
                   4689: 	return '';
                   4690:     }
1.351     www      4691: }
1.353     www      4692: 
                   4693: # ---------------------------------------------------------- Course ID routines
                   4694: # Deal with domain's nohist_courseid.db files
                   4695: #
                   4696: 
                   4697: sub courseidput {
1.921     raeburn  4698:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4699:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4700:     my $outcome;
                   4701:     if ($caller eq 'timeonly') {
                   4702:         my $cids = '';
                   4703:         foreach my $item (keys(%$storehash)) {
                   4704:             $cids.=&escape($item).'&';
                   4705:         }
                   4706:         $cids=~s/\&$//;
                   4707:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4708:                           $coursehome);       
                   4709:     } else {
                   4710:         my $items = '';
                   4711:         foreach my $item (keys(%$storehash)) {
                   4712:             $items.= &escape($item).'='.
                   4713:                      &freeze_escape($$storehash{$item}).'&';
                   4714:         }
                   4715:         $items=~s/\&$//;
                   4716:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4717:                           $coursehome);
1.918     raeburn  4718:     }
                   4719:     if ($outcome eq 'unknown_cmd') {
                   4720:         my $what;
                   4721:         foreach my $cid (keys(%$storehash)) {
                   4722:             $what .= &escape($cid).'=';
1.921     raeburn  4723:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4724:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4725:             }
                   4726:             $what =~ s/\:$/&/;
                   4727:         }
                   4728:         $what =~ s/\&$//;  
                   4729:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4730:     } else {
                   4731:         return $outcome;
                   4732:     }
1.353     www      4733: }
                   4734: 
                   4735: sub courseiddump {
1.921     raeburn  4736:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4737:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4738:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  4739:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  4740:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  4741:     my $as_hash = 1;
                   4742:     my %returnhash;
                   4743:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4744:     my %libserv = &all_library();
                   4745:     foreach my $tryserver (keys(%libserv)) {
                   4746:         if ( (  $hostidflag == 1 
                   4747: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4748: 	     || (!defined($hostidflag)) ) {
                   4749: 
1.918     raeburn  4750: 	    if (($domfilter eq '') ||
                   4751: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 4752:                 my $rep;
                   4753:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   4754:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   4755:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   4756:                                 &escape($descfilter), &escape($instcodefilter), 
                   4757:                                 &escape($ownerfilter), &escape($coursefilter),
                   4758:                                 &escape($typefilter), &escape($regexp_ok), 
                   4759:                                 $as_hash, &escape($selfenrollonly), 
                   4760:                                 &escape($catfilter), $showhidden, $caller, 
                   4761:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   4762:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  4763:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   4764:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 4765:                 } else {
                   4766:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4767:                              $sincefilter.':'.&escape($descfilter).':'.
                   4768:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4769:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4770:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4771:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4772:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4773:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4774:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  4775:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   4776:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 4777:                 }
                   4778:                      
1.918     raeburn  4779:                 my @pairs=split(/\&/,$rep);
                   4780:                 foreach my $item (@pairs) {
                   4781:                     my ($key,$value)=split(/\=/,$item,2);
                   4782:                     $key = &unescape($key);
                   4783:                     next if ($key =~ /^error: 2 /);
                   4784:                     my $result = &thaw_unescape($value);
                   4785:                     if (ref($result) eq 'HASH') {
                   4786:                         $returnhash{$key}=$result;
                   4787:                     } else {
1.921     raeburn  4788:                         my @responses = split(/:/,$value);
                   4789:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4790:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4791:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4792:                         }
1.1008    raeburn  4793:                     }
1.353     www      4794:                 }
                   4795:             }
                   4796:         }
                   4797:     }
                   4798:     return %returnhash;
                   4799: }
                   4800: 
1.1055    raeburn  4801: sub courselastaccess {
                   4802:     my ($cdom,$cnum,$hostidref) = @_;
                   4803:     my %returnhash;
                   4804:     if ($cdom && $cnum) {
                   4805:         my $chome = &homeserver($cnum,$cdom);
                   4806:         if ($chome ne 'no_host') {
                   4807:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4808:             &extract_lastaccess(\%returnhash,$rep);
                   4809:         }
                   4810:     } else {
                   4811:         if (!$cdom) { $cdom=''; }
                   4812:         my %libserv = &all_library();
                   4813:         foreach my $tryserver (keys(%libserv)) {
                   4814:             if (ref($hostidref) eq 'ARRAY') {
                   4815:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4816:             } 
                   4817:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4818:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4819:                 &extract_lastaccess(\%returnhash,$rep);
                   4820:             }
                   4821:         }
                   4822:     }
                   4823:     return %returnhash;
                   4824: }
                   4825: 
                   4826: sub extract_lastaccess {
                   4827:     my ($returnhash,$rep) = @_;
                   4828:     if (ref($returnhash) eq 'HASH') {
                   4829:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4830:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4831:                  $rep eq '') {
                   4832:             my @pairs=split(/\&/,$rep);
                   4833:             foreach my $item (@pairs) {
                   4834:                 my ($key,$value)=split(/\=/,$item,2);
                   4835:                 $key = &unescape($key);
                   4836:                 next if ($key =~ /^error: 2 /);
                   4837:                 $returnhash->{$key} = &thaw_unescape($value);
                   4838:             }
                   4839:         }
                   4840:     }
                   4841:     return;
                   4842: }
                   4843: 
1.658     raeburn  4844: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4845: 
                   4846: sub dcmailput {
1.685     raeburn  4847:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4848:     my $status = &Apache::lonnet::critical(
1.740     www      4849:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4850:        &escape($message),$server);
1.662     raeburn  4851:     return $status;
                   4852: }
                   4853: 
1.658     raeburn  4854: sub dcmaildump {
                   4855:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4856:     my %returnhash=();
1.846     albertel 4857: 
                   4858:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4859:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4860:                                                          &escape($enddate).':';
                   4861: 	my @esc_senders=map { &escape($_)} @$senders;
                   4862: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4863: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4864:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4865:             if (($key) && ($value)) {
                   4866:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4867:             }
                   4868:         }
                   4869:     }
                   4870:     return %returnhash;
                   4871: }
1.662     raeburn  4872: # ---------------------------------------------------------- Domain roles
                   4873: 
                   4874: sub get_domain_roles {
                   4875:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4876:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4877:         $startdate = '.';
                   4878:     }
1.1018    raeburn  4879:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4880:         $enddate = '.';
                   4881:     }
1.922     raeburn  4882:     my $rolelist;
                   4883:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  4884:         $rolelist = join('&',@{$roles});
1.922     raeburn  4885:     }
1.662     raeburn  4886:     my %personnel = ();
1.841     albertel 4887: 
                   4888:     my %servers = &get_servers($dom,'library');
                   4889:     foreach my $tryserver (keys(%servers)) {
                   4890: 	%{$personnel{$tryserver}}=();
                   4891: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4892: 					    &escape($startdate).':'.
                   4893: 					    &escape($enddate).':'.
                   4894: 					    &escape($rolelist), $tryserver))) {
                   4895: 	    my ($key,$value) = split(/\=/,$line,2);
                   4896: 	    if (($key) && ($value)) {
                   4897: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4898: 	    }
                   4899: 	}
1.662     raeburn  4900:     }
                   4901:     return %personnel;
                   4902: }
1.658     raeburn  4903: 
1.1332    raeburn  4904: sub get_active_domroles {
                   4905:     my ($dom,$roles) = @_;
                   4906:     return () unless (ref($roles) eq 'ARRAY');
                   4907:     my $now = time;
                   4908:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   4909:     my %domroles;
                   4910:     foreach my $server (keys(%dompersonnel)) {
                   4911:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   4912:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   4913:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   4914:         }
                   4915:     }
                   4916:     return %domroles;
                   4917: }
                   4918: 
1.1057    www      4919: # ----------------------------------------------------------- Interval timing 
1.149     www      4920: 
1.1153    www      4921: {
                   4922: # Caches needed for speedup of navmaps
                   4923: # We don't want to cache this for very long at all (5 seconds at most)
                   4924: # 
                   4925: # The user for whom we cache
                   4926: my $cachedkey='';
                   4927: # The cached times for this user
                   4928: my %cachedtimes=();
                   4929: # When this was last done
1.1282    raeburn  4930: my $cachedtime='';
1.1153    www      4931: 
                   4932: sub load_all_first_access {
1.1308    raeburn  4933:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      4934:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  4935:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   4936:         (!$ignorecache)) {
1.1154    raeburn  4937:         return;
                   4938:     }
                   4939:     $cachedtime=time;
                   4940:     $cachedkey=$uname.':'.$udom;
                   4941:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4942: }
                   4943: 
1.504     albertel 4944: sub get_first_access {
1.1308    raeburn  4945:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 4946:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4947:     if ($argsymb) { $symb=$argsymb; }
                   4948:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4949:     if ($argmap) { $map = $argmap; }
1.926     albertel 4950:     if ($type eq 'course') {
                   4951: 	$res='course';
                   4952:     } elsif ($type eq 'map') {
1.588     albertel 4953: 	$res=&symbread($map);
                   4954:     } else {
                   4955: 	$res=$symb;
                   4956:     }
1.1308    raeburn  4957:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      4958:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4959: }
                   4960: 
                   4961: sub set_first_access {
1.1162    raeburn  4962:     my ($type,$interval)=@_;
1.790     albertel 4963:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4964:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4965:     if ($type eq 'course') {
                   4966: 	$res='course';
                   4967:     } elsif ($type eq 'map') {
1.588     albertel 4968: 	$res=&symbread($map);
                   4969:     } else {
                   4970: 	$res=$symb;
                   4971:     }
1.1153    www      4972:     $cachedkey='';
1.1162    raeburn  4973:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4974:     if (!$firstaccess) {
1.1162    raeburn  4975:         my $start = time;
                   4976: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4977:                           $udom,$uname);
                   4978:         if ($putres eq 'ok') {
                   4979:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4980:                  $udom,$uname); 
                   4981:             &appenv(
                   4982:                      {
                   4983:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4984:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4985:                      }
                   4986:                   );
                   4987:         }
                   4988:         return $putres;
1.505     albertel 4989:     }
                   4990:     return 'already_set';
1.504     albertel 4991: }
1.1153    www      4992: }
1.1282    raeburn  4993: 
1.110     www      4994: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4995: 
                   4996: sub expirespread {
                   4997:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4998:     my $cid=$env{'request.course.id'}; 
1.110     www      4999:     if ($cid) {
                   5000:        my $now=time;
                   5001:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5002:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5003:                             $env{'course.'.$cid.'.num'}.
1.110     www      5004: 	        	    ':nohist_expirationdates:'.
                   5005:                             &escape($key).'='.$now,
1.620     albertel 5006:                             $env{'course.'.$cid.'.home'})
1.110     www      5007:     }
                   5008:     return 'ok';
1.14      www      5009: }
                   5010: 
1.109     www      5011: # ----------------------------------------------------- Devalidate Spreadsheets
                   5012: 
                   5013: sub devalidate {
1.325     www      5014:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5015:     my $cid=$env{'request.course.id'}; 
1.109     www      5016:     if ($cid) {
1.391     matthew  5017:         # delete the stored spreadsheets for
                   5018:         # - the student level sheet of this user in course's homespace
                   5019:         # - the assessment level sheet for this resource 
                   5020:         #   for this user in user's homespace
1.553     albertel 5021: 	# - current conditional state info
1.325     www      5022: 	my $key=$uname.':'.$udom.':';
1.109     www      5023:         my $status=
1.299     matthew  5024: 	    &del('nohist_calculatedsheets',
1.391     matthew  5025: 		 [$key.'studentcalc:'],
1.620     albertel 5026: 		 $env{'course.'.$cid.'.domain'},
                   5027: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5028: 		.' '.
                   5029: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5030: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5031:         unless ($status eq 'ok ok') {
                   5032:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5033:                     $uname.' at '.$udom.' for '.
1.109     www      5034: 		    $symb.': '.$status);
1.133     albertel 5035:         }
1.553     albertel 5036: 	&delenv('user.state.'.$cid);
1.109     www      5037:     }
                   5038: }
                   5039: 
1.265     albertel 5040: sub get_scalar {
                   5041:     my ($string,$end) = @_;
                   5042:     my $value;
                   5043:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5044: 	$value = $1;
                   5045:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5046: 	$value = $1;
                   5047:     }
                   5048:     return &unescape($value);
                   5049: }
                   5050: 
                   5051: sub array2str {
                   5052:   my (@array) = @_;
                   5053:   my $result=&arrayref2str(\@array);
                   5054:   $result=~s/^__ARRAY_REF__//;
                   5055:   $result=~s/__END_ARRAY_REF__$//;
                   5056:   return $result;
                   5057: }
                   5058: 
1.204     albertel 5059: sub arrayref2str {
                   5060:   my ($arrayref) = @_;
1.265     albertel 5061:   my $result='__ARRAY_REF__';
1.204     albertel 5062:   foreach my $elem (@$arrayref) {
1.265     albertel 5063:     if(ref($elem) eq 'ARRAY') {
                   5064:       $result.=&arrayref2str($elem).'&';
                   5065:     } elsif(ref($elem) eq 'HASH') {
                   5066:       $result.=&hashref2str($elem).'&';
                   5067:     } elsif(ref($elem)) {
                   5068:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5069:     } else {
                   5070:       $result.=&escape($elem).'&';
                   5071:     }
                   5072:   }
                   5073:   $result=~s/\&$//;
1.265     albertel 5074:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5075:   return $result;
                   5076: }
                   5077: 
1.168     albertel 5078: sub hash2str {
1.204     albertel 5079:   my (%hash) = @_;
                   5080:   my $result=&hashref2str(\%hash);
1.265     albertel 5081:   $result=~s/^__HASH_REF__//;
                   5082:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5083:   return $result;
                   5084: }
                   5085: 
                   5086: sub hashref2str {
                   5087:   my ($hashref)=@_;
1.265     albertel 5088:   my $result='__HASH_REF__';
1.800     albertel 5089:   foreach my $key (sort(keys(%$hashref))) {
                   5090:     if (ref($key) eq 'ARRAY') {
                   5091:       $result.=&arrayref2str($key).'=';
                   5092:     } elsif (ref($key) eq 'HASH') {
                   5093:       $result.=&hashref2str($key).'=';
                   5094:     } elsif (ref($key)) {
1.265     albertel 5095:       $result.='=';
1.800     albertel 5096:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5097:     } else {
1.1132    raeburn  5098: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5099:     }
                   5100: 
1.800     albertel 5101:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5102:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5103:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5104:       $result.=&hashref2str($hashref->{$key}).'&';
                   5105:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5106:        $result.='&';
1.800     albertel 5107:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5108:     } else {
1.800     albertel 5109:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5110:     }
                   5111:   }
1.168     albertel 5112:   $result=~s/\&$//;
1.265     albertel 5113:   $result .= '__END_HASH_REF__';
1.168     albertel 5114:   return $result;
                   5115: }
                   5116: 
                   5117: sub str2hash {
1.265     albertel 5118:     my ($string)=@_;
                   5119:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5120:     return %$hash;
                   5121: }
                   5122: 
                   5123: sub str2hashref {
1.168     albertel 5124:   my ($string) = @_;
1.265     albertel 5125: 
                   5126:   my %hash;
                   5127: 
                   5128:   if($string !~ /^__HASH_REF__/) {
                   5129:       if (! ($string eq '' || !defined($string))) {
                   5130: 	  $hash{'error'}='Not hash reference';
                   5131:       }
                   5132:       return (\%hash, $string);
                   5133:   }
                   5134: 
                   5135:   $string =~ s/^__HASH_REF__//;
                   5136: 
                   5137:   while($string !~ /^__END_HASH_REF__/) {
                   5138:       #key
                   5139:       my $key='';
                   5140:       if($string =~ /^__HASH_REF__/) {
                   5141:           ($key, $string)=&str2hashref($string);
                   5142:           if(defined($key->{'error'})) {
                   5143:               $hash{'error'}='Bad data';
                   5144:               return (\%hash, $string);
                   5145:           }
                   5146:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5147:           ($key, $string)=&str2arrayref($string);
                   5148:           if($key->[0] eq 'Array reference error') {
                   5149:               $hash{'error'}='Bad data';
                   5150:               return (\%hash, $string);
                   5151:           }
                   5152:       } else {
                   5153:           $string =~ s/^(.*?)=//;
1.267     albertel 5154: 	  $key=&unescape($1);
1.265     albertel 5155:       }
                   5156:       $string =~ s/^=//;
                   5157: 
                   5158:       #value
                   5159:       my $value='';
                   5160:       if($string =~ /^__HASH_REF__/) {
                   5161:           ($value, $string)=&str2hashref($string);
                   5162:           if(defined($value->{'error'})) {
                   5163:               $hash{'error'}='Bad data';
                   5164:               return (\%hash, $string);
                   5165:           }
                   5166:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5167:           ($value, $string)=&str2arrayref($string);
                   5168:           if($value->[0] eq 'Array reference error') {
                   5169:               $hash{'error'}='Bad data';
                   5170:               return (\%hash, $string);
                   5171:           }
                   5172:       } else {
                   5173: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5174:       }
                   5175:       $string =~ s/^&//;
                   5176: 
                   5177:       $hash{$key}=$value;
1.204     albertel 5178:   }
1.265     albertel 5179: 
                   5180:   $string =~ s/^__END_HASH_REF__//;
                   5181: 
                   5182:   return (\%hash, $string);
1.204     albertel 5183: }
                   5184: 
                   5185: sub str2array {
1.265     albertel 5186:     my ($string)=@_;
                   5187:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5188:     return @$array;
                   5189: }
                   5190: 
                   5191: sub str2arrayref {
1.204     albertel 5192:   my ($string) = @_;
1.265     albertel 5193:   my @array;
                   5194: 
                   5195:   if($string !~ /^__ARRAY_REF__/) {
                   5196:       if (! ($string eq '' || !defined($string))) {
                   5197: 	  $array[0]='Array reference error';
                   5198:       }
                   5199:       return (\@array, $string);
                   5200:   }
                   5201: 
                   5202:   $string =~ s/^__ARRAY_REF__//;
                   5203: 
                   5204:   while($string !~ /^__END_ARRAY_REF__/) {
                   5205:       my $value='';
                   5206:       if($string =~ /^__HASH_REF__/) {
                   5207:           ($value, $string)=&str2hashref($string);
                   5208:           if(defined($value->{'error'})) {
                   5209:               $array[0] ='Array reference error';
                   5210:               return (\@array, $string);
                   5211:           }
                   5212:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5213:           ($value, $string)=&str2arrayref($string);
                   5214:           if($value->[0] eq 'Array reference error') {
                   5215:               $array[0] ='Array reference error';
                   5216:               return (\@array, $string);
                   5217:           }
                   5218:       } else {
                   5219: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5220:       }
                   5221:       $string =~ s/^&//;
                   5222: 
                   5223:       push(@array, $value);
1.191     harris41 5224:   }
1.265     albertel 5225: 
                   5226:   $string =~ s/^__END_ARRAY_REF__//;
                   5227: 
                   5228:   return (\@array, $string);
1.168     albertel 5229: }
                   5230: 
1.167     albertel 5231: # -------------------------------------------------------------------Temp Store
                   5232: 
1.168     albertel 5233: sub tmpreset {
                   5234:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5235:   if (!$symb) {
                   5236:     $symb=&symbread();
1.620     albertel 5237:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5238:   }
                   5239:   $symb=escape($symb);
                   5240: 
1.620     albertel 5241:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5242:   $namespace=~s/\//\_/g;
                   5243:   $namespace=~s/\W//g;
                   5244: 
1.620     albertel 5245:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5246:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5247:   if ($domain eq 'public' && $stuname eq 'public') {
                   5248:       $stuname=$ENV{'REMOTE_ADDR'};
                   5249:   }
1.1117    foxr     5250:   my $path=LONCAPA::tempdir();
1.168     albertel 5251:   my %hash;
                   5252:   if (tie(%hash,'GDBM_File',
                   5253: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5254: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5255:     foreach my $key (keys(%hash)) {
1.180     albertel 5256:       if ($key=~ /:$symb/) {
1.168     albertel 5257: 	delete($hash{$key});
                   5258:       }
                   5259:     }
                   5260:   }
                   5261: }
                   5262: 
1.167     albertel 5263: sub tmpstore {
1.168     albertel 5264:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5265: 
                   5266:   if (!$symb) {
                   5267:     $symb=&symbread();
1.620     albertel 5268:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5269:   }
                   5270:   $symb=escape($symb);
                   5271: 
                   5272:   if (!$namespace) {
                   5273:     # I don't think we would ever want to store this for a course.
                   5274:     # it seems this will only be used if we don't have a course.
1.620     albertel 5275:     #$namespace=$env{'request.course.id'};
1.168     albertel 5276:     #if (!$namespace) {
1.620     albertel 5277:       $namespace=$env{'request.state'};
1.168     albertel 5278:     #}
                   5279:   }
                   5280:   $namespace=~s/\//\_/g;
                   5281:   $namespace=~s/\W//g;
1.620     albertel 5282:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5283:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5284:   if ($domain eq 'public' && $stuname eq 'public') {
                   5285:       $stuname=$ENV{'REMOTE_ADDR'};
                   5286:   }
1.168     albertel 5287:   my $now=time;
                   5288:   my %hash;
1.1117    foxr     5289:   my $path=LONCAPA::tempdir();
1.168     albertel 5290:   if (tie(%hash,'GDBM_File',
                   5291: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5292: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5293:     $hash{"version:$symb"}++;
                   5294:     my $version=$hash{"version:$symb"};
                   5295:     my $allkeys=''; 
                   5296:     foreach my $key (keys(%$storehash)) {
                   5297:       $allkeys.=$key.':';
1.591     albertel 5298:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5299:     }
                   5300:     $hash{"$version:$symb:timestamp"}=$now;
                   5301:     $allkeys.='timestamp';
                   5302:     $hash{"$version:keys:$symb"}=$allkeys;
                   5303:     if (untie(%hash)) {
                   5304:       return 'ok';
                   5305:     } else {
                   5306:       return "error:$!";
                   5307:     }
                   5308:   } else {
                   5309:     return "error:$!";
                   5310:   }
                   5311: }
1.167     albertel 5312: 
1.168     albertel 5313: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5314: 
1.168     albertel 5315: sub tmprestore {
                   5316:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5317: 
1.168     albertel 5318:   if (!$symb) {
                   5319:     $symb=&symbread();
1.620     albertel 5320:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5321:   }
                   5322:   $symb=escape($symb);
                   5323: 
1.620     albertel 5324:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5325: 
1.620     albertel 5326:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5327:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5328:   if ($domain eq 'public' && $stuname eq 'public') {
                   5329:       $stuname=$ENV{'REMOTE_ADDR'};
                   5330:   }
1.168     albertel 5331:   my %returnhash;
                   5332:   $namespace=~s/\//\_/g;
                   5333:   $namespace=~s/\W//g;
                   5334:   my %hash;
1.1117    foxr     5335:   my $path=LONCAPA::tempdir();
1.168     albertel 5336:   if (tie(%hash,'GDBM_File',
                   5337: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5338: 	  &GDBM_READER(),0640)) {
1.168     albertel 5339:     my $version=$hash{"version:$symb"};
                   5340:     $returnhash{'version'}=$version;
                   5341:     my $scope;
                   5342:     for ($scope=1;$scope<=$version;$scope++) {
                   5343:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5344:       my @keys=split(/:/,$vkeys);
                   5345:       my $key;
                   5346:       $returnhash{"$scope:keys"}=$vkeys;
                   5347:       foreach $key (@keys) {
1.591     albertel 5348: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5349: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5350:       }
                   5351:     }
1.168     albertel 5352:     if (!(untie(%hash))) {
                   5353:       return "error:$!";
                   5354:     }
                   5355:   } else {
                   5356:     return "error:$!";
                   5357:   }
                   5358:   return %returnhash;
1.167     albertel 5359: }
                   5360: 
1.9       www      5361: # ----------------------------------------------------------------------- Store
                   5362: 
                   5363: sub store {
1.1269    raeburn  5364:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5365:     my $home='';
                   5366: 
1.168     albertel 5367:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5368: 
1.213     www      5369:     $symb=&symbclean($symb);
1.122     albertel 5370:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5371: 
1.620     albertel 5372:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5373:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5374: 
                   5375:     &devalidate($symb,$stuname,$domain);
1.109     www      5376: 
                   5377:     $symb=escape($symb);
1.187     www      5378:     if (!$namespace) { 
1.620     albertel 5379:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5380:           return ''; 
                   5381:        } 
                   5382:     }
1.620     albertel 5383:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5384: 
                   5385:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5386:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5387: 
1.12      www      5388:     my $namevalue='';
1.800     albertel 5389:     foreach my $key (keys(%$storehash)) {
                   5390:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5391:     }
1.12      www      5392:     $namevalue=~s/\&$//;
1.187     www      5393:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  5394:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5395: }
                   5396: 
1.47      www      5397: # -------------------------------------------------------------- Critical Store
                   5398: 
                   5399: sub cstore {
1.1269    raeburn  5400:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5401:     my $home='';
                   5402: 
1.168     albertel 5403:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5404: 
1.213     www      5405:     $symb=&symbclean($symb);
1.122     albertel 5406:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5407: 
1.620     albertel 5408:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5409:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5410: 
                   5411:     &devalidate($symb,$stuname,$domain);
1.109     www      5412: 
                   5413:     $symb=escape($symb);
1.187     www      5414:     if (!$namespace) { 
1.620     albertel 5415:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5416:           return ''; 
                   5417:        } 
                   5418:     }
1.620     albertel 5419:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5420: 
                   5421:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5422:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5423: 
1.47      www      5424:     my $namevalue='';
1.800     albertel 5425:     foreach my $key (keys(%$storehash)) {
                   5426:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5427:     }
1.47      www      5428:     $namevalue=~s/\&$//;
1.187     www      5429:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5430:     return critical
1.1269    raeburn  5431:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5432: }
                   5433: 
1.9       www      5434: # --------------------------------------------------------------------- Restore
                   5435: 
                   5436: sub restore {
1.124     www      5437:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5438:     my $home='';
                   5439: 
1.168     albertel 5440:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5441: 
1.122     albertel 5442:     if (!$symb) {
1.1224    raeburn  5443:         return if ($namespace eq 'courserequests');
                   5444:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5445:     } else {
1.1224    raeburn  5446:         unless ($namespace eq 'courserequests') {
                   5447:             $symb=&escape(&symbclean($symb));
                   5448:         }
1.122     albertel 5449:     }
1.188     www      5450:     if (!$namespace) { 
1.620     albertel 5451:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5452:           return ''; 
                   5453:        } 
                   5454:     }
1.620     albertel 5455:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5456:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5457:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5458:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5459: 
1.12      www      5460:     my %returnhash=();
1.800     albertel 5461:     foreach my $line (split(/\&/,$answer)) {
                   5462: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5463:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5464:     }
1.75      www      5465:     my $version;
                   5466:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5467:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5468:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5469:        }
1.75      www      5470:     }
1.13      www      5471:     return %returnhash;
1.34      www      5472: }
                   5473: 
                   5474: # ---------------------------------------------------------- Course Description
1.1118    foxr     5475: #
                   5476: #  
1.34      www      5477: 
                   5478: sub coursedescription {
1.731     albertel 5479:     my ($courseid,$args)=@_;
1.34      www      5480:     $courseid=~s/^\///;
1.49      www      5481:     $courseid=~s/\_/\//g;
1.34      www      5482:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5483:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5484:     my $normalid=$cdomain.'_'.$cnum;
                   5485:     # need to always cache even if we get errors otherwise we keep 
                   5486:     # trying and trying and trying to get the course description.
                   5487:     my %envhash=();
                   5488:     my %returnhash=();
1.731     albertel 5489:     
                   5490:     my $expiretime=600;
                   5491:     if ($env{'request.course.id'} eq $normalid) {
                   5492: 	$expiretime=120;
                   5493:     }
                   5494: 
                   5495:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5496:     if (!$args->{'freshen_cache'}
                   5497: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5498: 	foreach my $key (keys(%env)) {
                   5499: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5500: 	    my ($setting) = $1;
                   5501: 	    $returnhash{$setting} = $env{$key};
                   5502: 	}
                   5503: 	return %returnhash;
                   5504:     }
                   5505: 
1.1118    foxr     5506:     # get the data again
                   5507: 
1.731     albertel 5508:     if (!$args->{'one_time'}) {
                   5509: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5510:     }
1.811     albertel 5511: 
1.34      www      5512:     if ($chome ne 'no_host') {
1.302     albertel 5513:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5514:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5515: 	   my $username = $env{'user.name'}; # Defult username
                   5516: 	   if(defined $args->{'user'}) {
                   5517: 	       $username = $args->{'user'};
                   5518: 	   }
1.129     albertel 5519:            $returnhash{'home'}= $chome;
                   5520: 	   $returnhash{'domain'} = $cdomain;
                   5521: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5522:            if (!defined($returnhash{'type'})) {
                   5523:                $returnhash{'type'} = 'Course';
                   5524:            }
1.130     albertel 5525:            while (my ($name,$value) = each %returnhash) {
1.53      www      5526:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5527:            }
1.270     www      5528:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5529:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5530: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5531:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5532:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5533:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5534:        }
                   5535:     }
1.731     albertel 5536:     if (!$args->{'one_time'}) {
1.949     raeburn  5537: 	&appenv(\%envhash);
1.731     albertel 5538:     }
1.302     albertel 5539:     return %returnhash;
1.461     www      5540: }
                   5541: 
1.1080    raeburn  5542: sub update_released_required {
                   5543:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5544:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5545:         $cid = $env{'request.course.id'};
                   5546:         $cdom = $env{'course.'.$cid.'.domain'};
                   5547:         $cnum = $env{'course.'.$cid.'.num'};
                   5548:         $chome = $env{'course.'.$cid.'.home'};
                   5549:     }
                   5550:     if ($needsrelease) {
                   5551:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5552:         my $needsupdate;
                   5553:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5554:             $needsupdate = 1;
                   5555:         } else {
                   5556:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5557:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5558:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5559:                 $needsupdate = 1;
                   5560:             }
                   5561:         }
                   5562:         if ($needsupdate) {
                   5563:             my %needshash = (
                   5564:                              'internal.releaserequired' => $needsrelease,
                   5565:                             );
                   5566:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5567:             if ($putresult eq 'ok') {
                   5568:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5569:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5570:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5571:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5572:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5573:                 }
                   5574:             }
                   5575:         }
                   5576:     }
                   5577:     return;
                   5578: }
                   5579: 
1.461     www      5580: # -------------------------------------------------See if a user is privileged
                   5581: 
                   5582: sub privileged {
1.1219    raeburn  5583:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5584:     my $now = time;
1.1219    raeburn  5585:     my $roles;
                   5586:     if (ref($possroles) eq 'ARRAY') {
                   5587:         $roles = $possroles; 
                   5588:     } else {
                   5589:         $roles = ['dc','su'];
                   5590:     }
                   5591:     if (ref($possdomains) eq 'ARRAY') {
                   5592:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5593:         foreach my $dom (@{$possdomains}) {
                   5594:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5595:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5596:                 foreach my $role (@{$roles}) {
                   5597:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5598:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5599:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5600:                             return 1 unless (($end && $end < $now) ||
                   5601:                                              ($start && $start > $now));
                   5602:                         }
                   5603:                     }
                   5604:                 }
                   5605:             }
                   5606:         }
                   5607:     } else {
                   5608:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5609:         my $now = time;
1.1170    droeschl 5610: 
1.1275    musolffc 5611:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5612:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  5613:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 5614:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  5615:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5616:             }
1.1219    raeburn  5617:         }
                   5618:     }
                   5619:     return 0;
                   5620: }
1.1170    droeschl 5621: 
1.1219    raeburn  5622: sub privileged_by_domain {
                   5623:     my ($domains,$roles) = @_;
                   5624:     my %privileged = ();
                   5625:     my $cachetime = 60*60*24;
                   5626:     my $now = time;
                   5627:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5628:         return %privileged;
                   5629:     }
                   5630:     foreach my $dom (@{$domains}) {
                   5631:         next if (ref($privileged{$dom}) eq 'HASH');
                   5632:         my $needroles;
                   5633:         foreach my $role (@{$roles}) {
                   5634:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5635:             if (defined($cached)) {
                   5636:                 if (ref($result) eq 'HASH') {
                   5637:                     $privileged{$dom}{$role} = $result;
                   5638:                 }
                   5639:             } else {
                   5640:                 $needroles = 1;
                   5641:             }
                   5642:         }
                   5643:         if ($needroles) {
                   5644:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5645:             $privileged{$dom} = {};
                   5646:             foreach my $server (keys(%dompersonnel)) {
                   5647:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5648:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5649:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5650:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5651:                         next if ($end && $end < $now);
                   5652:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   5653:                             $dompersonnel{$server}{$item};
                   5654:                     }
                   5655:                 }
                   5656:             }
                   5657:             if (ref($privileged{$dom}) eq 'HASH') {
                   5658:                 foreach my $role (@{$roles}) {
                   5659:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5660:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5661:                     } else {
                   5662:                         my %hash = ();
                   5663:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5664:                     }
                   5665:                 }
                   5666:             }
                   5667:         }
                   5668:     }
                   5669:     return %privileged;
1.9       www      5670: }
1.1       albertel 5671: 
1.103     harris41 5672: # -------------------------------------------------------- Get user privileges
1.11      www      5673: 
                   5674: sub rolesinit {
1.1169    droeschl 5675:     my ($domain, $username) = @_;
                   5676:     my %userroles = ('user.login.time' => time);
                   5677:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5678: 
                   5679:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5680:     # also, blocking can be triggered by an activating timer
                   5681:     # it's saved in the user's %env.
                   5682:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5683:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5684:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5685:         %timerintchk, %timerintenv);
                   5686: 
1.1162    raeburn  5687:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5688:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5689:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5690:     }
1.1169    droeschl 5691: 
1.1162    raeburn  5692:     foreach my $key (keys(%timerinterval)) {
                   5693:         my ($cid,$rest) = split(/\0/,$key);
                   5694:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5695:     }
1.1169    droeschl 5696: 
1.11      www      5697:     my %allroles=();
1.1162    raeburn  5698:     my %allgroups=();
1.11      www      5699: 
1.1274    raeburn  5700:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5701:         my $role = $rolesdump{$area};
                   5702:         $area =~ s/\_\w\w$//;
                   5703: 
                   5704:         my ($trole, $tend, $tstart, $group_privs);
                   5705: 
                   5706:         if ($role =~ /^cr/) {
                   5707:         # Custom role, defined by a user 
                   5708:         # e.g., user.role.cr/msu/smith/mynewrole
                   5709:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5710:                 $trole = $1;
                   5711:                 ($tend, $tstart) = split('_', $2);
                   5712:             } else {
                   5713:                 $trole = $role;
                   5714:             }
                   5715:         } elsif ($role =~ m|^gr/|) {
                   5716:         # Role of member in a group, defined within a course/community
                   5717:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5718:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5719:             next if $tstart eq '-1';
                   5720:             ($trole, $group_privs) = split(/\//, $trole);
                   5721:             $group_privs = &unescape($group_privs);
                   5722:         } else {
                   5723:         # Just a normal role, defined in roles.tab
                   5724:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5725:         }
                   5726: 
                   5727:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5728:                  $username);
                   5729:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5730: 
                   5731:         # role expired or not available yet?
                   5732:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5733:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5734: 
                   5735:         next if $area eq '' or $trole eq '';
                   5736: 
                   5737:         my $spec = "$trole.$area";
                   5738:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5739: 
                   5740:         if ($trole =~ /^cr\//) {
                   5741:         # Custom role, defined by a user
                   5742:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5743:         } elsif ($trole eq 'gr') {
                   5744:         # Role of a member in a group, defined within a course/community
                   5745:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5746:             next;
                   5747:         } else {
                   5748:         # Normal role, defined in roles.tab
                   5749:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5750:         }
                   5751: 
                   5752:         my $cid = $tdomain.'_'.$trest;
                   5753:         unless ($firstaccchk{$cid}) {
                   5754:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5755:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5756:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5757:                         $coursetimerstarts{$cid}{$item}; 
                   5758:                 }
                   5759:             }
                   5760:             $firstaccchk{$cid} = 1;
                   5761:         }
                   5762:         unless ($timerintchk{$cid}) {
                   5763:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5764:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5765:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5766:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5767:                 }
1.12      www      5768:             }
1.1169    droeschl 5769:             $timerintchk{$cid} = 1;
1.191     harris41 5770:         }
1.11      www      5771:     }
1.1169    droeschl 5772: 
                   5773:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5774:         \%allroles, \%allgroups);
                   5775:     $env{'user.adv'} = $userroles{'user.adv'};
                   5776: 
1.1162    raeburn  5777:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5778: }
                   5779: 
1.567     raeburn  5780: sub set_arearole {
1.1215    raeburn  5781:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5782:     unless ($nolog) {
1.567     raeburn  5783: # log the associated role with the area
1.1215    raeburn  5784:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5785:     }
1.743     albertel 5786:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5787: }
                   5788: 
                   5789: sub custom_roleprivs {
                   5790:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5791:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  5792:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5793:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5794:         my ($rdummy,$roledef)=
                   5795:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5796:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5797:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5798:             if (defined($syspriv)) {
1.1043    raeburn  5799:                 if ($trest =~ /^$match_community$/) {
                   5800:                     $syspriv =~ s/bre\&S//; 
                   5801:                 }
1.567     raeburn  5802:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5803:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5804:             }
                   5805:             if ($tdomain ne '') {
                   5806:                 if (defined($dompriv)) {
                   5807:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5808:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5809:                 }
                   5810:                 if (($trest ne '') && (defined($coursepriv))) {
1.1332    raeburn  5811:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   5812:                         my $rolename = $1;
                   5813:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   5814:                     }
1.567     raeburn  5815:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5816:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5817:                 }
                   5818:             }
                   5819:         }
                   5820:     }
                   5821: }
                   5822: 
1.1332    raeburn  5823: sub course_adhocrole_privs {
                   5824:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   5825:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   5826:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   5827:         my (%currprivs,%storeprivs);
                   5828:         foreach my $item (split(/:/,$coursepriv)) {
                   5829:             my ($priv,$restrict) = split(/\&/,$item);
                   5830:             $currprivs{$priv} = $restrict;
                   5831:         }
                   5832:         my (%possadd,%possremove,%full);
                   5833:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   5834:             my ($priv,$restrict)=split(/\&/,$item);
                   5835:             $full{$priv} = $restrict;
                   5836:         }
                   5837:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   5838:              next if ($item eq '');
                   5839:              my ($rule,$rest) = split(/=/,$item);
                   5840:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   5841:              foreach my $priv (split(/:/,$rest)) {
                   5842:                  if ($priv ne '') {
                   5843:                      if ($rule eq 'off') {
                   5844:                          $possremove{$priv} = 1;
                   5845:                      } else {
                   5846:                          $possadd{$priv} = 1;
                   5847:                      }
                   5848:                  }
                   5849:              }
                   5850:          }
                   5851:          foreach my $priv (sort(keys(%full))) {
                   5852:              if (exists($currprivs{$priv})) {
                   5853:                  unless (exists($possremove{$priv})) {
                   5854:                      $storeprivs{$priv} = $currprivs{$priv};
                   5855:                  }
                   5856:              } elsif (exists($possadd{$priv})) {
                   5857:                  $storeprivs{$priv} = $full{$priv};
                   5858:              }
                   5859:          }
                   5860:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   5861:      }
                   5862:      return $coursepriv;
                   5863: }
                   5864: 
1.678     raeburn  5865: sub group_roleprivs {
                   5866:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5867:     my $access = 1;
                   5868:     my $now = time;
                   5869:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5870:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5871:     if ($access) {
1.811     albertel 5872:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5873:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5874:     }
                   5875: }
1.567     raeburn  5876: 
                   5877: sub standard_roleprivs {
                   5878:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5879:     if (defined($pr{$trole.':s'})) {
                   5880:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5881:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5882:     }
                   5883:     if ($tdomain ne '') {
                   5884:         if (defined($pr{$trole.':d'})) {
                   5885:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5886:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5887:         }
                   5888:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5889:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5890:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5891:         }
                   5892:     }
                   5893: }
                   5894: 
                   5895: sub set_userprivs {
1.1064    raeburn  5896:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5897:     my $author=0;
                   5898:     my $adv=0;
1.678     raeburn  5899:     my %grouproles = ();
                   5900:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5901:         my @groupkeys; 
1.1000    raeburn  5902:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5903:             push(@groupkeys,$role);
                   5904:         }
                   5905:         if (ref($groups_roles) eq 'HASH') {
                   5906:             foreach my $key (keys(%{$groups_roles})) {
                   5907:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5908:                     push(@groupkeys,$key);
                   5909:                 }
                   5910:             }
                   5911:         }
                   5912:         if (@groupkeys > 0) {
                   5913:             foreach my $role (@groupkeys) {
                   5914:                 my ($trole,$area,$sec,$extendedarea);
                   5915:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5916:                     $trole = $1;
                   5917:                     $area = $2;
                   5918:                     $sec = $3;
                   5919:                     $extendedarea = $area.$sec;
                   5920:                     if (exists($$allgroups{$area})) {
                   5921:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5922:                             my $spec = $trole.'.'.$extendedarea;
                   5923:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5924:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5925:                         }
1.678     raeburn  5926:                     }
                   5927:                 }
                   5928:             }
                   5929:         }
                   5930:     }
1.800     albertel 5931:     foreach my $group (keys(%grouproles)) {
                   5932:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5933:     }
1.800     albertel 5934:     foreach my $role (keys(%{$allroles})) {
                   5935:         my %thesepriv;
1.941     raeburn  5936:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5937:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5938:             if ($item ne '') {
                   5939:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5940:                 if ($restrictions eq '') {
                   5941:                     $thesepriv{$privilege}='F';
                   5942:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5943:                     $thesepriv{$privilege}.=$restrictions;
                   5944:                 }
                   5945:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5946:             }
                   5947:         }
                   5948:         my $thesestr='';
1.1104    raeburn  5949:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5950: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5951: 	}
                   5952:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5953:     }
                   5954:     return ($author,$adv);
                   5955: }
                   5956: 
1.994     raeburn  5957: sub role_status {
1.1104    raeburn  5958:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5959:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  5960:         my ($one,$two) = split(m{\./},$rolekey,2);
                   5961:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  5962:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  5963:             $$where = '/'.$two;
1.994     raeburn  5964:             $$trolecode=$$role.'.'.$$where;
                   5965:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5966:             $$tstatus='is';
1.1104    raeburn  5967:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5968:                 $$tstatus='future';
1.1034    raeburn  5969:                 if ($$tstart<$now) {
                   5970:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5971:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5972:                             my (%allroles,%allgroups,$group_privs,
                   5973:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5974:                             my %userroles = (
                   5975:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5976:                             );
1.1064    raeburn  5977:                             @rolecodes = ('cm'); 
1.1002    raeburn  5978:                             my $spec=$$role.'.'.$$where;
                   5979:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5980:                             if ($$role =~ /^cr\//) {
                   5981:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5982:                                 push(@rolecodes,'cr');
1.1002    raeburn  5983:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5984:                                 push(@rolecodes,$$role);
1.1002    raeburn  5985:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5986:                                                     $env{'user.name'});
1.1064    raeburn  5987:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5988:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5989:                                 $group_privs = &unescape($group_privs);
                   5990:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5991:                                 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  5992:                                 &get_groups_roles($tdomain,$trest,
                   5993:                                                   \%course_roles,\@rolecodes,
                   5994:                                                   \%groups_roles);
1.1002    raeburn  5995:                             } else {
1.1064    raeburn  5996:                                 push(@rolecodes,$$role);
1.1002    raeburn  5997:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5998:                             }
1.1064    raeburn  5999:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   6000:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  6001:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   6002:                         }
                   6003:                     }
1.1034    raeburn  6004:                     $$tstatus = 'is';
1.1002    raeburn  6005:                 }
1.994     raeburn  6006:             }
                   6007:             if ($$tend) {
1.1104    raeburn  6008:                 if ($$tend<$update) {
1.994     raeburn  6009:                     $$tstatus='expired';
                   6010:                 } elsif ($$tend<$now) {
                   6011:                     $$tstatus='will_not';
                   6012:                 }
                   6013:             }
                   6014:         }
                   6015:     }
                   6016: }
                   6017: 
1.1104    raeburn  6018: sub get_groups_roles {
                   6019:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6020:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6021:                   (ref($rolecodes) eq 'ARRAY') && 
                   6022:                   (ref($groups_roles) eq 'HASH')); 
                   6023:     if (keys(%{$cdom_courseroles}) > 0) {
                   6024:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6025:         if ($cdom ne '' && $cnum ne '') {
                   6026:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6027:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6028:                     my $crsrole = $1;
                   6029:                     my $crssec = $2;
                   6030:                     if ($crsrole =~ /^cr/) {
                   6031:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6032:                             push(@{$rolecodes},'cr');
                   6033:                         }
                   6034:                     } else {
                   6035:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6036:                             push(@{$rolecodes},$crsrole);
                   6037:                         }
                   6038:                     }
                   6039:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6040:                     if ($crssec ne '') {
                   6041:                         $rolekey .= "/$crssec";
                   6042:                     }
                   6043:                     $rolekey .= './';
                   6044:                     $groups_roles->{$rolekey} = $rolecodes;
                   6045:                 }
                   6046:             }
                   6047:         }
                   6048:     }
                   6049:     return;
                   6050: }
                   6051: 
                   6052: sub delete_env_groupprivs {
                   6053:     my ($where,$courseroles,$possroles) = @_;
                   6054:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6055:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6056:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6057:         %{$courseroles->{$udom}} =
                   6058:             &get_my_roles('','','userroles',['active'],
                   6059:                           $possroles,[$udom],1);
                   6060:     }
                   6061:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6062:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6063:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6064:             my $area = '/'.$cdom.'/'.$cnum;
                   6065:             my $privkey = "user.priv.$crsrole.$area";
                   6066:             if ($crssec ne '') {
                   6067:                 $privkey .= '/'.$crssec;
                   6068:             }
                   6069:             $privkey .= ".$area/$group";
                   6070:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6071:         }
                   6072:     }
                   6073:     return;
                   6074: }
                   6075: 
1.994     raeburn  6076: sub check_adhoc_privs {
1.1329    raeburn  6077:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6078:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329    raeburn  6079:     if ($sec) {
                   6080:         $cckey .= '/'.$sec;
                   6081:     } 
1.1185    raeburn  6082:     my $setprivs;
1.994     raeburn  6083:     if ($env{$cckey}) {
                   6084:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6085:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6086:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329    raeburn  6087:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6088:             $setprivs = 1;
1.994     raeburn  6089:         }
                   6090:     } else {
1.1330    raeburn  6091:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6092:         $setprivs = 1;
1.994     raeburn  6093:     }
1.1185    raeburn  6094:     return $setprivs;
1.994     raeburn  6095: }
                   6096: 
                   6097: sub set_adhoc_privileges {
1.1326    raeburn  6098: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329    raeburn  6099:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6100:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329    raeburn  6101:     if ($sec ne '') {
                   6102:         $area .= '/'.$sec;
                   6103:     }
1.994     raeburn  6104:     my $spec = $role.'.'.$area;
                   6105:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  6106:                                   $env{'user.name'},1);
1.1326    raeburn  6107:     my %rolehash = ();
1.1332    raeburn  6108:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6109:         my $rolename = $1;
1.1326    raeburn  6110:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332    raeburn  6111:         my %domdef = &get_domain_defaults($dcdom);
                   6112:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6113:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6114:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6115:             }
                   6116:         }
1.1326    raeburn  6117:     } else {
                   6118:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6119:     }
                   6120:     my ($author,$adv)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6121:     &appenv(\%userroles,[$role,'cm']);
                   6122:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  6123:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6124:         &appenv( {'request.role'        => $spec,
                   6125:                   'request.role.domain' => $dcdom,
1.1332    raeburn  6126:                   'request.course.sec'  => $sec,
1.1088    raeburn  6127:                  }
                   6128:                );
                   6129:         my $tadv=0;
                   6130:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6131:         &appenv({'request.role.adv'    => $tadv});
                   6132:     }
1.994     raeburn  6133: }
                   6134: 
1.12      www      6135: # --------------------------------------------------------------- get interface
                   6136: 
                   6137: sub get {
1.131     albertel 6138:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6139:    my $items='';
1.800     albertel 6140:    foreach my $item (@$storearr) {
                   6141:        $items.=&escape($item).'&';
1.191     harris41 6142:    }
1.12      www      6143:    $items=~s/\&$//;
1.620     albertel 6144:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6145:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6146:    my $uhome=&homeserver($uname,$udomain);
                   6147: 
1.133     albertel 6148:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6149:    my @pairs=split(/\&/,$rep);
1.273     albertel 6150:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6151:      return @pairs;
                   6152:    }
1.15      www      6153:    my %returnhash=();
1.42      www      6154:    my $i=0;
1.800     albertel 6155:    foreach my $item (@$storearr) {
                   6156:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6157:       $i++;
1.191     harris41 6158:    }
1.15      www      6159:    return %returnhash;
1.27      www      6160: }
                   6161: 
                   6162: # --------------------------------------------------------------- del interface
                   6163: 
                   6164: sub del {
1.133     albertel 6165:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6166:    my $items='';
1.800     albertel 6167:    foreach my $item (@$storearr) {
                   6168:        $items.=&escape($item).'&';
1.191     harris41 6169:    }
1.984     neumanie 6170: 
1.27      www      6171:    $items=~s/\&$//;
1.620     albertel 6172:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6173:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6174:    my $uhome=&homeserver($uname,$udomain);
                   6175:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6176: }
                   6177: 
                   6178: # -------------------------------------------------------------- dump interface
                   6179: 
1.1180    droeschl 6180: sub unserialize {
                   6181:     my ($rep, $escapedkeys) = @_;
                   6182: 
                   6183:     return {} if $rep =~ /^error/;
                   6184: 
                   6185:     my %returnhash=();
1.1252    raeburn  6186: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 6187: 	    my ($key, $value) = split(/=/, $item, 2);
                   6188: 	    $key = unescape($key) unless $escapedkeys;
                   6189: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  6190: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 6191: 	}
                   6192:     #return %returnhash;
                   6193:     return \%returnhash;
                   6194: }        
                   6195: 
                   6196: # see Lond::dump_with_regexp
                   6197: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6198: sub dump {
1.1180    droeschl 6199:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6200:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6201:     if (!$uname) { $uname=$env{'user.name'}; }
                   6202:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6203: 
1.1266    raeburn  6204:     if ($regexp) {
                   6205:         $regexp=&escape($regexp);
                   6206:     } else {
                   6207:         $regexp='.';
                   6208:     }
1.1180    droeschl 6209:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   6210:         # user is hosted on this machine
1.1266    raeburn  6211:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  6212:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 6213:         return %{unserialize($reply, $escapedkeys)};
                   6214:     }
1.1166    raeburn  6215:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6216:     my @pairs=split(/\&/,$rep);
                   6217:     my %returnhash=();
1.1098    foxr     6218:     if (!($rep =~ /^error/ )) {
                   6219: 	foreach my $item (@pairs) {
                   6220: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 6221:         $key = unescape($key) unless $escapedkeys;
                   6222:         #$key = &unescape($key);
1.1098    foxr     6223: 	    next if ($key =~ /^error: 2 /);
                   6224: 	    $returnhash{$key}=&thaw_unescape($value);
                   6225: 	}
1.755     albertel 6226:     }
                   6227:     return %returnhash;
1.407     www      6228: }
                   6229: 
1.1098    foxr     6230: 
1.717     albertel 6231: # --------------------------------------------------------- dumpstore interface
                   6232: 
                   6233: sub dumpstore {
                   6234:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 6235:    # same as dump but keys must be escaped. They may contain colon separated
                   6236:    # lists of values that may themself contain colons (e.g. symbs).
                   6237:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6238: }
                   6239: 
1.407     www      6240: # -------------------------------------------------------------- keys interface
                   6241: 
                   6242: sub getkeys {
                   6243:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6244:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6245:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6246:    my $uhome=&homeserver($uname,$udomain);
                   6247:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6248:    my @keyarray=();
1.800     albertel 6249:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6250:       next if ($key =~ /^error: 2 /);
1.800     albertel 6251:       push(@keyarray,&unescape($key));
1.407     www      6252:    }
                   6253:    return @keyarray;
1.318     matthew  6254: }
                   6255: 
1.319     matthew  6256: # --------------------------------------------------------------- currentdump
                   6257: sub currentdump {
1.328     matthew  6258:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6259:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6260:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6261:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6262:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 6263:    my $rep;
                   6264: 
                   6265:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6266:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   6267:                    $courseid)));
                   6268:    } else {
                   6269:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6270:    }
                   6271: 
1.318     matthew  6272:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6273:    #
1.318     matthew  6274:    my %returnhash=();
1.319     matthew  6275:    #
                   6276:    if ($rep eq "unknown_cmd") { 
                   6277:        # an old lond will not know currentdump
                   6278:        # Do a dump and make it look like a currentdump
1.822     albertel 6279:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6280:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6281:        my %hash = @tmp;
                   6282:        @tmp=();
1.424     matthew  6283:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6284:    } else {
                   6285:        my @pairs=split(/\&/,$rep);
1.800     albertel 6286:        foreach my $pair (@pairs) {
                   6287:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6288:            my ($symb,$param) = split(/:/,$key);
                   6289:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6290:                                                         &thaw_unescape($value);
1.319     matthew  6291:        }
1.191     harris41 6292:    }
1.12      www      6293:    return %returnhash;
1.424     matthew  6294: }
                   6295: 
                   6296: sub convert_dump_to_currentdump{
                   6297:     my %hash = %{shift()};
                   6298:     my %returnhash;
                   6299:     # Code ripped from lond, essentially.  The only difference
                   6300:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6301:     # we might run in to problems with parameter names =~ /^v\./
                   6302:     while (my ($key,$value) = each(%hash)) {
                   6303:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6304: 	$symb  = &unescape($symb);
                   6305: 	$param = &unescape($param);
1.424     matthew  6306:         next if ($v eq 'version' || $symb eq 'keys');
                   6307:         next if (exists($returnhash{$symb}) &&
                   6308:                  exists($returnhash{$symb}->{$param}) &&
                   6309:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6310:         $returnhash{$symb}->{$param}=$value;
                   6311:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6312:     }
                   6313:     #
                   6314:     # Remove all of the keys in the hashes which keep track of
                   6315:     # the version of the parameter.
                   6316:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6317:         # use a foreach because we are going to delete from the hash.
                   6318:         foreach my $key (keys(%$param_hash)) {
                   6319:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6320:         }
                   6321:     }
                   6322:     return \%returnhash;
1.12      www      6323: }
                   6324: 
1.627     albertel 6325: # ------------------------------------------------------ critical inc interface
                   6326: 
                   6327: sub cinc {
                   6328:     return &inc(@_,'critical');
                   6329: }
                   6330: 
1.449     matthew  6331: # --------------------------------------------------------------- inc interface
                   6332: 
                   6333: sub inc {
1.627     albertel 6334:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6335:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6336:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6337:     my $uhome=&homeserver($uname,$udomain);
                   6338:     my $items='';
                   6339:     if (! ref($store)) {
                   6340:         # got a single value, so use that instead
                   6341:         $items = &escape($store).'=&';
                   6342:     } elsif (ref($store) eq 'SCALAR') {
                   6343:         $items = &escape($$store).'=&';        
                   6344:     } elsif (ref($store) eq 'ARRAY') {
                   6345:         $items = join('=&',map {&escape($_);} @{$store});
                   6346:     } elsif (ref($store) eq 'HASH') {
                   6347:         while (my($key,$value) = each(%{$store})) {
                   6348:             $items.= &escape($key).'='.&escape($value).'&';
                   6349:         }
                   6350:     }
                   6351:     $items=~s/\&$//;
1.627     albertel 6352:     if ($critical) {
                   6353: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6354:     } else {
                   6355: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6356:     }
1.449     matthew  6357: }
                   6358: 
1.12      www      6359: # --------------------------------------------------------------- put interface
                   6360: 
                   6361: sub put {
1.134     albertel 6362:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6363:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6364:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6365:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6366:    my $items='';
1.800     albertel 6367:    foreach my $item (keys(%$storehash)) {
                   6368:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6369:    }
1.12      www      6370:    $items=~s/\&$//;
1.134     albertel 6371:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6372: }
                   6373: 
1.631     albertel 6374: # ------------------------------------------------------------ newput interface
                   6375: 
                   6376: sub newput {
                   6377:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6378:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6379:    if (!$uname) { $uname=$env{'user.name'}; }
                   6380:    my $uhome=&homeserver($uname,$udomain);
                   6381:    my $items='';
                   6382:    foreach my $key (keys(%$storehash)) {
                   6383:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6384:    }
                   6385:    $items=~s/\&$//;
                   6386:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6387: }
                   6388: 
                   6389: # ---------------------------------------------------------  putstore interface
                   6390: 
1.524     raeburn  6391: sub putstore {
1.1269    raeburn  6392:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6393:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6394:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6395:    my $uhome=&homeserver($uname,$udomain);
                   6396:    my $items='';
1.715     albertel 6397:    foreach my $key (keys(%$storehash)) {
                   6398:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6399:    }
1.715     albertel 6400:    $items=~s/\&$//;
1.716     albertel 6401:    my $esc_symb=&escape($symb);
                   6402:    my $esc_v=&escape($version);
1.715     albertel 6403:    my $reply =
1.716     albertel 6404:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6405: 	      $uhome);
1.1269    raeburn  6406:    if (($tolog) && ($reply eq 'ok')) {
                   6407:        my $namevalue='';
                   6408:        foreach my $key (keys(%{$storehash})) {
                   6409:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6410:        }
                   6411:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6412:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6413:                      '&version='.$esc_v.
                   6414:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6415:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6416:    }
1.715     albertel 6417:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6418:        # gfall back to way things use to be done
1.715     albertel 6419:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6420: 			    $uname);
1.524     raeburn  6421:    }
1.715     albertel 6422:    return $reply;
                   6423: }
                   6424: 
                   6425: sub old_putstore {
1.716     albertel 6426:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6427:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6428:     if (!$uname) { $uname=$env{'user.name'}; }
                   6429:     my $uhome=&homeserver($uname,$udomain);
                   6430:     my %newstorehash;
1.800     albertel 6431:     foreach my $item (keys(%$storehash)) {
                   6432: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6433: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6434:     }
                   6435:     my $items='';
                   6436:     my %allitems = ();
1.800     albertel 6437:     foreach my $item (keys(%newstorehash)) {
                   6438: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6439: 	    my $key = $1.':keys:'.$2;
                   6440: 	    $allitems{$key} .= $3.':';
                   6441: 	}
1.800     albertel 6442: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6443:     }
1.800     albertel 6444:     foreach my $item (keys(%allitems)) {
                   6445: 	$allitems{$item} =~ s/\:$//;
                   6446: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6447:     }
                   6448:     $items=~s/\&$//;
                   6449:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6450: }
                   6451: 
1.47      www      6452: # ------------------------------------------------------ critical put interface
                   6453: 
                   6454: sub cput {
1.134     albertel 6455:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6456:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6457:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6458:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6459:    my $items='';
1.800     albertel 6460:    foreach my $item (keys(%$storehash)) {
                   6461:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6462:    }
1.47      www      6463:    $items=~s/\&$//;
1.134     albertel 6464:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6465: }
                   6466: 
                   6467: # -------------------------------------------------------------- eget interface
                   6468: 
                   6469: sub eget {
1.133     albertel 6470:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6471:    my $items='';
1.800     albertel 6472:    foreach my $item (@$storearr) {
                   6473:        $items.=&escape($item).'&';
1.191     harris41 6474:    }
1.12      www      6475:    $items=~s/\&$//;
1.620     albertel 6476:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6477:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6478:    my $uhome=&homeserver($uname,$udomain);
                   6479:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6480:    my @pairs=split(/\&/,$rep);
                   6481:    my %returnhash=();
1.42      www      6482:    my $i=0;
1.800     albertel 6483:    foreach my $item (@$storearr) {
                   6484:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6485:       $i++;
1.191     harris41 6486:    }
1.12      www      6487:    return %returnhash;
                   6488: }
                   6489: 
1.667     albertel 6490: # ------------------------------------------------------------ tmpput interface
                   6491: sub tmpput {
1.802     raeburn  6492:     my ($storehash,$server,$context)=@_;
1.667     albertel 6493:     my $items='';
1.800     albertel 6494:     foreach my $item (keys(%$storehash)) {
                   6495: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6496:     }
                   6497:     $items=~s/\&$//;
1.802     raeburn  6498:     if (defined($context)) {
                   6499:         $items .= ':'.&escape($context);
                   6500:     }
1.667     albertel 6501:     return &reply("tmpput:$items",$server);
                   6502: }
                   6503: 
                   6504: # ------------------------------------------------------------ tmpget interface
                   6505: sub tmpget {
1.688     albertel 6506:     my ($token,$server)=@_;
                   6507:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6508:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6509:     my %returnhash;
1.1328    raeburn  6510:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   6511:         return %returnhash;
                   6512:     }
1.667     albertel 6513:     foreach my $item (split(/\&/,$rep)) {
                   6514: 	my ($key,$value)=split(/=/,$item);
                   6515: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6516:     }
                   6517:     return %returnhash;
                   6518: }
                   6519: 
1.1113    raeburn  6520: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6521: sub tmpdel {
                   6522:     my ($token,$server)=@_;
                   6523:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6524:     return &reply("tmpdel:$token",$server);
                   6525: }
                   6526: 
1.1198    raeburn  6527: # ------------------------------------------------------------ get_timebased_id 
                   6528: 
                   6529: sub get_timebased_id {
                   6530:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6531:         $maxtries) = @_;
                   6532:     my ($newid,$error,$dellock);
                   6533:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   6534:         return ('','ok','invalid call to get suffix');
                   6535:     }
                   6536: 
                   6537: # set defaults for any optional args for which values were not supplied
                   6538:     if ($who eq '') {
                   6539:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6540:     }
                   6541:     if (!$locktries) {
                   6542:         $locktries = 3;
                   6543:     }
                   6544:     if (!$maxtries) {
                   6545:         $maxtries = 10;
                   6546:     }
                   6547:     
                   6548:     if (($cdom eq '') || ($cnum eq '')) {
                   6549:         if ($env{'request.course.id'}) {
                   6550:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6551:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6552:         }
                   6553:         if (($cdom eq '') || ($cnum eq '')) {
                   6554:             return ('','ok','call to get suffix not in course context');
                   6555:         }
                   6556:     }
                   6557: 
                   6558: # construct locking item
                   6559:     my $lockhash = {
                   6560:                       $prefix."\0".'locked_'.$keyid => $who,
                   6561:                    };
                   6562:     my $tries = 0;
                   6563: 
                   6564: # attempt to get lock on nohist_$namespace file
                   6565:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6566:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6567:         $tries ++;
                   6568:         sleep 1;
                   6569:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6570:     }
                   6571: 
                   6572: # attempt to get unique identifier, based on current timestamp
                   6573:     if ($gotlock eq 'ok') {
                   6574:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6575:         my $id = time;
                   6576:         $newid = $id;
1.1268    raeburn  6577:         if ($idtype eq 'addcode') {
                   6578:             $newid .= &sixnum_code();
                   6579:         }
1.1198    raeburn  6580:         my $idtries = 0;
                   6581:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6582:             if ($idtype eq 'concat') {
                   6583:                 $newid = $id.$idtries;
1.1268    raeburn  6584:             } elsif ($idtype eq 'addcode') {
                   6585:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  6586:             } else {
                   6587:                 $newid ++;
                   6588:             }
                   6589:             $idtries ++;
                   6590:         }
                   6591:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6592:             my %new_item =  (
                   6593:                               $prefix."\0".$newid => $who,
                   6594:                             );
                   6595:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6596:                                                  $cdom,$cnum);
                   6597:             if ($putresult ne 'ok') {
                   6598:                 undef($newid);
                   6599:                 $error = 'error saving new item: '.$putresult;
                   6600:             }
                   6601:         } else {
1.1268    raeburn  6602:              undef($newid);
1.1198    raeburn  6603:              $error = ('error: no unique suffix available for the new item ');
                   6604:         }
                   6605: #  remove lock
                   6606:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6607:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6608:     } else {
                   6609:         $error = "error: could not obtain lockfile\n";
                   6610:         $dellock = 'ok';
1.1276    raeburn  6611:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6612:             $dellock = 'nolock';
                   6613:         }
1.1198    raeburn  6614:     }
                   6615:     return ($newid,$dellock,$error);
                   6616: }
                   6617: 
1.1268    raeburn  6618: sub sixnum_code {
                   6619:     my $code;
                   6620:     for (0..6) {
                   6621:         $code .= int( rand(9) );
                   6622:     }
                   6623:     return $code;
                   6624: }
                   6625: 
1.765     albertel 6626: # -------------------------------------------------- portfolio access checking
                   6627: 
                   6628: sub portfolio_access {
1.1270    raeburn  6629:     my ($requrl,$clientip) = @_;
1.765     albertel 6630:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  6631:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6632:     if ($result) {
                   6633:         my %setters;
                   6634:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6635:             my ($startblock,$endblock) =
                   6636:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6637:             if ($startblock && $endblock) {
                   6638:                 return 'B';
                   6639:             }
                   6640:         } else {
                   6641:             my ($startblock,$endblock) =
                   6642:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6643:             if ($startblock && $endblock) {
                   6644:                 return 'B';
                   6645:             }
                   6646:         }
                   6647:     }
1.765     albertel 6648:     if ($result eq 'ok') {
1.766     albertel 6649:        return 'F';
1.765     albertel 6650:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6651:        return 'A';
1.765     albertel 6652:     }
1.766     albertel 6653:     return '';
1.765     albertel 6654: }
                   6655: 
                   6656: sub get_portfolio_access {
1.1270    raeburn  6657:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 6658: 
                   6659:     if (!ref($access_hash)) {
                   6660: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6661: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6662: 						   $file_name);
                   6663: 	$access_hash = $access_controls{$file_name};
                   6664:     }
                   6665: 
1.1270    raeburn  6666:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 6667:     my $now = time;
                   6668:     if (ref($access_hash) eq 'HASH') {
                   6669:         foreach my $key (keys(%{$access_hash})) {
                   6670:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6671:             if ($start > $now) {
                   6672:                 next;
                   6673:             }
                   6674:             if ($end && $end<$now) {
                   6675:                 next;
                   6676:             }
                   6677:             if ($scope eq 'public') {
                   6678:                 $public = $key;
                   6679:                 last;
                   6680:             } elsif ($scope eq 'guest') {
                   6681:                 $guest = $key;
                   6682:             } elsif ($scope eq 'domains') {
                   6683:                 push(@domains,$key);
                   6684:             } elsif ($scope eq 'users') {
                   6685:                 push(@users,$key);
                   6686:             } elsif ($scope eq 'course') {
                   6687:                 push(@courses,$key);
                   6688:             } elsif ($scope eq 'group') {
                   6689:                 push(@groups,$key);
1.1270    raeburn  6690:             } elsif ($scope eq 'ip') {
                   6691:                 push(@ips,$key);
1.765     albertel 6692:             }
                   6693:         }
                   6694:         if ($public) {
                   6695:             return 'ok';
1.1270    raeburn  6696:         } elsif (@ips > 0) {
                   6697:             my $allowed;
                   6698:             foreach my $ipkey (@ips) {
                   6699:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   6700:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   6701:                         $allowed = 1;
                   6702:                         last; 
                   6703:                     }
                   6704:                 }
                   6705:             }
                   6706:             if ($allowed) {
                   6707:                 return 'ok';
                   6708:             }
1.765     albertel 6709:         }
                   6710:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6711:             if ($guest) {
                   6712:                 return $guest;
                   6713:             }
                   6714:         } else {
                   6715:             if (@domains > 0) {
                   6716:                 foreach my $domkey (@domains) {
                   6717:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6718:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6719:                             return 'ok';
                   6720:                         }
                   6721:                     }
                   6722:                 }
                   6723:             }
                   6724:             if (@users > 0) {
                   6725:                 foreach my $userkey (@users) {
1.865     raeburn  6726:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6727:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6728:                             if (ref($item) eq 'HASH') {
                   6729:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6730:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6731:                                     return 'ok';
                   6732:                                 }
                   6733:                             }
                   6734:                         }
                   6735:                     } 
1.765     albertel 6736:                 }
                   6737:             }
                   6738:             my %roleshash;
                   6739:             my @courses_and_groups = @courses;
                   6740:             push(@courses_and_groups,@groups); 
                   6741:             if (@courses_and_groups > 0) {
                   6742:                 my (%allgroups,%allroles); 
                   6743:                 my ($start,$end,$role,$sec,$group);
                   6744:                 foreach my $envkey (%env) {
1.1060    raeburn  6745:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6746:                         my $cid = $2.'_'.$3; 
                   6747:                         if ($1 eq 'gr') {
                   6748:                             $group = $4;
                   6749:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6750:                         } else {
                   6751:                             if ($4 eq '') {
                   6752:                                 $sec = 'none';
                   6753:                             } else {
                   6754:                                 $sec = $4;
                   6755:                             }
                   6756:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6757:                         }
1.811     albertel 6758:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6759:                         my $cid = $2.'_'.$3;
                   6760:                         if ($4 eq '') {
                   6761:                             $sec = 'none';
                   6762:                         } else {
                   6763:                             $sec = $4;
                   6764:                         }
                   6765:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6766:                     }
                   6767:                 }
                   6768:                 if (keys(%allroles) == 0) {
                   6769:                     return;
                   6770:                 }
                   6771:                 foreach my $key (@courses_and_groups) {
                   6772:                     my %content = %{$$access_hash{$key}};
                   6773:                     my $cnum = $content{'number'};
                   6774:                     my $cdom = $content{'domain'};
                   6775:                     my $cid = $cdom.'_'.$cnum;
                   6776:                     if (!exists($allroles{$cid})) {
                   6777:                         next;
                   6778:                     }    
                   6779:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6780:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6781:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6782:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6783:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6784:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6785:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6786:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6787:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6788:                                         if (grep/^all$/,@sections) {
                   6789:                                             return 'ok';
                   6790:                                         } else {
                   6791:                                             if (grep/^$sec$/,@sections) {
                   6792:                                                 return 'ok';
                   6793:                                             }
                   6794:                                         }
                   6795:                                     }
                   6796:                                 }
                   6797:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6798:                                     if (grep/^none$/,@groups) {
                   6799:                                         return 'ok';
                   6800:                                     }
                   6801:                                 } else {
                   6802:                                     if (grep/^all$/,@groups) {
                   6803:                                         return 'ok';
                   6804:                                     } 
                   6805:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6806:                                         if (grep/^$group$/,@groups) {
                   6807:                                             return 'ok';
                   6808:                                         }
                   6809:                                     }
                   6810:                                 } 
                   6811:                             }
                   6812:                         }
                   6813:                     }
                   6814:                 }
                   6815:             }
                   6816:             if ($guest) {
                   6817:                 return $guest;
                   6818:             }
                   6819:         }
                   6820:     }
                   6821:     return;
                   6822: }
                   6823: 
                   6824: sub course_group_datechecker {
                   6825:     my ($dates,$now,$status) = @_;
                   6826:     my ($start,$end) = split(/\./,$dates);
                   6827:     if (!$start && !$end) {
                   6828:         return 'ok';
                   6829:     }
                   6830:     if (grep/^active$/,@{$status}) {
                   6831:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6832:             return 'ok';
                   6833:         }
                   6834:     }
                   6835:     if (grep/^previous$/,@{$status}) {
                   6836:         if ($end > $now ) {
                   6837:             return 'ok';
                   6838:         }
                   6839:     }
                   6840:     if (grep/^future$/,@{$status}) {
                   6841:         if ($start > $now) {
                   6842:             return 'ok';
                   6843:         }
                   6844:     }
                   6845:     return; 
                   6846: }
                   6847: 
                   6848: sub parse_portfolio_url {
                   6849:     my ($url) = @_;
                   6850: 
                   6851:     my ($type,$udom,$unum,$group,$file_name);
                   6852:     
1.823     albertel 6853:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6854: 	$type = 1;
                   6855:         $udom = $1;
                   6856:         $unum = $2;
                   6857:         $file_name = $3;
1.823     albertel 6858:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6859: 	$type = 2;
                   6860:         $udom = $1;
                   6861:         $unum = $2;
                   6862:         $group = $3;
                   6863:         $file_name = $3.'/'.$4;
                   6864:     }
                   6865:     if (wantarray) {
                   6866: 	return ($type,$udom,$unum,$file_name,$group);
                   6867:     }
                   6868:     return $type;
                   6869: }
                   6870: 
                   6871: sub is_portfolio_url {
                   6872:     my ($url) = @_;
                   6873:     return scalar(&parse_portfolio_url($url));
                   6874: }
                   6875: 
1.798     raeburn  6876: sub is_portfolio_file {
                   6877:     my ($file) = @_;
1.820     raeburn  6878:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6879:         return 1;
                   6880:     }
                   6881:     return;
                   6882: }
                   6883: 
1.976     raeburn  6884: sub usertools_access {
1.1084    raeburn  6885:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6886:     my ($access,%tools);
                   6887:     if ($context eq '') {
                   6888:         $context = 'tools';
                   6889:     }
                   6890:     if ($context eq 'requestcourses') {
                   6891:         %tools = (
                   6892:                       official   => 1,
                   6893:                       unofficial => 1,
1.1006    raeburn  6894:                       community  => 1,
1.1246    raeburn  6895:                       textbook   => 1,
1.1305    raeburn  6896:                       placement  => 1,
1.985     raeburn  6897:                  );
1.1183    raeburn  6898:     } elsif ($context eq 'requestauthor') {
                   6899:         %tools = (
                   6900:                       requestauthor => 1,
                   6901:                  );
1.985     raeburn  6902:     } else {
                   6903:         %tools = (
                   6904:                       aboutme   => 1,
                   6905:                       blog      => 1,
1.1177    raeburn  6906:                       webdav    => 1,
1.985     raeburn  6907:                       portfolio => 1,
                   6908:                  );
                   6909:     }
1.976     raeburn  6910:     return if (!defined($tools{$tool}));
                   6911: 
1.1242    raeburn  6912:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6913:         $udom = $env{'user.domain'};
                   6914:         $uname = $env{'user.name'};
                   6915:     }
                   6916: 
1.978     raeburn  6917:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6918:         if ($action ne 'reload') {
1.985     raeburn  6919:             if ($context eq 'requestcourses') {
                   6920:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  6921:             } elsif ($context eq 'requestauthor') {
                   6922:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6923:             } else {
                   6924:                 return $env{'environment.availabletools.'.$tool};
                   6925:             }
                   6926:         }
1.976     raeburn  6927:     }
                   6928: 
1.1183    raeburn  6929:     my ($toolstatus,$inststatus,$envkey);
                   6930:     if ($context eq 'requestauthor') {
                   6931:         $envkey = $context; 
                   6932:     } else {
                   6933:         $envkey = $context.'.'.$tool;
                   6934:     }
1.976     raeburn  6935: 
1.985     raeburn  6936:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6937:          ($action ne 'reload')) {
1.1183    raeburn  6938:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6939:         $inststatus = $env{'environment.inststatus'};
                   6940:     } else {
1.1084    raeburn  6941:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  6942:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6943:             $inststatus = $userenvref->{'inststatus'};
                   6944:         } else {
1.1183    raeburn  6945:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6946:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6947:             $inststatus = $userenv{'inststatus'};
                   6948:         }
1.976     raeburn  6949:     }
                   6950: 
                   6951:     if ($toolstatus ne '') {
                   6952:         if ($toolstatus) {
                   6953:             $access = 1;
                   6954:         } else {
                   6955:             $access = 0;
                   6956:         }
                   6957:         return $access;
                   6958:     }
                   6959: 
1.1084    raeburn  6960:     my ($is_adv,%domdef);
                   6961:     if (ref($is_advref) eq 'HASH') {
                   6962:         $is_adv = $is_advref->{'is_adv'};
                   6963:     } else {
                   6964:         $is_adv = &is_advanced_user($udom,$uname);
                   6965:     }
                   6966:     if (ref($domdefref) eq 'HASH') {
                   6967:         %domdef = %{$domdefref};
                   6968:     } else {
                   6969:         %domdef = &get_domain_defaults($udom);
                   6970:     }
1.976     raeburn  6971:     if (ref($domdef{$tool}) eq 'HASH') {
                   6972:         if ($is_adv) {
                   6973:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6974:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6975:                     $access = 1;
                   6976:                 } else {
                   6977:                     $access = 0;
                   6978:                 }
                   6979:                 return $access;
                   6980:             }
                   6981:         }
                   6982:         if ($inststatus ne '') {
                   6983:             my ($hasaccess,$hasnoaccess);
                   6984:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6985:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6986:                     if ($domdef{$tool}{$affiliation}) {
                   6987:                         $hasaccess = 1;
                   6988:                     } else {
                   6989:                         $hasnoaccess = 1;
                   6990:                     }
                   6991:                 }
                   6992:             }
                   6993:             if ($hasaccess || $hasnoaccess) {
                   6994:                 if ($hasaccess) {
                   6995:                     $access = 1;
                   6996:                 } elsif ($hasnoaccess) {
                   6997:                     $access = 0; 
                   6998:                 }
                   6999:                 return $access;
                   7000:             }
                   7001:         } else {
                   7002:             if ($domdef{$tool}{'default'} ne '') {
                   7003:                 if ($domdef{$tool}{'default'}) {
                   7004:                     $access = 1;
                   7005:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7006:                     $access = 0;
                   7007:                 }
                   7008:                 return $access;
                   7009:             }
                   7010:         }
                   7011:     } else {
1.1177    raeburn  7012:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7013:             $access = 1;
                   7014:         } else {
                   7015:             $access = 0;
                   7016:         }
1.976     raeburn  7017:         return $access;
                   7018:     }
                   7019: }
                   7020: 
1.1050    raeburn  7021: sub is_course_owner {
                   7022:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7023:     if (($udom eq '') || ($uname eq '')) {
                   7024:         $udom = $env{'user.domain'};
                   7025:         $uname = $env{'user.name'};
                   7026:     }
                   7027:     unless (($udom eq '') || ($uname eq '')) {
                   7028:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7029:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7030:                 return 1;
                   7031:             } else {
                   7032:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7033:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7034:                     return 1;
                   7035:                 }
                   7036:             }
                   7037:         }
                   7038:     }
                   7039:     return;
                   7040: }
                   7041: 
1.976     raeburn  7042: sub is_advanced_user {
                   7043:     my ($udom,$uname) = @_;
1.1085    raeburn  7044:     if ($udom ne '' && $uname ne '') {
                   7045:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7046:             if (wantarray) {
                   7047:                 return ($env{'user.adv'},$env{'user.author'});
                   7048:             } else {
                   7049:                 return $env{'user.adv'};
                   7050:             }
1.1085    raeburn  7051:         }
                   7052:     }
1.976     raeburn  7053:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7054:     my %allroles;
1.1128    raeburn  7055:     my ($is_adv,$is_author);
1.976     raeburn  7056:     foreach my $role (keys(%roleshash)) {
                   7057:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7058:         my $area = '/'.$tdomain.'/'.$trest;
                   7059:         if ($sec ne '') {
                   7060:             $area .= '/'.$sec;
                   7061:         }
                   7062:         if (($area ne '') && ($trole ne '')) {
                   7063:             my $spec=$trole.'.'.$area;
                   7064:             if ($trole =~ /^cr\//) {
                   7065:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7066:             } elsif ($trole ne 'gr') {
                   7067:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7068:             }
1.1128    raeburn  7069:             if ($trole eq 'au') {
                   7070:                 $is_author = 1;
                   7071:             }
1.976     raeburn  7072:         }
                   7073:     }
                   7074:     foreach my $role (keys(%allroles)) {
                   7075:         last if ($is_adv);
                   7076:         foreach my $item (split(/:/,$allroles{$role})) {
                   7077:             if ($item ne '') {
                   7078:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7079:                 if ($privilege eq 'adv') {
                   7080:                     $is_adv = 1;
                   7081:                     last;
                   7082:                 }
                   7083:             }
                   7084:         }
                   7085:     }
1.1128    raeburn  7086:     if (wantarray) {
                   7087:         return ($is_adv,$is_author);
                   7088:     }
1.976     raeburn  7089:     return $is_adv;
                   7090: }
1.798     raeburn  7091: 
1.1035    raeburn  7092: sub check_can_request {
1.1036    raeburn  7093:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7094:     my $canreq = 0;
                   7095:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7096:     my @options = ('approval','validate','autolimit');
                   7097:     my $optregex = join('|',@options);
                   7098:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7099:         foreach my $type (@{$types}) {
                   7100:             if (&usertools_access($env{'user.name'},
                   7101:                                   $env{'user.domain'},
                   7102:                                   $type,undef,'requestcourses')) {
                   7103:                 $canreq ++;
1.1036    raeburn  7104:                 if (ref($request_domains) eq 'HASH') {
                   7105:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7106:                 }
1.1035    raeburn  7107:                 if ($dom eq $env{'user.domain'}) {
                   7108:                     $can_request->{$type} = 1;
                   7109:                 }
                   7110:             }
                   7111:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7112:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7113:                 if (@curr > 0) {
1.1036    raeburn  7114:                     foreach my $item (@curr) {
                   7115:                         if (ref($request_domains) eq 'HASH') {
                   7116:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7117:                             if ($otherdom ne '') {
                   7118:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7119:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7120:                                         push(@{$request_domains->{$type}},$otherdom);
                   7121:                                     }
                   7122:                                 } else {
                   7123:                                     push(@{$request_domains->{$type}},$otherdom);
                   7124:                                 }
                   7125:                             }
                   7126:                         }
                   7127:                     }
                   7128:                     unless($dom eq $env{'user.domain'}) {
                   7129:                         $canreq ++;
1.1035    raeburn  7130:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7131:                             $can_request->{$type} = 1;
                   7132:                         }
                   7133:                     }
                   7134:                 }
                   7135:             }
                   7136:         }
                   7137:     }
                   7138:     return $canreq;
                   7139: }
                   7140: 
1.341     www      7141: # ---------------------------------------------- Custom access rule evaluation
                   7142: 
                   7143: sub customaccess {
                   7144:     my ($priv,$uri)=@_;
1.807     albertel 7145:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7146:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7147:     $udom = &LONCAPA::clean_domain($udom);
                   7148:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7149:     my $access=0;
1.800     albertel 7150:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7151: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7152: 	if ($type eq 'user') {
                   7153: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7154: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7155: 		if ($tdom) {
                   7156: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7157: 		}
1.896     albertel 7158: 		if ($tuname) {
                   7159: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7160: 		}
                   7161: 		$access=($effect eq 'allow');
                   7162: 		last;
                   7163: 	    }
                   7164: 	} else {
                   7165: 	    if ($role) {
                   7166: 		if ($role ne $urole) { next; }
                   7167: 	    }
                   7168: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7169: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7170: 		if ($tdom) {
                   7171: 		    if ($tdom ne $udom) { next; }
                   7172: 		}
                   7173: 		if ($tcrs) {
                   7174: 		    if ($tcrs ne $ucrs) { next; }
                   7175: 		}
                   7176: 		if ($tsec) {
                   7177: 		    if ($tsec ne $usec) { next; }
                   7178: 		}
                   7179: 		$access=($effect eq 'allow');
                   7180: 		last;
                   7181: 	    }
                   7182: 	    if ($realm eq '' && $role eq '') {
                   7183: 		$access=($effect eq 'allow');
                   7184: 	    }
1.402     bowersj2 7185: 	}
1.341     www      7186:     }
                   7187:     return $access;
                   7188: }
                   7189: 
1.103     harris41 7190: # ------------------------------------------------- Check for a user privilege
1.12      www      7191: 
                   7192: sub allowed {
1.1281    raeburn  7193:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7194:     my $ver_orguri=$uri;
1.439     www      7195:     $uri=&deversion($uri);
1.152     www      7196:     my $orguri=$uri;
1.52      www      7197:     $uri=&declutter($uri);
1.809     raeburn  7198: 
1.810     raeburn  7199:     if ($priv eq 'evb') {
                   7200: # Evade communication block restrictions for specified role in a course
                   7201:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7202:             return $1;
                   7203:         } else {
                   7204:             return;
                   7205:         }
                   7206:     }
                   7207: 
1.620     albertel 7208:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7209: # Free bre access to adm and meta resources
1.775     albertel 7210:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 7211: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7212: 	&& ($priv eq 'bre')) {
1.14      www      7213: 	return 'F';
1.159     www      7214:     }
                   7215: 
1.545     banghart 7216: # Free bre access to user's own portfolio contents
1.714     raeburn  7217:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7218:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7219: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7220:         my %setters;
                   7221:         my ($startblock,$endblock) = 
                   7222:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7223:         if ($startblock && $endblock) {
                   7224:             return 'B';
                   7225:         } else {
                   7226:             return 'F';
                   7227:         }
1.545     banghart 7228:     }
                   7229: 
1.762     raeburn  7230: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7231:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7232:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7233:         if (exists($env{'request.course.id'})) {
                   7234:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7235:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7236:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7237:                 my $courseprivid=$env{'request.course.id'};
                   7238:                 $courseprivid=~s/\_/\//;
                   7239:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7240:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7241:                     return $1; 
1.762     raeburn  7242:                 } else {
                   7243:                     if ($env{'request.course.sec'}) {
                   7244:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7245:                     }
                   7246:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7247:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7248:                         return $2;
                   7249:                     }
1.714     raeburn  7250:                 }
                   7251:             }
                   7252:         }
                   7253:     }
                   7254: 
1.159     www      7255: # Free bre to public access
                   7256: 
                   7257:     if ($priv eq 'bre') {
1.238     www      7258:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7259: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7260:            return 'F'; 
                   7261:         }
1.238     www      7262:         if ($copyright eq 'priv') {
                   7263:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7264: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7265: 		return '';
                   7266:             }
                   7267:         }
                   7268:         if ($copyright eq 'domain') {
                   7269:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7270: 	    unless (($env{'user.domain'} eq $1) ||
                   7271:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7272: 		return '';
                   7273:             }
1.262     matthew  7274:         }
1.620     albertel 7275:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7276:             # Library role, so allow browsing of resources in this domain.
                   7277:             return 'F';
1.238     www      7278:         }
1.341     www      7279:         if ($copyright eq 'custom') {
                   7280: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7281:         }
1.14      www      7282:     }
1.264     matthew  7283:     # Domain coordinator is trying to create a course
1.620     albertel 7284:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7285:         # uri is the requested domain in this case.
                   7286:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7287:         # a role of dc for the domain in question.
1.620     albertel 7288:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7289:     }
1.29      www      7290: 
1.52      www      7291:     my $thisallowed='';
                   7292:     my $statecond=0;
                   7293:     my $courseprivid='';
                   7294: 
1.1039    raeburn  7295:     my $ownaccess;
1.1043    raeburn  7296:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7297:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7298:         if ($uri eq '') {
                   7299:             $ownaccess = 1;
                   7300:         } else {
                   7301:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7302:                 my $udom = $env{'user.domain'};
                   7303:                 my $uname = $env{'user.name'};
                   7304:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7305:                     $ownaccess = 1;
1.1040    raeburn  7306:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7307:                     unless ($uri =~ m{\.\./}) {
                   7308:                         $ownaccess = 1;
                   7309:                     }
                   7310:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7311:                     my $now = time;
                   7312:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7313:                         my $adom = $1;
                   7314:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7315:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7316:                                 my ($start,$end) = split('.',$env{$key});
                   7317:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7318:                                     $ownaccess = 1;
                   7319:                                     last;
                   7320:                                 }
                   7321:                             }
                   7322:                         }
                   7323:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7324:                         my $adom = $1;
                   7325:                         my $aname = $2;
1.1042    raeburn  7326:                         foreach my $role ('ca','aa') { 
                   7327:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7328:                                 my ($start,$end) =
                   7329:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7330:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7331:                                     $ownaccess = 1;
                   7332:                                     last;
                   7333:                                 }
1.1039    raeburn  7334:                             }
                   7335:                         }
                   7336:                     }
                   7337:                 }
                   7338:             }
                   7339:         }
                   7340:     }
                   7341: 
1.52      www      7342: # Course
                   7343: 
1.620     albertel 7344:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7345:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7346:             $thisallowed.=$1;
                   7347:         }
1.52      www      7348:     }
1.29      www      7349: 
1.52      www      7350: # Domain
                   7351: 
1.620     albertel 7352:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7353:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7354:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7355:             $thisallowed.=$1;
                   7356:         }
1.12      www      7357:     }
1.52      www      7358: 
1.1141    raeburn  7359: # User who is not author or co-author might still be able to edit
                   7360: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7361:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7362:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7363:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7364:             $thisallowed.=$1;
                   7365:         }
                   7366:     }
                   7367: 
1.52      www      7368: # Course: uri itself is a course
1.66      www      7369:     my $courseuri=$uri;
                   7370:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7371:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7372: 
1.620     albertel 7373:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7374:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7375:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7376:             $thisallowed.=$1;
                   7377:         }
1.12      www      7378:     }
1.29      www      7379: 
1.665     albertel 7380: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7381: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7382:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7383: 	$thisallowed='';
1.671     raeburn  7384:         my ($match)=&is_on_map($uri);
                   7385:         if ($match) {
                   7386:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7387:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  7388:                 my $value = $1;
                   7389:                 if ($noblockcheck) {
                   7390:                     $thisallowed.=$value;
1.1162    raeburn  7391:                 } else {
1.1281    raeburn  7392:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7393:                     if (@blockers > 0) {
                   7394:                         $thisallowed = 'B';
                   7395:                     } else {
                   7396:                         $thisallowed.=$value;
                   7397:                     }
1.1162    raeburn  7398:                 }
1.671     raeburn  7399:             }
                   7400:         } else {
1.705     albertel 7401:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7402:             if ($refuri) {
                   7403:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7404:                     $thisallowed='F';
1.671     raeburn  7405:                 } else {
                   7406:                     $refuri=&declutter($refuri);
                   7407:                     my ($match) = &is_on_map($refuri);
                   7408:                     if ($match) {
1.1281    raeburn  7409:                         if ($noblockcheck) {
                   7410:                             $thisallowed='F';
1.1162    raeburn  7411:                         } else {
1.1281    raeburn  7412:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7413:                             if (@blockers > 0) {
                   7414:                                 $thisallowed = 'B';
                   7415:                             } else {
                   7416:                                 $thisallowed='F';
                   7417:                             }
1.1162    raeburn  7418:                         }
1.671     raeburn  7419:                     }
1.669     raeburn  7420:                 }
1.671     raeburn  7421:             }
                   7422:         }
1.314     www      7423:     }
1.492     albertel 7424: 
1.766     albertel 7425:     if ($priv eq 'bre'
                   7426: 	&& $thisallowed ne 'F' 
                   7427: 	&& $thisallowed ne '2'
                   7428: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  7429: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7430:     }
1.1250    raeburn  7431: 
1.52      www      7432: # Full access at system, domain or course-wide level? Exit.
1.29      www      7433:     if ($thisallowed=~/F/) {
                   7434: 	return 'F';
                   7435:     }
                   7436: 
1.52      www      7437: # If this is generating or modifying users, exit with special codes
1.29      www      7438: 
1.643     www      7439:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7440: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7441: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7442: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7443: 	    unless ($auname) { return $thisallowed; }
                   7444: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7445: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7446: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7447: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7448: 	}
1.52      www      7449: 	return $thisallowed;
                   7450:     }
                   7451: #
1.103     harris41 7452: # Gathered so far: system, domain and course wide privileges
1.52      www      7453: #
                   7454: # Course: See if uri or referer is an individual resource that is part of 
                   7455: # the course
                   7456: 
1.620     albertel 7457:     if ($env{'request.course.id'}) {
1.232     www      7458: 
1.620     albertel 7459:        $courseprivid=$env{'request.course.id'};
                   7460:        if ($env{'request.course.sec'}) {
                   7461:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7462:        }
                   7463:        $courseprivid=~s/\_/\//;
                   7464:        my $checkreferer=1;
1.232     www      7465:        my ($match,$cond)=&is_on_map($uri);
                   7466:        if ($match) {
                   7467:            $statecond=$cond;
1.620     albertel 7468:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7469:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7470:                my $value = $1;
                   7471:                if ($priv eq 'bre') {
1.1281    raeburn  7472:                    if ($noblockcheck) {
                   7473:                        $thisallowed.=$value;
1.1162    raeburn  7474:                    } else {
1.1281    raeburn  7475:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7476:                        if (@blockers > 0) {
                   7477:                            $thisallowed = 'B';
                   7478:                        } else {
                   7479:                            $thisallowed.=$value;
                   7480:                        }
1.1162    raeburn  7481:                    }
                   7482:                } else {
                   7483:                    $thisallowed.=$value;
                   7484:                }
1.52      www      7485:                $checkreferer=0;
                   7486:            }
1.29      www      7487:        }
1.83      www      7488:        
1.148     www      7489:        if ($checkreferer) {
1.620     albertel 7490: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7491:             unless ($refuri) {
1.800     albertel 7492:                 foreach my $key (keys(%env)) {
                   7493: 		    if ($key=~/^httpref\..*\*/) {
                   7494: 			my $pattern=$key;
1.156     www      7495:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7496:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7497:                         $pattern=~s/\//\\\//g;
1.152     www      7498:                         if ($orguri=~/$pattern/) {
1.800     albertel 7499: 			    $refuri=$env{$key};
1.148     www      7500:                         }
                   7501:                     }
1.191     harris41 7502:                 }
1.148     www      7503:             }
1.232     www      7504: 
1.148     www      7505:          if ($refuri) { 
1.152     www      7506: 	  $refuri=&declutter($refuri);
1.232     www      7507:           my ($match,$cond)=&is_on_map($refuri);
                   7508:             if ($match) {
                   7509:               my $refstatecond=$cond;
1.620     albertel 7510:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7511:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7512:                   my $value = $1;
                   7513:                   if ($priv eq 'bre') {
1.1281    raeburn  7514:                       if ($noblockcheck) {
                   7515:                           $thisallowed.=$value;
1.1162    raeburn  7516:                       } else {
1.1281    raeburn  7517:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7518:                           if (@blockers > 0) {
                   7519:                               $thisallowed = 'B';
                   7520:                           } else {
                   7521:                               $thisallowed.=$value;
                   7522:                           }
1.1162    raeburn  7523:                       }
                   7524:                   } else {
                   7525:                       $thisallowed.=$value;
                   7526:                   }
1.53      www      7527:                   $uri=$refuri;
                   7528:                   $statecond=$refstatecond;
1.52      www      7529:               }
                   7530:           }
1.148     www      7531:         }
1.29      www      7532:        }
1.52      www      7533:    }
1.29      www      7534: 
1.52      www      7535: #
1.103     harris41 7536: # Gathered now: all privileges that could apply, and condition number
1.52      www      7537: # 
                   7538: #
                   7539: # Full or no access?
                   7540: #
1.29      www      7541: 
1.52      www      7542:     if ($thisallowed=~/F/) {
                   7543: 	return 'F';
                   7544:     }
1.29      www      7545: 
1.52      www      7546:     unless ($thisallowed) {
                   7547:         return '';
                   7548:     }
1.29      www      7549: 
1.52      www      7550: # Restrictions exist, deal with them
                   7551: #
                   7552: #   C:according to course preferences
                   7553: #   R:according to resource settings
                   7554: #   L:unless locked
                   7555: #   X:according to user session state
                   7556: #
                   7557: 
                   7558: # Possibly locked functionality, check all courses
1.54      www      7559: # Locks might take effect only after 10 minutes cache expiration for other
                   7560: # courses, and 2 minutes for current course
1.52      www      7561: 
                   7562:     my $envkey;
                   7563:     if ($thisallowed=~/L/) {
1.1000    raeburn  7564:         foreach $envkey (keys(%env)) {
1.54      www      7565:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7566:                my $courseid=$2;
                   7567:                my $roleid=$1.'.'.$2;
1.92      www      7568:                $courseid=~s/^\///;
1.54      www      7569:                my $expiretime=600;
1.620     albertel 7570:                if ($env{'request.role'} eq $roleid) {
1.54      www      7571: 		  $expiretime=120;
                   7572:                }
                   7573: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7574:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7575:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7576: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7577:                }
1.620     albertel 7578:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7579:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7580: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7581:                        &log($env{'user.domain'},$env{'user.name'},
                   7582:                             $env{'user.home'},
1.57      www      7583:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7584:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7585:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7586: 		       return '';
                   7587:                    }
                   7588:                }
1.620     albertel 7589:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7590:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7591: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7592:                        &log($env{'user.domain'},$env{'user.name'},
                   7593:                             $env{'user.home'},
1.57      www      7594:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7595:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7596:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7597: 		       return '';
                   7598:                    }
                   7599:                }
                   7600: 	   }
1.29      www      7601:        }
1.52      www      7602:     }
                   7603:    
                   7604: #
                   7605: # Rest of the restrictions depend on selected course
                   7606: #
                   7607: 
1.620     albertel 7608:     unless ($env{'request.course.id'}) {
1.766     albertel 7609: 	if ($thisallowed eq 'A') {
                   7610: 	    return 'A';
1.814     raeburn  7611:         } elsif ($thisallowed eq 'B') {
                   7612:             return 'B';
1.766     albertel 7613: 	} else {
                   7614: 	    return '1';
                   7615: 	}
1.52      www      7616:     }
1.29      www      7617: 
1.52      www      7618: #
                   7619: # Now user is definitely in a course
                   7620: #
1.53      www      7621: 
                   7622: 
                   7623: # Course preferences
                   7624: 
                   7625:    if ($thisallowed=~/C/) {
1.620     albertel 7626:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7627:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7628:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7629: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  7630: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 7631: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7632: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7633: 			$env{'request.course.id'});
                   7634: 	   }
1.237     www      7635:            return '';
                   7636:        }
                   7637: 
1.620     albertel 7638:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7639: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  7640: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 7641: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7642: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7643: 			$env{'request.course.id'});
                   7644: 	   }
1.54      www      7645:            return '';
                   7646:        }
1.53      www      7647:    }
                   7648: 
                   7649: # Resource preferences
                   7650: 
                   7651:    if ($thisallowed=~/R/) {
1.620     albertel 7652:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7653:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7654: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7655: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7656: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7657: 	   }
                   7658: 	   return '';
1.54      www      7659:        }
1.53      www      7660:    }
1.30      www      7661: 
1.246     www      7662: # Restricted by state or randomout?
1.30      www      7663: 
1.52      www      7664:    if ($thisallowed=~/X/) {
1.620     albertel 7665:       if ($env{'acc.randomout'}) {
1.579     albertel 7666: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7667:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7668:             return ''; 
                   7669:          }
1.247     www      7670:       }
                   7671:       if (&condval($statecond)) {
1.52      www      7672: 	 return '2';
                   7673:       } else {
                   7674:          return '';
                   7675:       }
                   7676:    }
1.30      www      7677: 
1.766     albertel 7678:     if ($thisallowed eq 'A') {
                   7679: 	return 'A';
1.814     raeburn  7680:     } elsif ($thisallowed eq 'B') {
                   7681:         return 'B';
1.766     albertel 7682:     }
1.52      www      7683:    return 'F';
1.232     www      7684: }
1.1162    raeburn  7685: 
1.1192    raeburn  7686: # ------------------------------------------- Check construction space access
                   7687: 
                   7688: sub constructaccess {
                   7689:     my ($url,$setpriv)=@_;
                   7690: 
                   7691: # We do not allow editing of previous versions of files
                   7692:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7693: 
                   7694: # Get username and domain from URL
                   7695:     my ($ownername,$ownerdomain,$ownerhome);
                   7696: 
                   7697:     ($ownerdomain,$ownername) =
1.1325    raeburn  7698:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192    raeburn  7699: 
                   7700: # The URL does not really point to any authorspace, forget it
                   7701:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7702: 
                   7703: # Now we need to see if the user has access to the authorspace of
                   7704: # $ownername at $ownerdomain
                   7705: 
                   7706:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7707: # Real author for this?
                   7708:        $ownerhome = $env{'user.home'};
                   7709:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7710:           return ($ownername,$ownerdomain,$ownerhome);
                   7711:        }
                   7712:     } else {
                   7713: # Co-author for this?
                   7714:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7715:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7716:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7717:             return ($ownername,$ownerdomain,$ownerhome);
                   7718:         }
1.1312    raeburn  7719:         if ($env{'request.course.id'}) {
                   7720:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
                   7721:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
                   7722:                 if (&allowed('mdc',$env{'request.course.id'})) {
                   7723:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   7724:                     return ($ownername,$ownerdomain,$ownerhome);
                   7725:                 }
                   7726:             }
                   7727:         }
1.1192    raeburn  7728:     }
                   7729: 
                   7730: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7731: # we might as well leave
                   7732:    unless ($setpriv) { return ''; }
                   7733: 
                   7734: # Backdoor access?
                   7735:     my $allowed=&allowed('eco',$ownerdomain);
                   7736: # Nope
                   7737:     unless ($allowed) { return ''; }
                   7738: # Looks like we may have access, but could be locked by the owner of the construction space
                   7739:     if ($allowed eq 'U') {
                   7740:         my %blocked=&get('environment',['domcoord.author'],
                   7741:                          $ownerdomain,$ownername);
                   7742: # Is blocked by owner
                   7743:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7744:     }
                   7745:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7746: # Grant temporary access
                   7747:         my $then=$env{'user.login.time'};
1.1209    raeburn  7748:         my $update=$env{'user.update.time'};
1.1192    raeburn  7749:         if (!$update) { $update = $then; }
                   7750:         my $refresh=$env{'user.refresh.time'};
                   7751:         if (!$refresh) { $refresh = $update; }
                   7752:         my $now = time;
                   7753:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7754:                            $now,'ca','constructaccess');
                   7755:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7756:         return($ownername,$ownerdomain,$ownerhome);
                   7757:     }
                   7758: # No business here
                   7759:     return '';
                   7760: }
                   7761: 
1.1282    raeburn  7762: # ----------------------------------------------------------- Content Blocking
                   7763: 
                   7764: {
                   7765: # Caches for faster Course Contents display where content blocking
                   7766: # is in operation (i.e., interval param set) for timed quiz.
                   7767: #
                   7768: # User for whom data are being temporarily cached.
                   7769: my $cacheduser='';
                   7770: # Cached blockers for this user (a hash of blocking items). 
                   7771: my %cachedblockers=();
                   7772: # When the data were last cached.
                   7773: my $cachedlast='';
                   7774: 
                   7775: sub load_all_blockers {
                   7776:     my ($uname,$udom,$blocks)=@_;
                   7777:     if (($uname ne '') && ($udom ne '')) { 
                   7778:         if (($cacheduser eq $uname.':'.$udom) &&
                   7779:             (abs($cachedlast-time)<5)) {
                   7780:             return;
                   7781:         }
                   7782:     }
                   7783:     $cachedlast=time;
                   7784:     $cacheduser=$uname.':'.$udom;
                   7785:     %cachedblockers = &get_commblock_resources($blocks);
                   7786: }
                   7787: 
1.1162    raeburn  7788: sub get_comm_blocks {
                   7789:     my ($cdom,$cnum) = @_;
                   7790:     if ($cdom eq '' || $cnum eq '') {
                   7791:         return unless ($env{'request.course.id'});
                   7792:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7793:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7794:     }
                   7795:     my %commblocks;
                   7796:     my $hashid=$cdom.'_'.$cnum;
                   7797:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7798:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7799:         %commblocks = %{$blocksref};
                   7800:     } else {
                   7801:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7802:         my $cachetime = 600;
                   7803:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7804:     }
                   7805:     return %commblocks;
                   7806: }
                   7807: 
1.1282    raeburn  7808: sub get_commblock_resources {
                   7809:     my ($blocks) = @_;
                   7810:     my %blockers = ();
                   7811:     return %blockers unless ($env{'request.course.id'});
                   7812:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  7813:     my %commblocks;
                   7814:     if (ref($blocks) eq 'HASH') {
                   7815:         %commblocks = %{$blocks};
                   7816:     } else {
                   7817:         %commblocks = &get_comm_blocks();
                   7818:     }
1.1282    raeburn  7819:     return %blockers unless (keys(%commblocks) > 0); 
                   7820:     my $navmap = Apache::lonnavmaps::navmap->new();
                   7821:     return %blockers unless (ref($navmap));
1.1162    raeburn  7822:     my $now = time;
                   7823:     foreach my $block (keys(%commblocks)) {
                   7824:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7825:             my ($start,$end) = ($1,$2);
                   7826:             if ($start <= $now && $end >= $now) {
                   7827:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7828:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7829:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  7830:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7831:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  7832:                             }
                   7833:                         }
                   7834:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  7835:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7836:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  7837:                             }
                   7838:                         }
                   7839:                     }
                   7840:                 }
                   7841:             }
                   7842:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7843:             my $item = $1;
1.1163    raeburn  7844:             my @to_test;
1.1162    raeburn  7845:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7846:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282    raeburn  7847:                     my @interval;
                   7848:                     my $type = 'map';
                   7849:                     if ($item eq 'course') {
                   7850:                         $type = 'course';
                   7851:                         @interval=&EXT("resource.0.interval");
                   7852:                     } else {
                   7853:                         if ($item =~ /___\d+___/) {
                   7854:                             $type = 'resource';
                   7855:                             @interval=&EXT("resource.0.interval",$item);
                   7856:                             if (ref($navmap)) {                        
                   7857:                                 my $res = $navmap->getBySymb($item); 
                   7858:                                 push(@to_test,$res);
                   7859:                             }
1.1162    raeburn  7860:                         } else {
1.1282    raeburn  7861:                             my $mapsymb = &symbread($item,1);
                   7862:                             if ($mapsymb) {
                   7863:                                 if (ref($navmap)) {
                   7864:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   7865:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   7866:                                     foreach my $res (@to_test) {
                   7867:                                         my $symb = $res->symb();
                   7868:                                         next if ($symb eq $mapsymb);
                   7869:                                         if ($symb ne '') {
                   7870:                                             @interval=&EXT("resource.0.interval",$symb);
                   7871:                                             if ($interval[1] eq 'map') {
                   7872:                                                 last;
1.1162    raeburn  7873:                                             }
                   7874:                                         }
                   7875:                                     }
                   7876:                                 }
                   7877:                             }
                   7878:                         }
1.1282    raeburn  7879:                     }
1.1310    raeburn  7880:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  7881:                         my $timelimit = $1; 
1.1282    raeburn  7882:                         my $first_access;
                   7883:                         if ($type eq 'resource') {
                   7884:                             $first_access=&get_first_access($interval[1],$item);
                   7885:                         } elsif ($type eq 'map') {
                   7886:                             $first_access=&get_first_access($interval[1],undef,$item);
                   7887:                         } else {
                   7888:                             $first_access=&get_first_access($interval[1]);
                   7889:                         }
                   7890:                         if ($first_access) {
1.1292    raeburn  7891:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  7892:                             if ($timesup > $now) {
                   7893:                                 my $activeblock;
                   7894:                                 foreach my $res (@to_test) {
1.1283    raeburn  7895:                                     if ($res->answerable()) {
1.1282    raeburn  7896:                                         $activeblock = 1;
                   7897:                                         last;
                   7898:                                     }
                   7899:                                 }
                   7900:                                 if ($activeblock) {
                   7901:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7902:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7903:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   7904:                                          }
                   7905:                                     }
                   7906:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7907:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7908:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  7909:                                         }
1.1162    raeburn  7910:                                     }
                   7911:                                 }
                   7912:                             }
                   7913:                         }
                   7914:                     }
                   7915:                 }
                   7916:             }
                   7917:         }
                   7918:     }
1.1282    raeburn  7919:     return %blockers;
1.1162    raeburn  7920: }
                   7921: 
1.1282    raeburn  7922: sub has_comm_blocking {
                   7923:     my ($priv,$symb,$uri,$blocks) = @_;
                   7924:     my @blockers;
                   7925:     return unless ($env{'request.course.id'});
                   7926:     return unless ($priv eq 'bre');
                   7927:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7928:     return if ($env{'request.state'} eq 'construct');
                   7929:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   7930:     return unless (keys(%cachedblockers) > 0);
                   7931:     my (%possibles,@symbs);
                   7932:     if (!$symb) {
                   7933:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  7934:     }
1.1282    raeburn  7935:     if ($symb) {
                   7936:         @symbs = ($symb);
                   7937:     } elsif (keys(%possibles)) { 
                   7938:         @symbs = keys(%possibles);
                   7939:     }
                   7940:     my $noblock;
                   7941:     foreach my $symb (@symbs) {
                   7942:         last if ($noblock);
                   7943:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   7944:         foreach my $block (keys(%cachedblockers)) {
                   7945:             if ($block =~ /^firstaccess____(.+)$/) {
                   7946:                 my $item = $1;
                   7947:                 if (($item eq $map) || ($item eq $symb)) {
                   7948:                     $noblock = 1;
                   7949:                     last;
                   7950:                 }
                   7951:             }
                   7952:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   7953:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   7954:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   7955:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   7956:                             push(@blockers,$block);
                   7957:                         }
                   7958:                     }
                   7959:                 }
1.1162    raeburn  7960:             }
1.1282    raeburn  7961:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   7962:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   7963:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   7964:                         push(@blockers,$block);
                   7965:                     }
                   7966:                 }
1.1162    raeburn  7967:             }
                   7968:         }
                   7969:     }
1.1282    raeburn  7970:     return if ($noblock);
                   7971:     return @blockers;
                   7972: }
1.1162    raeburn  7973: }
                   7974: 
1.1282    raeburn  7975: # -------------------------------- Deversion and split uri into path an filename   
                   7976: 
1.1133    foxr     7977: #
1.1282    raeburn  7978: #   Removes the version from a URI and
1.1133    foxr     7979: #   splits it in to its filename and path to the filename.
                   7980: #   Seems like File::Basename could have done this more clearly.
                   7981: #   Parameters:
                   7982: #      $uri   - input URI
                   7983: #   Returns:
                   7984: #     Two element list consisting of 
                   7985: #     $pathname  - the URI up to and excluding the trailing /
                   7986: #     $filename  - The part of the URI following the last /
                   7987: #  NOTE:
                   7988: #    Another realization of this is simply:
                   7989: #    use File::Basename;
                   7990: #    ...
                   7991: #    $uri = shift;
                   7992: #    $filename = basename($uri);
                   7993: #    $path     = dirname($uri);
                   7994: #    return ($filename, $path);
                   7995: #
                   7996: #     The implementation below is probably faster however.
                   7997: #
1.710     albertel 7998: sub split_uri_for_cond {
                   7999:     my $uri=&deversion(&declutter(shift));
                   8000:     my @uriparts=split(/\//,$uri);
                   8001:     my $filename=pop(@uriparts);
                   8002:     my $pathname=join('/',@uriparts);
                   8003:     return ($pathname,$filename);
                   8004: }
1.232     www      8005: # --------------------------------------------------- Is a resource on the map?
                   8006: 
                   8007: sub is_on_map {
1.710     albertel 8008:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8009:     #Trying to find the conditional for the file
1.620     albertel 8010:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8011: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8012:     if ($match) {
1.289     bowersj2 8013: 	return (1,$1);
                   8014:     } else {
1.434     www      8015: 	return (0,0);
1.289     bowersj2 8016:     }
1.12      www      8017: }
                   8018: 
1.427     www      8019: # --------------------------------------------------------- Get symb from alias
                   8020: 
                   8021: sub get_symb_from_alias {
                   8022:     my $symb=shift;
                   8023:     my ($map,$resid,$url)=&decode_symb($symb);
                   8024: # Already is a symb
                   8025:     if ($url) { return $symb; }
                   8026: # Must be an alias
                   8027:     my $aliassymb='';
                   8028:     my %bighash;
1.620     albertel 8029:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8030:                             &GDBM_READER(),0640)) {
                   8031:         my $rid=$bighash{'mapalias_'.$symb};
                   8032: 	if ($rid) {
                   8033: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8034: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8035: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8036: 	}
                   8037:         untie %bighash;
                   8038:     }
                   8039:     return $aliassymb;
                   8040: }
                   8041: 
1.12      www      8042: # ----------------------------------------------------------------- Define Role
                   8043: 
                   8044: sub definerole {
                   8045:   if (allowed('mcr','/')) {
1.1326    raeburn  8046:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8047:     foreach my $role (split(':',$sysrole)) {
                   8048: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8049:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8050:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8051: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8052:                return "refused:s:$crole&$cqual"; 
                   8053:             }
                   8054:         }
1.191     harris41 8055:     }
1.800     albertel 8056:     foreach my $role (split(':',$domrole)) {
                   8057: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8058:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8059:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8060: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8061:                return "refused:d:$crole&$cqual"; 
                   8062:             }
                   8063:         }
1.191     harris41 8064:     }
1.800     albertel 8065:     foreach my $role (split(':',$courole)) {
                   8066: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8067:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8068:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8069: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8070:                return "refused:c:$crole&$cqual"; 
                   8071:             }
                   8072:         }
1.191     harris41 8073:     }
1.1326    raeburn  8074:     my $uhome;
                   8075:     if (($uname ne '') && ($udom ne '')) {
                   8076:         $uhome = &homeserver($uname,$udom);
                   8077:         return $uhome if ($uhome eq 'no_host');
                   8078:     } else {
                   8079:         $uname = $env{'user.name'};
                   8080:         $udom = $env{'user.domain'};
                   8081:         $uhome = $env{'user.home'};
                   8082:     }
1.620     albertel 8083:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326    raeburn  8084:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8085:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326    raeburn  8086:     return reply($command,$uhome);
1.12      www      8087:   } else {
                   8088:     return 'refused';
                   8089:   }
1.105     harris41 8090: }
                   8091: 
                   8092: # ---------------- Make a metadata query against the network of library servers
                   8093: 
                   8094: sub metadata_query {
1.1237    raeburn  8095:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8096:     my %rhash;
1.845     albertel 8097:     my %libserv = &all_library();
1.244     matthew  8098:     my @server_list = (defined($server_array) ? @$server_array
                   8099:                                               : keys(%libserv) );
                   8100:     for my $server (@server_list) {
1.1237    raeburn  8101:         my $domains = ''; 
                   8102:         if (ref($domains_hash) eq 'HASH') {
                   8103:             $domains = $domains_hash->{$server}; 
                   8104:         }
1.118     harris41 8105: 	unless ($custom or $customshow) {
1.1237    raeburn  8106: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8107: 	    $rhash{$server}=$reply;
                   8108: 	}
                   8109: 	else {
                   8110: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  8111: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8112: 			     $server);
                   8113: 	    $rhash{$server}=$reply;
                   8114: 	}
1.112     harris41 8115:     }
1.118     harris41 8116:     return \%rhash;
1.240     www      8117: }
                   8118: 
                   8119: # ----------------------------------------- Send log queries and wait for reply
                   8120: 
                   8121: sub log_query {
                   8122:     my ($uname,$udom,$query,%filters)=@_;
                   8123:     my $uhome=&homeserver($uname,$udom);
                   8124:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8125:     my $uhost=&hostname($uhome);
1.800     albertel 8126:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8127:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8128:                        $uhome);
1.479     albertel 8129:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8130:     return get_query_reply($queryid);
                   8131: }
                   8132: 
1.818     raeburn  8133: # -------------------------- Update MySQL table for portfolio file
                   8134: 
                   8135: sub update_portfolio_table {
1.821     raeburn  8136:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8137:     if ($group ne '') {
                   8138:         $file_name =~s /^\Q$group\E//;
                   8139:     }
1.818     raeburn  8140:     my $homeserver = &homeserver($uname,$udom);
                   8141:     my $queryid=
1.821     raeburn  8142:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8143:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8144:     my $reply = &get_query_reply($queryid);
                   8145:     return $reply;
                   8146: }
                   8147: 
1.899     raeburn  8148: # -------------------------- Update MySQL allusers table
                   8149: 
                   8150: sub update_allusers_table {
                   8151:     my ($uname,$udom,$names) = @_;
                   8152:     my $homeserver = &homeserver($uname,$udom);
                   8153:     my $queryid=
                   8154:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8155:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8156:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8157:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8158:                'generation='.&escape($names->{'generation'}).'%%'.
                   8159:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8160:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8161:     return;
1.899     raeburn  8162: }
                   8163: 
1.508     raeburn  8164: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8165: 
                   8166: sub fetch_enrollment_query {
1.511     raeburn  8167:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317    raeburn  8168:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8169:     my $maxtries = 1;
1.508     raeburn  8170:     if ($context eq 'automated') {
                   8171:         $homeserver = $perlvar{'lonHostID'};
1.1317    raeburn  8172:         $sleep = 2;
                   8173:         $loopmax = 100;
1.547     raeburn  8174:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8175:     } else {
                   8176:         $homeserver = &homeserver($cnum,$dom);
                   8177:     }
1.838     albertel 8178:     my $host=&hostname($homeserver);
1.506     raeburn  8179:     my $cmd = '';
1.1000    raeburn  8180:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8181:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8182:     }
                   8183:     $cmd =~ s/%%$//;
                   8184:     $cmd = &escape($cmd);
                   8185:     my $query = 'fetchenrollment';
1.620     albertel 8186:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8187:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8188:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8189:         return 'error: '.$queryid;
                   8190:     }
1.1317    raeburn  8191:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8192:     my $tries = 1;
                   8193:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317    raeburn  8194:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8195:         $tries ++;
                   8196:     }
1.526     raeburn  8197:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8198:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8199:     } else {
1.901     albertel 8200:         my @responses = split(/:/,$reply);
1.1322    raeburn  8201:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8202:             foreach my $line (@responses) {
                   8203:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8204:                 $$replyref{$key} = $value;
                   8205:             }
                   8206:         } else {
1.1117    foxr     8207:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8208:             foreach my $line (@responses) {
                   8209:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8210:                 $$replyref{$key} = $value;
                   8211:                 if ($value > 0) {
1.800     albertel 8212:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8213:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8214:                         my $destname = $pathname.'/'.$filename;
                   8215:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8216:                         if ($xml_classlist =~ /^error/) {
                   8217:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8218:                         } else {
1.506     raeburn  8219:                             if ( open(FILE,">$destname") ) {
                   8220:                                 print FILE &unescape($xml_classlist);
                   8221:                                 close(FILE);
1.526     raeburn  8222:                             } else {
                   8223:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8224:                             }
                   8225:                         }
                   8226:                     }
                   8227:                 }
                   8228:             }
                   8229:         }
                   8230:         return 'ok';
                   8231:     }
                   8232:     return 'error';
                   8233: }
                   8234: 
1.242     www      8235: sub get_query_reply {
1.1317    raeburn  8236:     my ($queryid,$sleep,$loopmax) = @_;;
                   8237:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8238:         $sleep = 0.2;
                   8239:     }
                   8240:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8241:         $loopmax = 100;
                   8242:     }
1.1117    foxr     8243:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8244:     my $reply='';
1.1317    raeburn  8245:     for (1..$loopmax) {
                   8246: 	sleep($sleep);
1.240     www      8247:         if (-e $replyfile.'.end') {
1.448     albertel 8248: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 8249: 		$reply = join('',<$fh>);
                   8250: 		close($fh);
1.240     www      8251: 	   } else { return 'error: reply_file_error'; }
1.242     www      8252:            return &unescape($reply);
                   8253: 	}
1.240     www      8254:     }
1.242     www      8255:     return 'timeout:'.$queryid;
1.240     www      8256: }
                   8257: 
                   8258: sub courselog_query {
1.241     www      8259: #
                   8260: # possible filters:
                   8261: # url: url or symb
                   8262: # username
                   8263: # domain
                   8264: # action: view, submit, grade
                   8265: # start: timestamp
                   8266: # end: timestamp
                   8267: #
1.240     www      8268:     my (%filters)=@_;
1.620     albertel 8269:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8270:     if ($filters{'url'}) {
                   8271: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8272:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8273:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8274:     }
1.620     albertel 8275:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8276:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8277:     return &log_query($cname,$cdom,'courselog',%filters);
                   8278: }
                   8279: 
                   8280: sub userlog_query {
1.858     raeburn  8281: #
                   8282: # possible filters:
                   8283: # action: log check role
                   8284: # start: timestamp
                   8285: # end: timestamp
                   8286: #
1.240     www      8287:     my ($uname,$udom,%filters)=@_;
                   8288:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8289: }
                   8290: 
1.506     raeburn  8291: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8292: 
                   8293: sub auto_run {
1.508     raeburn  8294:     my ($cnum,$cdom) = @_;
1.876     raeburn  8295:     my $response = 0;
                   8296:     my $settings;
                   8297:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8298:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8299:         $settings = $domconfig{'autoenroll'};
                   8300:         if ($settings->{'run'} eq '1') {
                   8301:             $response = 1;
                   8302:         }
                   8303:     } else {
1.934     raeburn  8304:         my $homeserver;
                   8305:         if (&is_course($cdom,$cnum)) {
                   8306:             $homeserver = &homeserver($cnum,$cdom);
                   8307:         } else {
                   8308:             $homeserver = &domain($cdom,'primary');
                   8309:         }
                   8310:         if ($homeserver ne 'no_host') {
                   8311:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8312:         }
1.876     raeburn  8313:     }
1.506     raeburn  8314:     return $response;
                   8315: }
1.776     albertel 8316: 
1.506     raeburn  8317: sub auto_get_sections {
1.508     raeburn  8318:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8319:     my $homeserver;
                   8320:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8321:         $homeserver = &homeserver($cnum,$cdom);
                   8322:     }
                   8323:     if (!defined($homeserver)) { 
                   8324:         if ($cdom =~ /^$match_domain$/) {
                   8325:             $homeserver = &domain($cdom,'primary');
                   8326:         }
                   8327:     }
                   8328:     my @secs;
                   8329:     if (defined($homeserver)) {
                   8330:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8331:         unless ($response eq 'refused') {
                   8332:             @secs = split(/:/,$response);
                   8333:         }
1.506     raeburn  8334:     }
                   8335:     return @secs;
                   8336: }
1.776     albertel 8337: 
1.506     raeburn  8338: sub auto_new_course {
1.1099    raeburn  8339:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8340:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8341:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8342:     return $response;
                   8343: }
1.776     albertel 8344: 
1.506     raeburn  8345: sub auto_validate_courseID {
1.508     raeburn  8346:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8347:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8348:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8349:     return $response;
                   8350: }
1.776     albertel 8351: 
1.1007    raeburn  8352: sub auto_validate_instcode {
1.1020    raeburn  8353:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8354:     my ($homeserver,$response);
                   8355:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8356:         $homeserver = &homeserver($cnum,$cdom);
                   8357:     }
                   8358:     if (!defined($homeserver)) {
                   8359:         if ($cdom =~ /^$match_domain$/) {
                   8360:             $homeserver = &domain($cdom,'primary');
                   8361:         }
                   8362:     }
1.1065    raeburn  8363:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8364:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  8365:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8366:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8367: }
                   8368: 
1.506     raeburn  8369: sub auto_create_password {
1.873     raeburn  8370:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8371:     my ($homeserver,$response);
1.506     raeburn  8372:     my $create_passwd = 0;
                   8373:     my $authchk = '';
1.873     raeburn  8374:     if ($udom =~ /^$match_domain$/) {
                   8375:         $homeserver = &domain($udom,'primary');
                   8376:     }
                   8377:     if ($homeserver eq '') {
                   8378:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8379:             $homeserver = &homeserver($cnum,$cdom);
                   8380:         }
                   8381:     }
                   8382:     if ($homeserver eq '') {
                   8383:         $authchk = 'nodomain';
1.506     raeburn  8384:     } else {
1.873     raeburn  8385:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8386:         if ($response eq 'refused') {
                   8387:             $authchk = 'refused';
                   8388:         } else {
1.901     albertel 8389:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8390:         }
1.506     raeburn  8391:     }
                   8392:     return ($authparam,$create_passwd,$authchk);
                   8393: }
                   8394: 
1.706     raeburn  8395: sub auto_photo_permission {
                   8396:     my ($cnum,$cdom,$students) = @_;
                   8397:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8398:     my ($outcome,$perm_reqd,$conditions) = 
                   8399: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8400:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8401: 	return (undef,undef);
                   8402:     }
1.706     raeburn  8403:     return ($outcome,$perm_reqd,$conditions);
                   8404: }
                   8405: 
                   8406: sub auto_checkphotos {
                   8407:     my ($uname,$udom,$pid) = @_;
                   8408:     my $homeserver = &homeserver($uname,$udom);
                   8409:     my ($result,$resulttype);
                   8410:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8411: 				   &escape($uname).':'.&escape($pid),
                   8412: 				   $homeserver));
1.709     albertel 8413:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8414: 	return (undef,undef);
                   8415:     }
1.706     raeburn  8416:     if ($outcome) {
                   8417:         ($result,$resulttype) = split(/:/,$outcome);
                   8418:     } 
                   8419:     return ($result,$resulttype);
                   8420: }
                   8421: 
                   8422: sub auto_photochoice {
                   8423:     my ($cnum,$cdom) = @_;
                   8424:     my $homeserver = &homeserver($cnum,$cdom);
                   8425:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8426: 						       &escape($cdom),
                   8427: 						       $homeserver)));
1.709     albertel 8428:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8429: 	return (undef,undef);
                   8430:     }
1.706     raeburn  8431:     return ($update,$comment);
                   8432: }
                   8433: 
                   8434: sub auto_photoupdate {
                   8435:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8436:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8437:     my $host=&hostname($homeserver);
1.706     raeburn  8438:     my $cmd = '';
                   8439:     my $maxtries = 1;
1.800     albertel 8440:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8441:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8442:     }
                   8443:     $cmd =~ s/%%$//;
                   8444:     $cmd = &escape($cmd);
                   8445:     my $query = 'institutionalphotos';
                   8446:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8447:     unless ($queryid=~/^\Q$host\E\_/) {
                   8448:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8449:         return 'error: '.$queryid;
                   8450:     }
                   8451:     my $reply = &get_query_reply($queryid);
                   8452:     my $tries = 1;
                   8453:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8454:         $reply = &get_query_reply($queryid);
                   8455:         $tries ++;
                   8456:     }
                   8457:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8458:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8459:     } else {
                   8460:         my @responses = split(/:/,$reply);
                   8461:         my $outcome = shift(@responses); 
                   8462:         foreach my $item (@responses) {
                   8463:             my ($key,$value) = split(/=/,$item);
                   8464:             $$photo{$key} = $value;
                   8465:         }
                   8466:         return $outcome;
                   8467:     }
                   8468:     return 'error';
                   8469: }
                   8470: 
1.521     raeburn  8471: sub auto_instcode_format {
1.793     albertel 8472:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8473: 	$cat_order) = @_;
1.521     raeburn  8474:     my $courses = '';
1.772     raeburn  8475:     my @homeservers;
1.521     raeburn  8476:     if ($caller eq 'global') {
1.841     albertel 8477: 	my %servers = &get_servers($codedom,'library');
                   8478: 	foreach my $tryserver (keys(%servers)) {
                   8479: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8480: 		push(@homeservers,$tryserver);
                   8481: 	    }
1.584     raeburn  8482:         }
1.1022    raeburn  8483:     } elsif ($caller eq 'requests') {
                   8484:         if ($codedom =~ /^$match_domain$/) {
                   8485:             my $chome = &domain($codedom,'primary');
                   8486:             unless ($chome eq 'no_host') {
                   8487:                 push(@homeservers,$chome);
                   8488:             }
                   8489:         }
1.521     raeburn  8490:     } else {
1.772     raeburn  8491:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8492:     }
1.793     albertel 8493:     foreach my $code (keys(%{$instcodes})) {
                   8494:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8495:     }
                   8496:     chop($courses);
1.772     raeburn  8497:     my $ok_response = 0;
                   8498:     my $response;
                   8499:     while (@homeservers > 0 && $ok_response == 0) {
                   8500:         my $server = shift(@homeservers); 
                   8501:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8502:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8503:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8504: 		split(/:/,$response);
1.772     raeburn  8505:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8506:             push(@{$codetitles},&str2array($codetitles_str));
                   8507:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8508:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8509:             $ok_response = 1;
                   8510:         }
                   8511:     }
                   8512:     if ($ok_response) {
1.521     raeburn  8513:         return 'ok';
1.772     raeburn  8514:     } else {
                   8515:         return $response;
1.521     raeburn  8516:     }
                   8517: }
                   8518: 
1.792     raeburn  8519: sub auto_instcode_defaults {
                   8520:     my ($domain,$returnhash,$code_order) = @_;
                   8521:     my @homeservers;
1.841     albertel 8522: 
                   8523:     my %servers = &get_servers($domain,'library');
                   8524:     foreach my $tryserver (keys(%servers)) {
                   8525: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8526: 	    push(@homeservers,$tryserver);
                   8527: 	}
1.792     raeburn  8528:     }
1.841     albertel 8529: 
1.792     raeburn  8530:     my $response;
1.841     albertel 8531:     foreach my $server (@homeservers) {
1.792     raeburn  8532:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8533:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8534: 	
                   8535: 	foreach my $pair (split(/\&/,$response)) {
                   8536: 	    my ($name,$value)=split(/\=/,$pair);
                   8537: 	    if ($name eq 'code_order') {
                   8538: 		@{$code_order} = split(/\&/,&unescape($value));
                   8539: 	    } else {
                   8540: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8541: 	    }
                   8542: 	}
                   8543: 	return 'ok';
1.792     raeburn  8544:     }
1.841     albertel 8545: 
                   8546:     return $response;
1.1003    raeburn  8547: }
                   8548: 
                   8549: sub auto_possible_instcodes {
1.1007    raeburn  8550:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8551:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8552:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8553:         return;
                   8554:     }
1.1003    raeburn  8555:     my (@homeservers,$uhome);
                   8556:     if (defined(&domain($domain,'primary'))) {
                   8557:         $uhome=&domain($domain,'primary');
                   8558:         push(@homeservers,&domain($domain,'primary'));
                   8559:     } else {
                   8560:         my %servers = &get_servers($domain,'library');
                   8561:         foreach my $tryserver (keys(%servers)) {
                   8562:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8563:                 push(@homeservers,$tryserver);
                   8564:             }
                   8565:         }
                   8566:     }
                   8567:     my $response;
                   8568:     foreach my $server (@homeservers) {
                   8569:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8570:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8571:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8572:             split(':',$response);
                   8573:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8574:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8575:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8576:             my ($name,$value)=split('=',$item);
                   8577:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8578:         }
                   8579:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8580:             my ($name,$value)=split('=',$item);
                   8581:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8582:         }
                   8583:         return 'ok';
                   8584:     }
                   8585:     return $response;
                   8586: }
1.792     raeburn  8587: 
1.1010    raeburn  8588: sub auto_courserequest_checks {
                   8589:     my ($dom) = @_;
1.1020    raeburn  8590:     my ($homeserver,%validations);
                   8591:     if ($dom =~ /^$match_domain$/) {
                   8592:         $homeserver = &domain($dom,'primary');
                   8593:     }
                   8594:     unless ($homeserver eq 'no_host') {
                   8595:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8596:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8597:             my @items = split(/&/,$response);
                   8598:             foreach my $item (@items) {
                   8599:                 my ($key,$value) = split('=',$item);
                   8600:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8601:             }
                   8602:         }
                   8603:     }
1.1010    raeburn  8604:     return %validations; 
                   8605: }
                   8606: 
1.1020    raeburn  8607: sub auto_courserequest_validation {
1.1255    raeburn  8608:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8609:     my ($homeserver,$response);
                   8610:     if ($dom =~ /^$match_domain$/) {
                   8611:         $homeserver = &domain($dom,'primary');
                   8612:     }
1.1255    raeburn  8613:     unless ($homeserver eq 'no_host') {
                   8614:         my $customdata;
                   8615:         if (ref($custominfo) eq 'HASH') {
                   8616:             $customdata = &freeze_escape($custominfo);
                   8617:         }
1.1020    raeburn  8618:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8619:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  8620:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8621:                                     $customdata,$homeserver));
1.1020    raeburn  8622:     }
                   8623:     return $response;
                   8624: }
                   8625: 
1.777     albertel 8626: sub auto_validate_class_sec {
1.918     raeburn  8627:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8628:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8629:     my $ownerlist;
                   8630:     if (ref($owners) eq 'ARRAY') {
                   8631:         $ownerlist = join(',',@{$owners});
                   8632:     } else {
                   8633:         $ownerlist = $owners;
                   8634:     }
1.773     raeburn  8635:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8636:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8637:     return $response;
                   8638: }
                   8639: 
1.1248    raeburn  8640: sub auto_crsreq_update {
                   8641:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  8642:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  8643:     my ($homeserver,%crsreqresponse);
                   8644:     if ($cdom =~ /^$match_domain$/) {
                   8645:         $homeserver = &domain($cdom,'primary');
                   8646:     }
                   8647:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8648:         my $info;
                   8649:         if (ref($inbound) eq 'HASH') {
                   8650:             $info = &freeze_escape($inbound);
                   8651:         }
                   8652:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8653:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8654:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  8655:                             &escape($title).':'.&escape($code).':'.
                   8656:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   8657:                             $homeserver);
1.1248    raeburn  8658:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8659:             my @items = split(/&/,$response);
                   8660:             foreach my $item (@items) {
                   8661:                 my ($key,$value) = split('=',$item);
                   8662:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8663:             }
                   8664:         }
                   8665:     }
                   8666:     return \%crsreqresponse;
                   8667: }
                   8668: 
1.1305    raeburn  8669: sub auto_export_grades {
1.1309    raeburn  8670:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   8671:     my ($homeserver,%exportresponse);
                   8672:     if ($cdom =~ /^$match_domain$/) {
                   8673:         $homeserver = &domain($cdom,'primary');
                   8674:     }
                   8675:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8676:         my $info;
                   8677:         if (ref($inforef) eq 'HASH') {
                   8678:             $info = &freeze_escape($inforef);
                   8679:         }
                   8680:         if (ref($gradesref) eq 'HASH') {
                   8681:             my $grades = &freeze_escape($gradesref);
                   8682:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   8683:                                 $info.':'.$grades,$homeserver);
                   8684:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   8685:                 my @items = split(/&/,$response);
                   8686:                 foreach my $item (@items) {
                   8687:                     my ($key,$value) = split('=',$item);
                   8688:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   8689:                 }
                   8690:             }
                   8691:         }
                   8692:     }
                   8693:     return \%exportresponse;
1.1305    raeburn  8694: }
                   8695: 
1.1287    raeburn  8696: sub check_instcode_cloning {
                   8697:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   8698:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8699:         return;
                   8700:     }
                   8701:     my $canclone;
                   8702:     if (@{$code_order} > 0) {
                   8703:         my $instcoderegexp ='^';
                   8704:         my @clonecodes = split(/\&/,$cloner);
                   8705:         foreach my $item (@{$code_order}) {
                   8706:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   8707:                 foreach my $pair (@clonecodes) {
                   8708:                     my ($key,$val) = split(/\=/,$pair,2);
                   8709:                     $val = &unescape($val);
                   8710:                     if ($key eq $item) {
                   8711:                         $instcoderegexp .= '('.$val.')';
                   8712:                         last;
                   8713:                     }
                   8714:                 }
                   8715:             } else {
                   8716:                 $instcoderegexp .= $codedefaults->{$item};
                   8717:             }
                   8718:         }
                   8719:         $instcoderegexp .= '$';
                   8720:         my (@from,@to);
                   8721:         eval {
                   8722:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8723:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8724:         };
                   8725:         if ((@from > 0) && (@to > 0)) {
                   8726:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8727:             if (!@diffs) {
                   8728:                 $canclone = 1;
                   8729:             }
                   8730:         }
                   8731:     }
                   8732:     return $canclone;
                   8733: }
                   8734: 
                   8735: sub default_instcode_cloning {
                   8736:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   8737:     my (%codedefaults,@code_order,$canclone);
                   8738:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   8739:         %codedefaults = %{$codedefaultsref};
                   8740:         @code_order = @{$codeorderref};
                   8741:     } elsif ($clonedom) {
                   8742:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   8743:     }
                   8744:     if (($domdefclone) && (@code_order)) {
                   8745:         my @clonecodes = split(/\+/,$domdefclone);
                   8746:         my $instcoderegexp ='^';
                   8747:         foreach my $item (@code_order) {
                   8748:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   8749:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   8750:             } else {
                   8751:                 $instcoderegexp .= $codedefaults{$item};
                   8752:             }
                   8753:         }
                   8754:         $instcoderegexp .= '$';
                   8755:         my (@from,@to);
                   8756:         eval {
                   8757:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8758:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8759:         };
                   8760:         if ((@from > 0) && (@to > 0)) {
                   8761:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8762:             if (!@diffs) {
                   8763:                 $canclone = 1;
                   8764:             }
                   8765:         }
                   8766:     }
                   8767:     return $canclone;
                   8768: }
                   8769: 
1.679     raeburn  8770: # ------------------------------------------------------- Course Group routines
                   8771: 
                   8772: sub get_coursegroups {
1.809     raeburn  8773:     my ($cdom,$cnum,$group,$namespace) = @_;
                   8774:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  8775: }
                   8776: 
1.679     raeburn  8777: sub modify_coursegroup {
                   8778:     my ($cdom,$cnum,$groupsettings) = @_;
                   8779:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   8780: }
                   8781: 
1.809     raeburn  8782: sub toggle_coursegroup_status {
                   8783:     my ($cdom,$cnum,$group,$action) = @_;
                   8784:     my ($from_namespace,$to_namespace);
                   8785:     if ($action eq 'delete') {
                   8786:         $from_namespace = 'coursegroups';
                   8787:         $to_namespace = 'deleted_groups';
                   8788:     } else {
                   8789:         $from_namespace = 'deleted_groups';
                   8790:         $to_namespace = 'coursegroups';
                   8791:     }
                   8792:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  8793:     if (my $tmp = &error(%curr_group)) {
                   8794:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   8795:         return ('read error',$tmp);
                   8796:     } else {
                   8797:         my %savedsettings = %curr_group; 
1.809     raeburn  8798:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  8799:         my $deloutcome;
                   8800:         if ($result eq 'ok') {
1.809     raeburn  8801:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  8802:         } else {
                   8803:             return ('write error',$result);
                   8804:         }
                   8805:         if ($deloutcome eq 'ok') {
                   8806:             return 'ok';
                   8807:         } else {
                   8808:             return ('delete error',$deloutcome);
                   8809:         }
                   8810:     }
                   8811: }
                   8812: 
1.679     raeburn  8813: sub modify_group_roles {
1.957     raeburn  8814:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  8815:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   8816:     my $role = 'gr/'.&escape($userprivs);
                   8817:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  8818:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  8819:     if ($result eq 'ok') {
                   8820:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   8821:     }
1.679     raeburn  8822:     return $result;
                   8823: }
                   8824: 
                   8825: sub modify_coursegroup_membership {
                   8826:     my ($cdom,$cnum,$membership) = @_;
                   8827:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   8828:     return $result;
                   8829: }
                   8830: 
1.682     raeburn  8831: sub get_active_groups {
                   8832:     my ($udom,$uname,$cdom,$cnum) = @_;
                   8833:     my $now = time;
                   8834:     my %groups = ();
                   8835:     foreach my $key (keys(%env)) {
1.811     albertel 8836:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  8837:             my ($start,$end) = split(/\./,$env{$key});
                   8838:             if (($end!=0) && ($end<$now)) { next; }
                   8839:             if (($start!=0) && ($start>$now)) { next; }
                   8840:             if ($1 eq $cdom && $2 eq $cnum) {
                   8841:                 $groups{$3} = $env{$key} ;
                   8842:             }
                   8843:         }
                   8844:     }
                   8845:     return %groups;
                   8846: }
                   8847: 
1.683     raeburn  8848: sub get_group_membership {
                   8849:     my ($cdom,$cnum,$group) = @_;
                   8850:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   8851: }
                   8852: 
                   8853: sub get_users_groups {
                   8854:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  8855:     my @usersgroups;
1.683     raeburn  8856:     my $cachetime=1800;
                   8857: 
                   8858:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  8859:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   8860:     if (defined($cached)) {
1.734     albertel 8861:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  8862:     } else {  
                   8863:         $grouplist = '';
1.816     raeburn  8864:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  8865:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  8866:         my $access_end = $env{'course.'.$courseid.
                   8867:                               '.default_enrollment_end_date'};
                   8868:         my $now = time;
                   8869:         foreach my $key (keys(%roleshash)) {
                   8870:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   8871:                 my $group = $1;
                   8872:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   8873:                     my $start = $2;
                   8874:                     my $end = $1;
                   8875:                     if ($start == -1) { next; } # deleted from group
                   8876:                     if (($start!=0) && ($start>$now)) { next; }
                   8877:                     if (($end!=0) && ($end<$now)) {
                   8878:                         if ($access_end && $access_end < $now) {
                   8879:                             if ($access_end - $end < 86400) {
                   8880:                                 push(@usersgroups,$group);
1.733     raeburn  8881:                             }
                   8882:                         }
1.817     raeburn  8883:                         next;
1.733     raeburn  8884:                     }
1.817     raeburn  8885:                     push(@usersgroups,$group);
1.683     raeburn  8886:                 }
                   8887:             }
                   8888:         }
1.817     raeburn  8889:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8890:         $grouplist = join(':',@usersgroups);
                   8891:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8892:     }
1.733     raeburn  8893:     return @usersgroups;
1.683     raeburn  8894: }
                   8895: 
                   8896: sub devalidate_getgroups_cache {
                   8897:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8898:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8899: 
1.683     raeburn  8900:     my $hashid="$udom:$uname:$courseid";
                   8901:     &devalidate_cache_new('getgroups',$hashid);
                   8902: }
                   8903: 
1.12      www      8904: # ------------------------------------------------------------------ Plain Text
                   8905: 
                   8906: sub plaintext {
1.988     raeburn  8907:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8908:     if ($short =~ m{^cr/}) {
1.758     albertel 8909: 	return (split('/',$short))[-1];
                   8910:     }
1.742     raeburn  8911:     if (!defined($cid)) {
                   8912:         $cid = $env{'request.course.id'};
                   8913:     }
                   8914:     my %rolenames = (
1.1008    raeburn  8915:                       Course    => 'std',
                   8916:                       Community => 'alt1',
1.1305    raeburn  8917:                       Placement => 'std',
1.742     raeburn  8918:                     );
1.1037    raeburn  8919:     if ($cid ne '') {
                   8920:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8921:             unless ($forcedefault) {
                   8922:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8923:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8924:                 return &Apache::lonlocal::mt($roletext);
                   8925:             }
                   8926:         }
                   8927:     }
                   8928:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8929:         (defined($rolenames{$type})) && 
                   8930:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8931:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8932:     } elsif ($cid ne '') {
                   8933:         my $crstype = $env{'course.'.$cid.'.type'};
                   8934:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8935:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8936:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8937:         }
1.742     raeburn  8938:     }
1.1037    raeburn  8939:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8940: }
                   8941: 
                   8942: # ----------------------------------------------------------------- Assign Role
                   8943: 
                   8944: sub assignrole {
1.957     raeburn  8945:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8946:         $context)=@_;
1.21      www      8947:     my $mrole;
                   8948:     if ($role =~ /^cr\//) {
1.393     www      8949:         my $cwosec=$url;
1.811     albertel 8950:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8951: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8952:            my $refused = 1;
                   8953:            if ($context eq 'requestcourses') {
                   8954:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8955:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8956:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8957:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8958:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8959:                            if ($crsenv{'internal.courseowner'} eq
                   8960:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8961:                                $refused = '';
                   8962:                            }
                   8963:                        }
                   8964:                    }
                   8965:                }
                   8966:            }
                   8967:            if ($refused) {
                   8968:                &logthis('Refused custom assignrole: '.
                   8969:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8970:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8971:                return 'refused';
                   8972:            }
1.104     www      8973:         }
1.21      www      8974:         $mrole='cr';
1.678     raeburn  8975:     } elsif ($role =~ /^gr\//) {
                   8976:         my $cwogrp=$url;
1.811     albertel 8977:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8978:         unless (&allowed('mdg',$cwogrp)) {
                   8979:             &logthis('Refused group assignrole: '.
                   8980:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   8981:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   8982:             return 'refused';
                   8983:         }
                   8984:         $mrole='gr';
1.21      www      8985:     } else {
1.82      www      8986:         my $cwosec=$url;
1.811     albertel 8987:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  8988:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   8989:             my $refused;
                   8990:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   8991:                 if (!(&allowed('c'.$role,$url))) {
                   8992:                     $refused = 1;
                   8993:                 }
                   8994:             } else {
                   8995:                 $refused = 1;
                   8996:             }
1.947     raeburn  8997:             if ($refused) {
1.1045    raeburn  8998:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8999:                 if (!$selfenroll && $context eq 'course') {
                   9000:                     my %crsenv;
                   9001:                     if ($role eq 'cc' || $role eq 'co') {
                   9002:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9003:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9004:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9005:                                 if ($crsenv{'internal.courseowner'} eq 
                   9006:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9007:                                     $refused = '';
                   9008:                                 }
                   9009:                             }
                   9010:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9011:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9012:                                 if ($crsenv{'internal.courseowner'} eq 
                   9013:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9014:                                     $refused = '';
                   9015:                                 }
                   9016:                             }
                   9017:                         }
                   9018:                     }
                   9019:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  9020:                     $refused = '';
1.1017    raeburn  9021:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9022:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9023:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9024:                         my $wrongcc;
                   9025:                         if ($cnum =~ /^$match_community$/) {
                   9026:                             $wrongcc = 1 if ($role eq 'cc');
                   9027:                         } else {
                   9028:                             $wrongcc = 1 if ($role eq 'co');
                   9029:                         }
                   9030:                         unless ($wrongcc) {
                   9031:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9032:                             if ($crsenv{'internal.courseowner'} eq 
                   9033:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9034:                                 $refused = '';
                   9035:                             }
1.1017    raeburn  9036:                         }
                   9037:                     }
1.1183    raeburn  9038:                 } elsif ($context eq 'requestauthor') {
                   9039:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   9040:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9041:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9042:                             $refused = '';
                   9043:                         } else {
                   9044:                             my %domdefaults = &get_domain_defaults($udom);
                   9045:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9046:                                 my $checkbystatus;
                   9047:                                 if ($env{'user.adv'}) { 
                   9048:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9049:                                     if ($disposition eq 'automatic') {
                   9050:                                         $refused = '';
                   9051:                                     } elsif ($disposition eq '') {
                   9052:                                         $checkbystatus = 1;
                   9053:                                     } 
                   9054:                                 } else {
                   9055:                                     $checkbystatus = 1;
                   9056:                                 }
                   9057:                                 if ($checkbystatus) {
                   9058:                                     if ($env{'environment.inststatus'}) {
                   9059:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9060:                                         foreach my $type (@inststatuses) {
                   9061:                                             if (($type ne '') &&
                   9062:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9063:                                                 $refused = '';
                   9064:                                             }
                   9065:                                         }
                   9066:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9067:                                         $refused = '';
                   9068:                                     }
                   9069:                                 }
                   9070:                             }
                   9071:                         }
                   9072:                     }
1.1017    raeburn  9073:                 }
                   9074:                 if ($refused) {
1.947     raeburn  9075:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9076:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9077: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9078:                     return 'refused';
                   9079:                 }
1.932     raeburn  9080:             }
1.1131    raeburn  9081:         } elsif ($role eq 'au') {
                   9082:             if ($url ne '/'.$udom.'/') {
                   9083:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9084:                          ' to assign author role for '.$uname.':'.$udom.
                   9085:                          ' in domain: '.$url.' refused (wrong domain).');
                   9086:                 return 'refused';
                   9087:             }
1.104     www      9088:         }
1.21      www      9089:         $mrole=$role;
                   9090:     }
1.620     albertel 9091:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9092:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9093:     if ($end) { $command.='_'.$end; }
1.21      www      9094:     if ($start) {
                   9095: 	if ($end) { 
1.81      www      9096:            $command.='_'.$start; 
1.21      www      9097:         } else {
1.81      www      9098:            $command.='_0_'.$start;
1.21      www      9099:         }
                   9100:     }
1.739     raeburn  9101:     my $origstart = $start;
                   9102:     my $origend = $end;
1.957     raeburn  9103:     my $delflag;
1.357     www      9104: # actually delete
                   9105:     if ($deleteflag) {
1.373     www      9106: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9107: # modify command to delete the role
1.620     albertel 9108:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9109:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9110: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9111: # set start and finish to negative values for userrolelog
                   9112:            $start=-1;
                   9113:            $end=-1;
1.957     raeburn  9114:            $delflag = 1;
1.357     www      9115:         }
                   9116:     }
                   9117: # send command
1.349     www      9118:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9119: # log new user role if status is ok
1.349     www      9120:     if ($answer eq 'ok') {
1.663     raeburn  9121: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  9122:         if (($role eq 'cc') || ($role eq 'in') ||
                   9123:             ($role eq 'ep') || ($role eq 'ad') ||
                   9124:             ($role eq 'ta') || ($role eq 'st') ||
                   9125:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9126:             ($role eq 'co')) {
1.1200    raeburn  9127: # for course roles, perform group memberships changes triggered by role change.
                   9128:             unless ($role =~ /^gr/) {
                   9129:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9130:                                                  $origstart,$selfenroll,$context);
                   9131:             }
1.1184    raeburn  9132:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9133:                            $selfenroll,$context);
                   9134:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334  ! raeburn  9135:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
        !          9136:                  ($role eq 'da')) {
1.1184    raeburn  9137:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9138:                            $context);
                   9139:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9140:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9141:                              $context); 
                   9142:         }
1.1053    raeburn  9143:         if ($role eq 'cc') {
                   9144:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9145:         }
1.349     www      9146:     }
                   9147:     return $answer;
1.169     harris41 9148: }
                   9149: 
1.1053    raeburn  9150: sub autoupdate_coowners {
                   9151:     my ($url,$end,$start,$uname,$udom) = @_;
                   9152:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9153:     if (($cdom ne '') && ($cnum ne '')) {
                   9154:         my $now = time;
                   9155:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9156:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9157:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9158:             my $instcode = $coursehash{'internal.coursecode'};
                   9159:             if ($instcode ne '') {
1.1056    raeburn  9160:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9161:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9162:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9163:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9164:                         if ($result eq 'valid') {
                   9165:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9166:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9167:                                     push(@newcoowners,$coowner);
                   9168:                                 }
                   9169:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9170:                                     push(@newcoowners,$uname.':'.$udom);
                   9171:                                 }
                   9172:                                 @newcoowners = sort(@newcoowners);
                   9173:                             } else {
                   9174:                                 push(@newcoowners,$uname.':'.$udom);
                   9175:                             }
                   9176:                         } else {
                   9177:                             if ($coursehash{'internal.co-owners'}) {
                   9178:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9179:                                     unless ($coowner eq $uname.':'.$udom) {
                   9180:                                         push(@newcoowners,$coowner);
                   9181:                                     }
                   9182:                                 }
                   9183:                                 unless (@newcoowners > 0) {
                   9184:                                     $delcoowners = 1;
                   9185:                                     $coowners = '';
                   9186:                                 }
                   9187:                             }
                   9188:                         }
                   9189:                         if (@newcoowners || $delcoowners) {
                   9190:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9191:                                             $delcoowners,@newcoowners);
                   9192:                         }
                   9193:                     }
                   9194:                 }
                   9195:             }
                   9196:         }
                   9197:     }
                   9198: }
                   9199: 
                   9200: sub store_coowners {
                   9201:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9202:     my $cid = $cdom.'_'.$cnum;
                   9203:     my ($coowners,$delresult,$putresult);
                   9204:     if (@newcoowners) {
                   9205:         $coowners = join(',',@newcoowners);
                   9206:         my %coownershash = (
                   9207:                             'internal.co-owners' => $coowners,
                   9208:                            );
                   9209:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9210:         if ($putresult eq 'ok') {
                   9211:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9212:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9213:             }
                   9214:         }
                   9215:     }
                   9216:     if ($delcoowners) {
                   9217:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9218:         if ($delresult eq 'ok') {
                   9219:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9220:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9221:             }
                   9222:         }
                   9223:     }
                   9224:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9225:         my %crsinfo =
                   9226:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9227:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9228:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9229:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9230:         }
                   9231:     }
                   9232: }
                   9233: 
1.169     harris41 9234: # -------------------------------------------------- Modify user authentication
1.197     www      9235: # Overrides without validation
                   9236: 
1.169     harris41 9237: sub modifyuserauth {
                   9238:     my ($udom,$uname,$umode,$upass)=@_;
                   9239:     my $uhome=&homeserver($uname,$udom);
1.197     www      9240:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   9241:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9242:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9243:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9244:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9245: 		     &escape($upass),$uhome);
1.620     albertel 9246:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9247:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9248:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9249:     &log($udom,,$uname,$uhome,
1.620     albertel 9250:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9251:                                      $env{'user.name'}.', '.$umode.
1.197     www      9252:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9253:     unless ($reply eq 'ok') {
1.197     www      9254:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9255: 	return 'error: '.$reply;
                   9256:     }   
1.170     harris41 9257:     return 'ok';
1.80      www      9258: }
                   9259: 
1.81      www      9260: # --------------------------------------------------------------- Modify a user
1.80      www      9261: 
1.81      www      9262: sub modifyuser {
1.206     matthew  9263:     my ($udom,    $uname, $uid,
                   9264:         $umode,   $upass, $first,
                   9265:         $middle,  $last,  $gene,
1.1058    raeburn  9266:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9267:     $udom= &LONCAPA::clean_domain($udom);
                   9268:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9269:     my $showcandelete = 'none';
                   9270:     if (ref($candelete) eq 'ARRAY') {
                   9271:         if (@{$candelete} > 0) {
                   9272:             $showcandelete = join(', ',@{$candelete});
                   9273:         }
                   9274:     }
1.81      www      9275:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9276:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9277: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9278:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9279:                                      ' desiredhome not specified'). 
1.620     albertel 9280:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9281:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9282:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9283:     my $newuser;
                   9284:     if ($uhome eq 'no_host') {
                   9285:         $newuser = 1;
                   9286:     }
1.80      www      9287: # ----------------------------------------------------------------- Create User
1.406     albertel 9288:     if (($uhome eq 'no_host') && 
                   9289: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      9290:         my $unhome='';
1.844     albertel 9291:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9292:             $unhome = $desiredhome;
1.620     albertel 9293: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9294: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9295:         } else { # load balancing routine for determining $unhome
1.81      www      9296:             my $loadm=10000000;
1.841     albertel 9297: 	    my %servers = &get_servers($udom,'library');
                   9298: 	    foreach my $tryserver (keys(%servers)) {
                   9299: 		my $answer=reply('load',$tryserver);
                   9300: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9301: 		    $loadm=$answer;
                   9302: 		    $unhome=$tryserver;
                   9303: 		}
1.80      www      9304: 	    }
                   9305:         }
                   9306:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9307: 	    return 'error: unable to find a home server for '.$uname.
                   9308:                    ' in domain '.$udom;
1.80      www      9309:         }
                   9310:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9311:                          &escape($upass),$unhome);
                   9312: 	unless ($reply eq 'ok') {
                   9313:             return 'error: '.$reply;
                   9314:         }   
1.230     stredwic 9315:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9316:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9317: 	    return 'error: unable verify users home machine.';
1.80      www      9318:         }
1.209     matthew  9319:     }   # End of creation of new user
1.80      www      9320: # ---------------------------------------------------------------------- Add ID
                   9321:     if ($uid) {
                   9322:        $uid=~tr/A-Z/a-z/;
                   9323:        my %uidhash=&idrget($udom,$uname);
1.196     www      9324:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9325:          && (!$forceid)) {
1.80      www      9326: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9327: 	      return 'error: user id "'.$uid.'" does not match '.
                   9328:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9329:           }
                   9330:        } else {
1.1300    raeburn  9331: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      9332:        }
                   9333:     }
                   9334: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9335:     my @tmp=&get('environment',
1.899     raeburn  9336: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9337:                     'permanentemail','inststatus'],
1.134     albertel 9338: 		   $udom,$uname);
1.1075    raeburn  9339:     my (%names,%oldnames);
1.313     matthew  9340:     if ($tmp[0] =~ m/^error:.*/) { 
                   9341:         %names=(); 
                   9342:     } else {
                   9343:         %names = @tmp;
1.1075    raeburn  9344:         %oldnames = %names;
1.313     matthew  9345:     }
1.388     www      9346: #
1.1058    raeburn  9347: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9348: # of users did not contain them), do not overwrite existing values
                   9349: # unless field is in $candelete array ref.  
                   9350: #
                   9351: 
                   9352:     my @fields = ('firstname','middlename','lastname','generation',
                   9353:                   'permanentemail','id');
                   9354:     my %newvalues;
                   9355:     if (ref($candelete) eq 'ARRAY') {
                   9356:         foreach my $field (@fields) {
                   9357:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9358:                 if ($field eq 'firstname') {
                   9359:                     $names{$field} = $first;
                   9360:                 } elsif ($field eq 'middlename') {
                   9361:                     $names{$field} = $middle;
                   9362:                 } elsif ($field eq 'lastname') {
                   9363:                     $names{$field} = $last;
                   9364:                 } elsif ($field eq 'generation') { 
                   9365:                     $names{$field} = $gene;
                   9366:                 } elsif ($field eq 'permanentemail') {
                   9367:                     $names{$field} = $email;
                   9368:                 } elsif ($field eq 'id') {
                   9369:                     $names{$field}  = $uid;
                   9370:                 }
                   9371:             }
                   9372:         }
                   9373:     }
1.388     www      9374:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9375:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9376:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9377:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9378:     if ($email) {
                   9379:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9380:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9381:     }
1.899     raeburn  9382:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9383:     if (defined($inststatus)) {
                   9384:         $names{'inststatus'} = '';
                   9385:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9386:         if (ref($usertypes) eq 'HASH') {
                   9387:             my @okstatuses; 
                   9388:             foreach my $item (split(/:/,$inststatus)) {
                   9389:                 if (defined($usertypes->{$item})) {
                   9390:                     push(@okstatuses,$item);  
                   9391:                 }
                   9392:             }
                   9393:             if (@okstatuses) {
                   9394:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9395:             }
                   9396:         }
                   9397:     }
1.1075    raeburn  9398:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9399:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9400:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9401:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9402:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9403:     } else {
                   9404:         $logmsg .= ' during self creation';
                   9405:     }
1.1075    raeburn  9406:     my $changed;
                   9407:     if ($newuser) {
                   9408:         $changed = 1;
                   9409:     } else {
                   9410:         foreach my $field (@fields) {
                   9411:             if ($names{$field} ne $oldnames{$field}) {
                   9412:                 $changed = 1;
                   9413:                 last;
                   9414:             }
                   9415:         }
                   9416:     }
                   9417:     unless ($changed) {
                   9418:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9419:         &logthis($logmsg);
                   9420:         return 'ok';
                   9421:     }
                   9422:     my $reply = &put('environment', \%names, $udom,$uname);
                   9423:     if ($reply ne 'ok') { 
                   9424:         return 'error: '.$reply;
                   9425:     }
1.1087    raeburn  9426:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9427:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9428:     }
1.1075    raeburn  9429:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9430:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9431:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9432:     &logthis($logmsg);
1.134     albertel 9433:     return 'ok';
1.80      www      9434: }
                   9435: 
1.81      www      9436: # -------------------------------------------------------------- Modify student
1.80      www      9437: 
1.81      www      9438: sub modifystudent {
                   9439:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9440:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314    raeburn  9441:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9442:     if (!$cid) {
1.620     albertel 9443: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9444: 	    return 'not_in_class';
                   9445: 	}
1.80      www      9446:     }
                   9447: # --------------------------------------------------------------- Make the user
1.81      www      9448:     my $reply=&modifyuser
1.209     matthew  9449: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9450:          $desiredhome,$email,$inststatus);
1.80      www      9451:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9452:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  9453:     # student's environment
1.297     matthew  9454:     $uid = undef if (!$forceid);
1.455     albertel 9455:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  9456:                                         $gene,$usec,$end,$start,$type,$locktype,
1.1314    raeburn  9457:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9458:     return $reply;
                   9459: }
                   9460: 
                   9461: sub modify_student_enrollment {
1.1216    raeburn  9462:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314    raeburn  9463:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9464:     my ($cdom,$cnum,$chome);
                   9465:     if (!$cid) {
1.620     albertel 9466: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9467: 	    return 'not_in_class';
                   9468: 	}
1.620     albertel 9469: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9470: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9471:     } else {
                   9472: 	($cdom,$cnum)=split(/_/,$cid);
                   9473:     }
1.620     albertel 9474:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9475:     if (!$chome) {
1.457     raeburn  9476: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9477:     }
1.455     albertel 9478:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9479:     # Make sure the user exists
1.81      www      9480:     my $uhome=&homeserver($uname,$udom);
                   9481:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9482: 	return 'error: no such user';
                   9483:     }
1.297     matthew  9484:     # Get student data if we were not given enough information
                   9485:     if (!defined($first)  || $first  eq '' || 
                   9486:         !defined($last)   || $last   eq '' || 
                   9487:         !defined($uid)    || $uid    eq '' || 
                   9488:         !defined($middle) || $middle eq '' || 
                   9489:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9490:         # They did not supply us with enough data to enroll the student, so
                   9491:         # we need to pick up more information.
1.297     matthew  9492:         my %tmp = &get('environment',
1.294     matthew  9493:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9494:                        ,$udom,$uname);
                   9495: 
1.800     albertel 9496:         #foreach my $key (keys(%tmp)) {
                   9497:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9498:         #}
1.294     matthew  9499:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9500:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9501:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9502:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9503:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9504:     }
1.556     albertel 9505:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9506:     my $user = "$uname:$udom";
                   9507:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9508:     my $reply=cput('classlist',
1.1148    raeburn  9509: 		   {$user => 
1.1314    raeburn  9510: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 9511: 		   $cdom,$cnum);
1.1148    raeburn  9512:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9513:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9514:     } else { 
1.81      www      9515: 	return 'error: '.$reply;
                   9516:     }
1.297     matthew  9517:     # Add student role to user
1.83      www      9518:     my $uurl='/'.$cid;
1.81      www      9519:     $uurl=~s/\_/\//g;
                   9520:     if ($usec) {
                   9521: 	$uurl.='/'.$usec;
                   9522:     }
1.1148    raeburn  9523:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9524:                              $selfenroll,$context);
                   9525:     if ($result ne 'ok') {
                   9526:         if ($old_entry{$user} ne '') {
                   9527:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9528:         } else {
                   9529:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9530:         }
                   9531:     }
                   9532:     return $result; 
1.21      www      9533: }
                   9534: 
1.556     albertel 9535: sub format_name {
                   9536:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9537:     my $name;
                   9538:     if ($first ne 'lastname') {
                   9539: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9540:     } else {
                   9541: 	if ($lastname=~/\S/) {
                   9542: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9543: 	    $name=~s/\s+,/,/;
                   9544: 	} else {
                   9545: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9546: 	}
                   9547:     }
                   9548:     $name=~s/^\s+//;
                   9549:     $name=~s/\s+$//;
                   9550:     $name=~s/\s+/ /g;
                   9551:     return $name;
                   9552: }
                   9553: 
1.84      www      9554: # ------------------------------------------------- Write to course preferences
                   9555: 
                   9556: sub writecoursepref {
                   9557:     my ($courseid,%prefs)=@_;
                   9558:     $courseid=~s/^\///;
                   9559:     $courseid=~s/\_/\//g;
                   9560:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9561:     my $chome=homeserver($cnum,$cdomain);
                   9562:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9563: 	return 'error: no such course';
                   9564:     }
                   9565:     my $cstring='';
1.800     albertel 9566:     foreach my $pref (keys(%prefs)) {
                   9567: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9568:     }
1.84      www      9569:     $cstring=~s/\&$//;
                   9570:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9571: }
                   9572: 
                   9573: # ---------------------------------------------------------- Make/modify course
                   9574: 
                   9575: sub createcourse {
1.741     raeburn  9576:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  9577:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      9578:     $url=&declutter($url);
                   9579:     my $cid='';
1.1028    raeburn  9580:     if ($context eq 'requestcourses') {
                   9581:         my $can_create = 0;
                   9582:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9583:         if ($udom eq $ownerdom) {
                   9584:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   9585:                                   $context)) {
                   9586:                 $can_create = 1;
                   9587:             }
                   9588:         } else {
                   9589:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9590:                                            $category);
                   9591:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   9592:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   9593:                 if (@curr > 0) {
                   9594:                     my @options = qw(approval validate autolimit);
                   9595:                     my $optregex = join('|',@options);
                   9596:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   9597:                         $can_create = 1;
                   9598:                     }
                   9599:                 }
                   9600:             }
                   9601:         }
                   9602:         if ($can_create) {
                   9603:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   9604:                 unless (&allowed('ccc',$udom)) {
                   9605:                     return 'refused'; 
                   9606:                 }
1.1017    raeburn  9607:             }
                   9608:         } else {
                   9609:             return 'refused';
                   9610:         }
1.1028    raeburn  9611:     } elsif (!&allowed('ccc',$udom)) {
                   9612:         return 'refused';
1.84      www      9613:     }
1.1011    raeburn  9614: # --------------------------------------------------------------- Get Unique ID
                   9615:     my $uname;
                   9616:     if ($cnum =~ /^$match_courseid$/) {
                   9617:         my $chome=&homeserver($cnum,$udom,'true');
                   9618:         if (($chome eq '') || ($chome eq 'no_host')) {
                   9619:             $uname = $cnum;
                   9620:         } else {
1.1038    raeburn  9621:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9622:         }
                   9623:     } else {
1.1038    raeburn  9624:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9625:     }
                   9626:     return $uname if ($uname =~ /^error/);
                   9627: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  9628:     if (!defined($course_server)) {
                   9629:         if (defined(&domain($udom,'primary'))) {
                   9630:             $course_server = &domain($udom,'primary');
                   9631:         } else {
                   9632:             $course_server = $env{'user.home'}; 
                   9633:         }
                   9634:     }
                   9635:     my %host_servers =
                   9636:         &Apache::lonnet::get_servers($udom,'library');
                   9637:     unless ($host_servers{$course_server}) {
                   9638:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  9639:     }
1.84      www      9640: # ------------------------------------------------------------- Make the course
                   9641:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  9642:                       $course_server);
1.84      www      9643:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  9644:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      9645:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9646: 	return 'error: no such course';
                   9647:     }
1.271     www      9648: # ----------------------------------------------------------------- Course made
1.516     raeburn  9649: # log existence
1.1029    raeburn  9650:     my $now = time;
1.918     raeburn  9651:     my $newcourse = {
                   9652:                     $udom.'_'.$uname => {
1.921     raeburn  9653:                                      description => $description,
                   9654:                                      inst_code   => $inst_code,
                   9655:                                      owner       => $course_owner,
                   9656:                                      type        => $crstype,
1.1029    raeburn  9657:                                      creator     => $env{'user.name'}.':'.
                   9658:                                                     $env{'user.domain'},
                   9659:                                      created     => $now,
                   9660:                                      context     => $context,
1.918     raeburn  9661:                                                 },
                   9662:                     };
1.921     raeburn  9663:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      9664: # set toplevel url
1.271     www      9665:     my $topurl=$url;
                   9666:     unless ($nonstandard) {
                   9667: # ------------------------------------------ For standard courses, make top url
                   9668:         my $mapurl=&clutter($url);
1.278     www      9669:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 9670:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      9671: <map>
                   9672: <resource id="1" type="start"></resource>
                   9673: <resource id="2" src="$mapurl"></resource>
                   9674: <resource id="3" type="finish"></resource>
                   9675: <link index="1" from="1" to="2"></link>
                   9676: <link index="2" from="2" to="3"></link>
                   9677: </map>
                   9678: ENDINITMAP
                   9679:         $topurl=&declutter(
1.638     albertel 9680:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      9681:                           );
                   9682:     }
                   9683: # ----------------------------------------------------------- Write preferences
1.84      www      9684:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  9685:                      ('description'              => $description,
                   9686:                       'url'                      => $topurl,
                   9687:                       'internal.creator'         => $env{'user.name'}.':'.
                   9688:                                                     $env{'user.domain'},
                   9689:                       'internal.created'         => $now,
                   9690:                       'internal.creationcontext' => $context)
                   9691:                     );
1.84      www      9692:     return '/'.$udom.'/'.$uname;
                   9693: }
                   9694: 
1.1011    raeburn  9695: # ------------------------------------------------------------------- Create ID
                   9696: sub generate_coursenum {
1.1038    raeburn  9697:     my ($udom,$crstype) = @_;
1.1011    raeburn  9698:     my $domdesc = &domain($udom);
                   9699:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  9700:     my $first;
                   9701:     if ($crstype eq 'Community') {
                   9702:         $first = '0';
                   9703:     } else {
                   9704:         $first = int(1+rand(9)); 
                   9705:     } 
                   9706:     my $uname=$first.
1.1011    raeburn  9707:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9708:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9709:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9710: # ----------------------------------------------- Make sure that does not exist
                   9711:     my $uhome=&homeserver($uname,$udom,'true');
                   9712:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  9713:         if ($crstype eq 'Community') {
                   9714:             $first = '0';
                   9715:         } else {
                   9716:             $first = int(1+rand(9));
                   9717:         }
                   9718:         $uname=$first.
1.1011    raeburn  9719:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9720:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9721:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9722:         $uhome=&homeserver($uname,$udom,'true');
                   9723:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   9724:             return 'error: unable to generate unique course-ID';
                   9725:         }
                   9726:     }
                   9727:     return $uname;
                   9728: }
                   9729: 
1.813     albertel 9730: sub is_course {
1.1167    droeschl 9731:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   9732:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   9733: 
                   9734:     return unless $cdom and $cnum;
                   9735: 
                   9736:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   9737:         '.');
                   9738: 
1.1219    raeburn  9739:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 9740:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 9741: }
                   9742: 
1.1015    raeburn  9743: sub store_userdata {
                   9744:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  9745:     my $result;
1.1016    raeburn  9746:     if ($datakey ne '') {
1.1013    raeburn  9747:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  9748:             if ($udom eq '' || $uname eq '') {
                   9749:                 $udom = $env{'user.domain'};
                   9750:                 $uname = $env{'user.name'};
                   9751:             }
                   9752:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  9753:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   9754:                 $result = 'error: no_host';
                   9755:             } else {
                   9756:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   9757:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   9758: 
                   9759:                 my $namevalue='';
                   9760:                 foreach my $key (keys(%{$storehash})) {
                   9761:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   9762:                 }
                   9763:                 $namevalue=~s/\&$//;
1.1224    raeburn  9764:                 unless ($namespace eq 'courserequests') {
                   9765:                     $datakey = &escape($datakey);
                   9766:                 }
1.1105    raeburn  9767:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   9768:                                   $namevalue,$uhome);
1.1013    raeburn  9769:             }
                   9770:         } else {
                   9771:             $result = 'error: data to store was not a hash reference'; 
                   9772:         }
                   9773:     } else {
                   9774:         $result= 'error: invalid requestkey'; 
                   9775:     }
                   9776:     return $result;
                   9777: }
                   9778: 
1.21      www      9779: # ---------------------------------------------------------- Assign Custom Role
                   9780: 
                   9781: sub assigncustomrole {
1.957     raeburn  9782:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9783:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  9784:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      9785: }
                   9786: 
                   9787: # ----------------------------------------------------------------- Revoke Role
                   9788: 
                   9789: sub revokerole {
1.957     raeburn  9790:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9791:     my $now=time;
1.965     raeburn  9792:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      9793: }
                   9794: 
                   9795: # ---------------------------------------------------------- Revoke Custom Role
                   9796: 
                   9797: sub revokecustomrole {
1.957     raeburn  9798:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9799:     my $now=time;
1.357     www      9800:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  9801:            $deleteflag,$selfenroll,$context);
1.17      www      9802: }
                   9803: 
1.533     banghart 9804: # ------------------------------------------------------------ Disk usage
1.535     albertel 9805: sub diskusage {
1.955     raeburn  9806:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   9807:     $directorypath =~ s/\/$//;
                   9808:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   9809:                        .&escape($getpropath).':'.&escape($uname).':'
                   9810:                        .&escape($udom),homeserver($uname,$udom));
                   9811:     if ($listing eq 'unknown_cmd') {
                   9812:         if ($getpropath) {
                   9813:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   9814:         }
                   9815:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   9816:     }
1.514     albertel 9817:     return $listing;
1.512     banghart 9818: }
                   9819: 
1.566     banghart 9820: sub is_locked {
1.1096    raeburn  9821:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 9822:     my @check;
                   9823:     my $is_locked;
1.1093    raeburn  9824:     push (@check,$file_name);
1.613     albertel 9825:     my %locked = &get('file_permissions',\@check,
1.620     albertel 9826: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 9827:     my ($tmp)=keys(%locked);
                   9828:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  9829:     
1.566     banghart 9830:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  9831:         $is_locked = 'false';
                   9832:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  9833:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  9834:                $is_locked = 'true';
1.1096    raeburn  9835:                if (ref($which) eq 'ARRAY') {
                   9836:                    push(@{$which},$entry);
                   9837:                } else {
                   9838:                    last;
                   9839:                }
1.745     raeburn  9840:            }
                   9841:        }
1.566     banghart 9842:     } else {
                   9843:         $is_locked = 'false';
                   9844:     }
1.1093    raeburn  9845:     return $is_locked;
1.566     banghart 9846: }
                   9847: 
1.759     albertel 9848: sub declutter_portfile {
                   9849:     my ($file) = @_;
1.833     albertel 9850:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 9851:     return $file;
                   9852: }
                   9853: 
1.559     banghart 9854: # ------------------------------------------------------------- Mark as Read Only
                   9855: 
                   9856: sub mark_as_readonly {
                   9857:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 9858:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9859:     my ($tmp)=keys(%current_permissions);
                   9860:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 9861:     foreach my $file (@{$files}) {
1.759     albertel 9862: 	$file = &declutter_portfile($file);
1.561     banghart 9863:         push(@{$current_permissions{$file}},$what);
1.559     banghart 9864:     }
1.613     albertel 9865:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9866:     return;
                   9867: }
                   9868: 
1.572     banghart 9869: # ------------------------------------------------------------Save Selected Files
                   9870: 
                   9871: sub save_selected_files {
                   9872:     my ($user, $path, @files) = @_;
                   9873:     my $filename = $user."savedfiles";
1.573     banghart 9874:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 9875:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 9876:     foreach my $file (@files) {
1.620     albertel 9877:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 9878:     }
                   9879:     foreach my $file (@other_files) {
1.574     banghart 9880:         print (OUT $file."\n");
1.572     banghart 9881:     }
1.574     banghart 9882:     close (OUT);
1.572     banghart 9883:     return 'ok';
                   9884: }
                   9885: 
1.574     banghart 9886: sub clear_selected_files {
                   9887:     my ($user) = @_;
                   9888:     my $filename = $user."savedfiles";
1.1117    foxr     9889:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 9890:     print (OUT undef);
                   9891:     close (OUT);
                   9892:     return ("ok");    
                   9893: }
                   9894: 
1.572     banghart 9895: sub files_in_path {
                   9896:     my ($user, $path) = @_;
                   9897:     my $filename = $user."savedfiles";
                   9898:     my %return_files;
1.1117    foxr     9899:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 9900:     while (my $line_in = <IN>) {
1.574     banghart 9901:         chomp ($line_in);
                   9902:         my @paths_and_file = split (m!/!, $line_in);
                   9903:         my $file_part = pop (@paths_and_file);
                   9904:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9905:         $path_part.='/';
                   9906:         my $path_and_file = $path_part.$file_part;
                   9907:         if ($path_part eq $path) {
                   9908:             $return_files{$file_part}= 'selected';
                   9909:         }
                   9910:     }
1.574     banghart 9911:     close (IN);
                   9912:     return (\%return_files);
1.572     banghart 9913: }
                   9914: 
                   9915: # called in portfolio select mode, to show files selected NOT in current directory
                   9916: sub files_not_in_path {
                   9917:     my ($user, $path) = @_;
                   9918:     my $filename = $user."savedfiles";
                   9919:     my @return_files;
                   9920:     my $path_part;
1.1117    foxr     9921:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 9922:     while (my $line = <IN>) {
1.572     banghart 9923:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9924:         my @paths_and_file = split(m|/|, $line);
                   9925:         my $file_part = pop(@paths_and_file);
                   9926:         chomp($file_part);
                   9927:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9928:         $path_part .= '/';
                   9929:         my $path_and_file = $path_part.$file_part;
                   9930:         if ($path_part ne $path) {
1.800     albertel 9931:             push(@return_files, ($path_and_file));
1.572     banghart 9932:         }
                   9933:     }
1.800     albertel 9934:     close(OUT);
1.574     banghart 9935:     return (@return_files);
1.572     banghart 9936: }
                   9937: 
1.1273    raeburn  9938: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   9939:  
                   9940: sub portfiles_versioning {
                   9941:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   9942:     my $portfolio_root = '/userfiles/portfolio';
                   9943:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   9944:     foreach my $file (@{$portfiles}) {
                   9945:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   9946:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   9947:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   9948:         my $getpropath = 1;
                   9949:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   9950:                                              $stu_name,$getpropath);
                   9951:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   9952:         my $new_answer = 
                   9953:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   9954:         if ($new_answer ne 'problem getting file') {
                   9955:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   9956:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   9957:                               [$symb,$env{'request.course.id'},'graded']);
                   9958:         }
                   9959:     }
                   9960: }
                   9961: 
                   9962: sub get_next_version {
                   9963:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   9964:     my $version;
                   9965:     if (ref($dir_list) eq 'ARRAY') {
                   9966:         foreach my $row (@{$dir_list}) {
                   9967:             my ($file) = split(/\&/,$row,2);
                   9968:             my ($file_name,$file_version,$file_ext) =
                   9969:                 &file_name_version_ext($file);
                   9970:             if (($file_name eq $answer_name) &&
                   9971:                 ($file_ext eq $answer_ext)) {
                   9972:                      # gets here if filename and extension match,
                   9973:                      # regardless of version
                   9974:                 if ($file_version ne '') {
                   9975:                     # a versioned file is found  so save it for later
                   9976:                     if ($file_version > $version) {
                   9977:                         $version = $file_version;
                   9978:                     }
                   9979:                 }
                   9980:             }
                   9981:         }
                   9982:     }
                   9983:     $version ++;
                   9984:     return($version);
                   9985: }
                   9986: 
                   9987: sub version_selected_portfile {
                   9988:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   9989:     my ($answer_name,$answer_ver,$answer_ext) =
                   9990:         &file_name_version_ext($file_name);
                   9991:     my $new_answer;
                   9992:     $env{'form.copy'} =
                   9993:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   9994:     if($env{'form.copy'} eq '-1') {
                   9995:         $new_answer = 'problem getting file';
                   9996:     } else {
                   9997:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   9998:         my $copy_result = 
                   9999:             &finishuserfileupload($stu_name,$domain,'copy',
                   10000:                                   '/portfolio'.$directory.$new_answer);
                   10001:     }
                   10002:     undef($env{'form.copy'});
                   10003:     return ($new_answer);
                   10004: }
                   10005: 
                   10006: sub file_name_version_ext {
                   10007:     my ($file)=@_;
                   10008:     my @file_parts = split(/\./, $file);
                   10009:     my ($name,$version,$ext);
                   10010:     if (@file_parts > 1) {
                   10011:         $ext=pop(@file_parts);
                   10012:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   10013:             $version=pop(@file_parts);
                   10014:         }
                   10015:         $name=join('.',@file_parts);
                   10016:     } else {
                   10017:         $name=join('.',@file_parts);
                   10018:     }
                   10019:     return($name,$version,$ext);
                   10020: }
                   10021: 
1.745     raeburn  10022: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10023: 
1.745     raeburn  10024: sub get_portfile_permissions {
                   10025:     my ($domain,$user) = @_;
1.613     albertel 10026:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10027:     my ($tmp)=keys(%current_permissions);
                   10028:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10029:     return \%current_permissions;
                   10030: }
                   10031: 
                   10032: #---------------------------------------------Get portfolio file access controls
                   10033: 
1.749     raeburn  10034: sub get_access_controls {
1.745     raeburn  10035:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10036:     my %access;
                   10037:     my $real_file = $file;
                   10038:     $file =~ s/\.meta$//;
1.745     raeburn  10039:     if (defined($file)) {
1.749     raeburn  10040:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10041:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10042:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10043:             }
                   10044:         }
1.745     raeburn  10045:     } else {
1.749     raeburn  10046:         foreach my $key (keys(%{$current_permissions})) {
                   10047:             if ($key =~ /\0accesscontrol$/) {
                   10048:                 if (defined($group)) {
                   10049:                     if ($key !~ m-^\Q$group\E/-) {
                   10050:                         next;
                   10051:                     }
                   10052:                 }
                   10053:                 my ($fullpath) = split(/\0/,$key);
                   10054:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10055:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10056:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10057:                     }
                   10058:                 }
                   10059:             }
                   10060:         }
                   10061:     }
                   10062:     return %access;
                   10063: }
                   10064: 
                   10065: sub modify_access_controls {
                   10066:     my ($file_name,$changes,$domain,$user)=@_;
                   10067:     my ($outcome,$deloutcome);
                   10068:     my %store_permissions;
                   10069:     my %new_values;
                   10070:     my %new_control;
                   10071:     my %translation;
                   10072:     my @deletions = ();
                   10073:     my $now = time;
                   10074:     if (exists($$changes{'activate'})) {
                   10075:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10076:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10077:             my $numnew = scalar(@newitems);
                   10078:             for (my $i=0; $i<$numnew; $i++) {
                   10079:                 my $newkey = $newitems[$i];
                   10080:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10081:                 if ($newkey =~ /^\d+:/) { 
                   10082:                     $newkey =~ s/^(\d+)/$newid/;
                   10083:                     $translation{$1} = $newid;
                   10084:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10085:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10086:                     $translation{$1} = $newid;
                   10087:                 }
1.749     raeburn  10088:                 $new_values{$file_name."\0".$newkey} = 
                   10089:                                           $$changes{'activate'}{$newitems[$i]};
                   10090:                 $new_control{$newkey} = $now;
                   10091:             }
                   10092:         }
                   10093:     }
                   10094:     my %todelete;
                   10095:     my %changed_items;
                   10096:     foreach my $action ('delete','update') {
                   10097:         if (exists($$changes{$action})) {
                   10098:             if (ref($$changes{$action}) eq 'HASH') {
                   10099:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10100:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10101:                     if ($action eq 'delete') { 
                   10102:                         $todelete{$itemnum} = 1;
                   10103:                     } else {
                   10104:                         $changed_items{$itemnum} = $key;
                   10105:                     }
                   10106:                 }
1.745     raeburn  10107:             }
                   10108:         }
1.749     raeburn  10109:     }
                   10110:     # get lock on access controls for file.
                   10111:     my $lockhash = {
                   10112:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10113:                                                        ':'.$env{'user.domain'},
                   10114:                    }; 
                   10115:     my $tries = 0;
                   10116:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10117:    
1.1288    damieng  10118:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10119:         $tries ++;
1.1289    damieng  10120:         sleep(0.1);
1.749     raeburn  10121:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10122:     }
                   10123:     if ($gotlock eq 'ok') {
                   10124:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10125:         my ($tmp)=keys(%curr_permissions);
                   10126:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10127:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10128:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10129:             if (ref($curr_controls) eq 'HASH') {
                   10130:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10131:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10132:                     if (defined($todelete{$itemnum})) {
                   10133:                         push(@deletions,$file_name."\0".$control_item);
                   10134:                     } else {
                   10135:                         if (defined($changed_items{$itemnum})) {
                   10136:                             $new_control{$changed_items{$itemnum}} = $now;
                   10137:                             push(@deletions,$file_name."\0".$control_item);
                   10138:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10139:                         } else {
                   10140:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10141:                         }
                   10142:                     }
1.745     raeburn  10143:                 }
                   10144:             }
                   10145:         }
1.970     raeburn  10146:         my ($group);
                   10147:         if (&is_course($domain,$user)) {
                   10148:             ($group,my $file) = split(/\//,$file_name,2);
                   10149:         }
1.749     raeburn  10150:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10151:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10152:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10153:         #  remove lock
                   10154:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10155:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10156:         my $sqlresult =
1.970     raeburn  10157:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10158:                                     $group);
1.749     raeburn  10159:     } else {
                   10160:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10161:     }
1.749     raeburn  10162:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10163: }
                   10164: 
1.827     raeburn  10165: sub make_public_indefinitely {
1.1271    raeburn  10166:     my (@requrl) = @_;
                   10167:     return &automated_portfile_access('public',\@requrl);
                   10168: }
                   10169: 
                   10170: sub automated_portfile_access {
                   10171:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  10172:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   10173:         return 'invalid';
                   10174:     }
1.1271    raeburn  10175:     my %urls;
                   10176:     if (ref($addsref) eq 'ARRAY') {
                   10177:         foreach my $requrl (@{$addsref}) {
                   10178:             if (&is_portfolio_url($requrl)) {
                   10179:                 unless (exists($urls{$requrl})) {
                   10180:                     $urls{$requrl} = 'add';
                   10181:                 }
                   10182:             }
                   10183:         }
                   10184:     }
                   10185:     if (ref($delsref) eq 'ARRAY') {
                   10186:         foreach my $requrl (@{$delsref}) { 
                   10187:             if (&is_portfolio_url($requrl)) {
                   10188:                 unless (exists($urls{$requrl})) {
                   10189:                     $urls{$requrl} = 'delete'; 
                   10190:                 }
                   10191:             }
                   10192:         }
                   10193:     }
                   10194:     unless (keys(%urls)) {
                   10195:         return 'invalid';
                   10196:     }
                   10197:     my $ip;
                   10198:     if ($accesstype eq 'ip') {
                   10199:         if (ref($info) eq 'HASH') {
                   10200:             if ($info->{'ip'} ne '') {
                   10201:                 $ip = $info->{'ip'};
                   10202:             }
                   10203:         }
                   10204:         if ($ip eq '') {
                   10205:             return 'invalid';
                   10206:         }
                   10207:     }
                   10208:     my $errors;
1.827     raeburn  10209:     my $now = time;
1.1271    raeburn  10210:     my %current_perms;
                   10211:     foreach my $requrl (sort(keys(%urls))) {
                   10212:         my $action;
                   10213:         if ($urls{$requrl} eq 'add') {
                   10214:             $action = 'activate';
                   10215:         } else {
                   10216:             $action = 'none';
                   10217:         }
                   10218:         my $aclnum = 0;
1.827     raeburn  10219:         my (undef,$udom,$unum,$file_name,$group) =
                   10220:             &parse_portfolio_url($requrl);
1.1271    raeburn  10221:         unless (exists($current_perms{$unum.':'.$udom})) {
                   10222:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   10223:         }
                   10224:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  10225:                                                    $group,$file_name);
                   10226:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10227:             my ($num,$scope,$end,$start) = 
                   10228:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  10229:             if ($scope eq $accesstype) {
                   10230:                 if (($start <= $now) && ($end == 0)) {
                   10231:                     if ($accesstype eq 'ip') {
                   10232:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   10233:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   10234:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   10235:                                     if ($urls{$requrl} eq 'add') {
                   10236:                                         $action = 'none';
                   10237:                                         last;
                   10238:                                     } else {
                   10239:                                         $action = 'delete';
                   10240:                                         $aclnum = $num;
                   10241:                                         last;
                   10242:                                     }
                   10243:                                 }
                   10244:                             }
                   10245:                         }
                   10246:                     } elsif ($accesstype eq 'public') {
                   10247:                         if ($urls{$requrl} eq 'add') {
                   10248:                             $action = 'none';
                   10249:                             last;
                   10250:                         } else {
                   10251:                             $action = 'delete';
                   10252:                             $aclnum = $num;
                   10253:                             last;
                   10254:                         }
                   10255:                     }
                   10256:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  10257:                     $action = 'update';
                   10258:                     $aclnum = $num;
1.1271    raeburn  10259:                     last;
1.827     raeburn  10260:                 }
                   10261:             }
                   10262:         }
                   10263:         if ($action eq 'none') {
1.1271    raeburn  10264:             next;
1.827     raeburn  10265:         } else {
                   10266:             my %changes;
                   10267:             my $newend = 0;
                   10268:             my $newstart = $now;
1.1271    raeburn  10269:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  10270:             $changes{$action}{$newkey} = {
1.1271    raeburn  10271:                 type => $accesstype,
1.827     raeburn  10272:                 time => {
                   10273:                     start => $newstart,
                   10274:                     end   => $newend,
                   10275:                 },
                   10276:             };
1.1271    raeburn  10277:             if ($accesstype eq 'ip') {
                   10278:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   10279:             }
1.827     raeburn  10280:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10281:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  10282:             unless ($outcome eq 'ok') {
                   10283:                 $errors .= $outcome.' ';
                   10284:             }
1.827     raeburn  10285:         }
1.1271    raeburn  10286:     }
                   10287:     if ($errors) {
                   10288:         $errors =~ s/\s$//;
                   10289:         return $errors;
1.827     raeburn  10290:     } else {
1.1271    raeburn  10291:         return 'ok';
1.827     raeburn  10292:     }
                   10293: }
                   10294: 
1.745     raeburn  10295: #------------------------------------------------------Get Marked as Read Only
                   10296: 
                   10297: sub get_marked_as_readonly {
                   10298:     my ($domain,$user,$what,$group) = @_;
                   10299:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10300:     my @readonly_files;
1.629     banghart 10301:     my $cmp1=$what;
                   10302:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10303:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10304:         if (defined($group)) {
                   10305:             if ($file_name !~ m-^\Q$group\E/-) {
                   10306:                 next;
                   10307:             }
                   10308:         }
1.561     banghart 10309:         if (ref($value) eq "ARRAY"){
                   10310:             foreach my $stored_what (@{$value}) {
1.629     banghart 10311:                 my $cmp2=$stored_what;
1.759     albertel 10312:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10313:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10314:                 }
1.629     banghart 10315:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10316:                     push(@readonly_files, $file_name);
1.745     raeburn  10317:                     last;
1.563     banghart 10318:                 } elsif (!defined($what)) {
                   10319:                     push(@readonly_files, $file_name);
1.745     raeburn  10320:                     last;
1.561     banghart 10321:                 }
                   10322:             }
1.745     raeburn  10323:         }
1.561     banghart 10324:     }
                   10325:     return @readonly_files;
                   10326: }
1.577     banghart 10327: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10328: 
1.577     banghart 10329: sub get_marked_as_readonly_hash {
1.745     raeburn  10330:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10331:     my %readonly_files;
1.745     raeburn  10332:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10333:         if (defined($group)) {
                   10334:             if ($file_name !~ m-^\Q$group\E/-) {
                   10335:                 next;
                   10336:             }
                   10337:         }
1.577     banghart 10338:         if (ref($value) eq "ARRAY"){
                   10339:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10340:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10341:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10342:                         if ($lock_descriptor eq 'graded') {
                   10343:                             $readonly_files{$file_name} = 'graded';
                   10344:                         } elsif ($lock_descriptor eq 'handback') {
                   10345:                             $readonly_files{$file_name} = 'handback';
                   10346:                         } else {
                   10347:                             if (!exists($readonly_files{$file_name})) {
                   10348:                                 $readonly_files{$file_name} = 'locked';
                   10349:                             }
                   10350:                         }
1.745     raeburn  10351:                     }
1.750     banghart 10352:                 } 
1.577     banghart 10353:             }
                   10354:         } 
                   10355:     }
                   10356:     return %readonly_files;
                   10357: }
1.559     banghart 10358: # ------------------------------------------------------------ Unmark as Read Only
                   10359: 
                   10360: sub unmark_as_readonly {
1.629     banghart 10361:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10362:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10363:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10364:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10365:     my $symb_crs = $what;
                   10366:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10367:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10368:     my ($tmp)=keys(%current_permissions);
                   10369:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10370:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10371:     foreach my $file (@readonly_files) {
1.759     albertel 10372: 	my $clean_file = &declutter_portfile($file);
                   10373: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10374: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10375:         my @new_locks;
                   10376:         my @del_keys;
                   10377:         if (ref($current_locks) eq "ARRAY"){
                   10378:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10379:                 my $compare=$locker;
1.749     raeburn  10380:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10381:                     $compare=join('',@{$locker});
1.746     raeburn  10382:                     if ($compare ne $symb_crs) {
                   10383:                         push(@new_locks, $locker);
                   10384:                     }
1.563     banghart 10385:                 }
                   10386:             }
1.650     albertel 10387:             if (scalar(@new_locks) > 0) {
1.563     banghart 10388:                 $current_permissions{$file} = \@new_locks;
                   10389:             } else {
                   10390:                 push(@del_keys, $file);
1.613     albertel 10391:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10392:                 delete($current_permissions{$file});
1.563     banghart 10393:             }
                   10394:         }
1.561     banghart 10395:     }
1.613     albertel 10396:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10397:     return;
                   10398: }
1.512     banghart 10399: 
1.17      www      10400: # ------------------------------------------------------------ Directory lister
                   10401: 
                   10402: sub dirlist {
1.955     raeburn  10403:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10404:     $uri=~s/^\///;
                   10405:     $uri=~s/\/$//;
1.253     stredwic 10406:     my ($udom, $uname);
1.955     raeburn  10407:     if ($getuserdir) {
1.253     stredwic 10408:         $udom = $userdomain;
                   10409:         $uname = $username;
1.955     raeburn  10410:     } else {
                   10411:         (undef,$udom,$uname)=split(/\//,$uri);
                   10412:         if(defined($userdomain)) {
                   10413:             $udom = $userdomain;
                   10414:         }
                   10415:         if(defined($username)) {
                   10416:             $uname = $username;
                   10417:         }
1.253     stredwic 10418:     }
1.955     raeburn  10419:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10420: 
1.955     raeburn  10421:     $dirRoot = $perlvar{'lonDocRoot'};
                   10422:     if (defined($getpropath)) {
                   10423:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10424:         $dirRoot =~ s/\/$//;
1.955     raeburn  10425:     } elsif (defined($getuserdir)) {
                   10426:         my $subdir=$uname.'__';
                   10427:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10428:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10429:                    ."/$udom/$subdir/$uname";
                   10430:     } elsif (defined($alternateRoot)) {
                   10431:         $dirRoot = $alternateRoot;
1.751     banghart 10432:     }
1.253     stredwic 10433: 
                   10434:     if($udom) {
                   10435:         if($uname) {
1.1135    raeburn  10436:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10437:             if ($uhome eq 'no_host') {
                   10438:                 return ([],'no_host');
                   10439:             }
1.955     raeburn  10440:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10441:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10442:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10443:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10444:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10445:             } else {
                   10446:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10447:             }
1.605     matthew  10448:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10449:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10450:                 @listing_results = split(/:/,$listing);
                   10451:             } else {
                   10452:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10453:             }
1.1135    raeburn  10454:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10455:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10456:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10457:                 return ([],$listing);
                   10458:             } else {
                   10459:                 return (\@listing_results);
1.1135    raeburn  10460:             }
1.955     raeburn  10461:         } elsif(!$alternateRoot) {
1.1136    raeburn  10462:             my (%allusers,%listerror);
1.841     albertel 10463: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10464:  	    foreach my $tryserver (keys(%servers)) {
                   10465:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10466:                                   &escape($udom),$tryserver);
                   10467:                 if ($listing eq 'unknown_cmd') {
                   10468: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10469: 				      $udom, $tryserver);
                   10470:                 } else {
                   10471:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10472:                 }
1.841     albertel 10473: 		if ($listing eq 'unknown_cmd') {
                   10474: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10475: 				      $udom, $tryserver);
                   10476: 		    @listing_results = split(/:/,$listing);
                   10477: 		} else {
                   10478: 		    @listing_results =
                   10479: 			map { &unescape($_); } split(/:/,$listing);
                   10480: 		}
1.1136    raeburn  10481:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10482:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10483:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10484:                     $listerror{$tryserver} = $listing;
                   10485:                 } else {
1.841     albertel 10486: 		    foreach my $line (@listing_results) {
                   10487: 			my ($entry) = split(/&/,$line,2);
                   10488: 			$allusers{$entry} = 1;
                   10489: 		    }
                   10490: 		}
1.253     stredwic 10491:             }
1.1136    raeburn  10492:             my @alluserslist=();
1.800     albertel 10493:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10494:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10495:             }
1.1318    droeschl 10496: 
                   10497:             if (!%listerror) {
                   10498:                 # no errors
                   10499:                 return (\@alluserslist);
                   10500:             } elsif (scalar(keys(%servers)) == 1) {
                   10501:                 # one library server, one error 
                   10502:                 my ($key) = keys(%listerror);
                   10503:                 return (\@alluserslist, $listerror{$key});
                   10504:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10505:                 # con_lost indicates that we might miss data from at least one
                   10506:                 # library server
                   10507:                 return (\@alluserslist, 'con_lost');
                   10508:             } else {
                   10509:                 # multiple library servers and no con_lost -> data should be
                   10510:                 # complete. 
                   10511:                 return (\@alluserslist);
                   10512:             }
                   10513: 
1.253     stredwic 10514:         } else {
1.1136    raeburn  10515:             return ([],'missing username');
1.253     stredwic 10516:         }
1.955     raeburn  10517:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10518:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10519:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10520:         return (\@all_domains);
1.955     raeburn  10521:     } else {
1.1136    raeburn  10522:         return ([],'missing domain');
1.275     stredwic 10523:     }
                   10524: }
                   10525: 
                   10526: # --------------------------------------------- GetFileTimestamp
                   10527: # This function utilizes dirlist and returns the date stamp for
                   10528: # when it was last modified.  It will also return an error of -1
                   10529: # if an error occurs
                   10530: 
                   10531: sub GetFileTimestamp {
1.955     raeburn  10532:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10533:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10534:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10535:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10536:                                     undef,$getuserdir);
                   10537:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10538:         return -1;
                   10539:     }
                   10540:     if (ref($fileref) eq 'ARRAY') {
                   10541:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10542:         # @stats contains first the filename, then the stat output
                   10543:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10544:     } else {
                   10545:         return -1;
1.253     stredwic 10546:     }
1.26      www      10547: }
                   10548: 
1.712     albertel 10549: sub stat_file {
                   10550:     my ($uri) = @_;
1.787     albertel 10551:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10552: 
1.955     raeburn  10553:     my ($udom,$uname,$file);
1.712     albertel 10554:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10555: 	($udom,$uname,$file) =
1.811     albertel 10556: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10557: 	$file = 'userfiles/'.$file;
                   10558:     }
                   10559:     if ($uri =~ m-^/res/-) {
                   10560: 	($udom,$uname) = 
1.807     albertel 10561: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10562: 	$file = $uri;
                   10563:     }
                   10564: 
                   10565:     if (!$udom || !$uname || !$file) {
                   10566: 	# unable to handle the uri
                   10567: 	return ();
                   10568:     }
1.956     raeburn  10569:     my $getpropath;
                   10570:     if ($file =~ /^userfiles\//) {
                   10571:         $getpropath = 1;
                   10572:     }
1.1136    raeburn  10573:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10574:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10575:         return ();
                   10576:     } else {
                   10577:         if (ref($listref) eq 'ARRAY') {
                   10578:             my @stats = split('&',$listref->[0]);
                   10579: 	    shift(@stats); #filename is first
                   10580: 	    return @stats;
                   10581:         }
1.712     albertel 10582:     }
                   10583:     return ();
                   10584: }
                   10585: 
1.1313    raeburn  10586: # --------------------------------------------------------- recursedirs
                   10587: # Recursive function to traverse either a specific user's Authoring Space
                   10588: # or corresponding Published Resource Space, and populate the hash ref:
                   10589: # $dirhashref with URLs of all directories, and if $filehashref hash
                   10590: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
                   10591: # or .rights files in resource space, and .meta, .save, .log, and .bak
                   10592: # files in Authoring Space.
                   10593: #
                   10594: # Inputs:
                   10595: #
                   10596: # $is_home - true if current server is home server for user's space
                   10597: # $context - either: priv, or res respectively for Authoring or Resource Space.
                   10598: # $docroot - Document root (i.e., /home/httpd/html
                   10599: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
                   10600: # $relpath - Current path (relative to top level).
                   10601: # $dirhashref - reference to hash to populate with URLs of directories (Required)
                   10602: # $filehashref - reference to hash to populate with URLs of files (Optional)
                   10603: #
                   10604: # Returns: nothing
                   10605: #
                   10606: # Side Effects: populates $dirhashref, and $filehashref (if provided).
                   10607: #
                   10608: # Currently used by interface/londocs.pm to create linked select boxes for
                   10609: # directory and filename to import a Course "Author" resource into a course, and
                   10610: # also to create linked select boxes for Authoring Space and Directory to choose
                   10611: # save location for creation of a new "standard" problem from the Course Editor.
                   10612: #
                   10613: 
                   10614: sub recursedirs {
                   10615:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
                   10616:     return unless (ref($dirhashref) eq 'HASH');
                   10617:     my $currpath = $docroot.$toppath;
                   10618:     if ($relpath) {
                   10619:         $currpath .= "/$relpath";
                   10620:     }
                   10621:     my $savefile;
                   10622:     if (ref($filehashref)) {
                   10623:         $savefile = 1;
                   10624:     }
                   10625:     if ($is_home) {
                   10626:         if (opendir(my $dirh,$currpath)) {
                   10627:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
                   10628:                 next if ($item eq '');
                   10629:                 if (-d "$currpath/$item") {
                   10630:                     my $newpath;
                   10631:                     if ($relpath) {
                   10632:                         $newpath = "$relpath/$item";
                   10633:                     } else {
                   10634:                         $newpath = $item;
                   10635:                     }
                   10636:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   10637:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   10638:                 } elsif ($savefile) {
                   10639:                     if ($context eq 'priv') {
                   10640:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   10641:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   10642:                         }
                   10643:                     } else {
                   10644:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
                   10645:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   10646:                         }
                   10647:                     }
                   10648:                 }
                   10649:             }
                   10650:             closedir($dirh);
                   10651:         }
                   10652:     } else {
                   10653:         my ($dirlistref,$listerror) =
                   10654:             &dirlist($toppath.$relpath);
                   10655:         my @dir_lines;
                   10656:         my $dirptr=16384;
                   10657:         if (ref($dirlistref) eq 'ARRAY') {
                   10658:             foreach my $dir_line (sort
                   10659:                               {
                   10660:                                   my ($afile)=split('&',$a,2);
                   10661:                                   my ($bfile)=split('&',$b,2);
                   10662:                                   return (lc($afile) cmp lc($bfile));
                   10663:                               } (@{$dirlistref})) {
                   10664:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
                   10665:                     split(/\&/,$dir_line,16);
                   10666:                 $item =~ s/\s+$//;
                   10667:                 next if (($item =~ /^\.\.?$/) || ($obs));
                   10668:                 if ($dirptr&$testdir) {
                   10669:                     my $newpath;
                   10670:                     if ($relpath) {
                   10671:                         $newpath = "$relpath/$item";
                   10672:                     } else {
                   10673:                         $relpath = '/';
                   10674:                         $newpath = $item;
                   10675:                     }
                   10676:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   10677:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   10678:                 } elsif ($savefile) {
                   10679:                     if ($context eq 'priv') {
                   10680:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   10681:                             $filehashref->{$relpath}{$item} = 1;
                   10682:                         }
                   10683:                     } else {
                   10684:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
                   10685:                             $filehashref->{$relpath}{$item} = 1;
                   10686:                         }
                   10687:                     }
                   10688:                 }
                   10689:             }
                   10690:         }
                   10691:     }
                   10692:     return;
                   10693: }
                   10694: 
1.26      www      10695: # -------------------------------------------------------- Value of a Condition
                   10696: 
1.713     albertel 10697: # gets the value of a specific preevaluated condition
                   10698: #    stored in the string  $env{user.state.<cid>}
                   10699: # or looks up a condition reference in the bighash and if if hasn't
                   10700: # already been evaluated recurses into docondval to get the value of
                   10701: # the condition, then memoizing it to 
                   10702: #   $env{user.state.<cid>.<condition>}
1.40      www      10703: sub directcondval {
                   10704:     my $number=shift;
1.620     albertel 10705:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 10706: 	&Apache::lonuserstate::evalstate();
                   10707:     }
1.713     albertel 10708:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   10709: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   10710:     } elsif ($number =~ /^_/) {
                   10711: 	my $sub_condition;
                   10712: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10713: 		&GDBM_READER(),0640)) {
                   10714: 	    $sub_condition=$bighash{'conditions'.$number};
                   10715: 	    untie(%bighash);
                   10716: 	}
                   10717: 	my $value = &docondval($sub_condition);
1.949     raeburn  10718: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 10719: 	return $value;
                   10720:     }
1.620     albertel 10721:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   10722:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      10723:     } else {
                   10724:        return 2;
                   10725:     }
                   10726: }
                   10727: 
1.713     albertel 10728: # get the collection of conditions for this resource
1.26      www      10729: sub condval {
                   10730:     my $condidx=shift;
1.54      www      10731:     my $allpathcond='';
1.713     albertel 10732:     foreach my $cond (split(/\|/,$condidx)) {
                   10733: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   10734: 	    $allpathcond.=
                   10735: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   10736: 	}
1.191     harris41 10737:     }
1.54      www      10738:     $allpathcond=~s/\|$//;
1.713     albertel 10739:     return &docondval($allpathcond);
                   10740: }
                   10741: 
                   10742: #evaluates an expression of conditions
                   10743: sub docondval {
                   10744:     my ($allpathcond) = @_;
                   10745:     my $result=0;
                   10746:     if ($env{'request.course.id'}
                   10747: 	&& defined($allpathcond)) {
                   10748: 	my $operand='|';
                   10749: 	my @stack;
                   10750: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   10751: 	    if ($chunk eq '(') {
                   10752: 		push @stack,($operand,$result);
                   10753: 	    } elsif ($chunk eq ')') {
                   10754: 		my $before=pop @stack;
                   10755: 		if (pop @stack eq '&') {
                   10756: 		    $result=$result>$before?$before:$result;
                   10757: 		} else {
                   10758: 		    $result=$result>$before?$result:$before;
                   10759: 		}
                   10760: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   10761: 		$operand=$chunk;
                   10762: 	    } else {
                   10763: 		my $new=directcondval($chunk);
                   10764: 		if ($operand eq '&') {
                   10765: 		    $result=$result>$new?$new:$result;
                   10766: 		} else {
                   10767: 		    $result=$result>$new?$result:$new;
                   10768: 		}
                   10769: 	    }
                   10770: 	}
1.26      www      10771:     }
                   10772:     return $result;
1.421     albertel 10773: }
                   10774: 
                   10775: # ---------------------------------------------------- Devalidate courseresdata
                   10776: 
                   10777: sub devalidatecourseresdata {
                   10778:     my ($coursenum,$coursedomain)=@_;
                   10779:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10780:     &devalidate_cache_new('courseres',$hashid);
1.28      www      10781: }
                   10782: 
1.763     www      10783: 
1.200     www      10784: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     10785: #
                   10786: #  Parameters:
                   10787: #      $coursenum    - Number of the course.
                   10788: #      $coursedomain - Domain at which the course was created.
                   10789: #  Returns:
                   10790: #     A hash of the course parameters along (I think) with timestamps
                   10791: #     and version info.
1.877     foxr     10792: 
1.624     albertel 10793: sub get_courseresdata {
                   10794:     my ($coursenum,$coursedomain)=@_;
1.200     www      10795:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   10796:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10797:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 10798:     my %dumpreply;
1.417     albertel 10799:     unless (defined($cached)) {
1.624     albertel 10800: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 10801: 	$result=\%dumpreply;
1.251     albertel 10802: 	my ($tmp) = keys(%dumpreply);
                   10803: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 10804: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 10805: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   10806: 	    return $tmp;
1.416     albertel 10807: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 10808: 	    $result=undef;
1.599     albertel 10809: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 10810: 	}
                   10811:     }
1.624     albertel 10812:     return $result;
                   10813: }
                   10814: 
1.633     albertel 10815: sub devalidateuserresdata {
                   10816:     my ($uname,$udom)=@_;
                   10817:     my $hashid="$udom:$uname";
                   10818:     &devalidate_cache_new('userres',$hashid);
                   10819: }
                   10820: 
1.624     albertel 10821: sub get_userresdata {
                   10822:     my ($uname,$udom)=@_;
                   10823:     #most student don\'t have any data set, check if there is some data
                   10824:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   10825: 
                   10826:     my $hashid="$udom:$uname";
                   10827:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   10828:     if (!defined($cached)) {
                   10829: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   10830: 	$result=\%resourcedata;
                   10831: 	&do_cache_new('userres',$hashid,$result,600);
                   10832:     }
                   10833:     my ($tmp)=keys(%$result);
                   10834:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   10835: 	return $result;
                   10836:     }
                   10837:     #error 2 occurs when the .db doesn't exist
                   10838:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  10839:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   10840: 	    &logthis("<font color=\"blue\">WARNING:".
                   10841: 		     " Trying to get resource data for ".
                   10842: 		     $uname." at ".$udom.": ".
                   10843: 		     $tmp."</font>");
                   10844:         }
1.624     albertel 10845:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 10846: 	#&EXT_cache_set($udom,$uname);
                   10847: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 10848: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 10849:     }
                   10850:     return $tmp;
                   10851: }
1.879     foxr     10852: #----------------------------------------------- resdata - return resource data
                   10853: #  Purpose:
                   10854: #    Return resource data for either users or for a course.
                   10855: #  Parameters:
                   10856: #     $name      - Course/user name.
                   10857: #     $domain    - Name of the domain the user/course is registered on.
1.1311    raeburn  10858: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  10859: #     $mapp      - decluttered URL of enclosing map  
                   10860: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   10861: #     $recurseup - Ref to array of map URLs, starting with map containing
                   10862: #                  $mapp up through hierarchy of nested maps to top level map.  
                   10863: #     $courseid  - CourseID (first part of param identifier).
                   10864: #     $modifier  - Middle part of param identifier.
                   10865: #     $what      - Last part of param identifier.
1.879     foxr     10866: #     @which     - Array of names of resources desired.
                   10867: #  Returns:
                   10868: #     The value of the first reasource in @which that is found in the
                   10869: #     resource hash.
                   10870: #  Exceptional Conditions:
                   10871: #     If the $type passed in is not valid (not the string 'course' or 
                   10872: #     'user', an undefined  reference is returned.
                   10873: #     If none of the resources are found, an undef is returned
1.624     albertel 10874: sub resdata {
1.1301    raeburn  10875:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   10876:         $modifier,$what,@which)=@_;
1.624     albertel 10877:     my $result;
                   10878:     if ($type eq 'course') {
                   10879: 	$result=&get_courseresdata($name,$domain);
                   10880:     } elsif ($type eq 'user') {
                   10881: 	$result=&get_userresdata($name,$domain);
                   10882:     }
                   10883:     if (!ref($result)) { return $result; }    
1.251     albertel 10884:     foreach my $item (@which) {
1.1301    raeburn  10885:         if ($item->[1] eq 'course') {
                   10886:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   10887:                 unless ($$recursed) {
1.1302    raeburn  10888:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  10889:                     $$recursed = 1;
                   10890:                 }
                   10891:                 foreach my $item (@${recurseup}) {
                   10892:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   10893:                     last if (defined($result->{$norecursechk}));
                   10894:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   10895:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   10896:                 }
                   10897:             }
                   10898:         }
                   10899:         if (defined($result->{$item->[0]})) {
1.927     albertel 10900: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 10901: 	}
1.250     albertel 10902:     }
1.291     albertel 10903:     return undef;
1.200     www      10904: }
                   10905: 
1.1298    raeburn  10906: sub get_domain_ltitools {
                   10907:     my ($cdom) = @_;
                   10908:     my %ltitools;
                   10909:     my ($result,$cached)=&is_cached_new('ltitools',$cdom);
                   10910:     if (defined($cached)) {
                   10911:         if (ref($result) eq 'HASH') {
                   10912:             %ltitools = %{$result};
                   10913:         }
                   10914:     } else {
                   10915:         my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
                   10916:         if (ref($domconfig{'ltitools'}) eq 'HASH') {
                   10917:             %ltitools = %{$domconfig{'ltitools'}};
                   10918:         }
                   10919:         my $cachetime = 24*60*60;
                   10920:         &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
                   10921:     }
                   10922:     return %ltitools;
                   10923: }
                   10924: 
1.1236    raeburn  10925: sub get_numsuppfiles {
                   10926:     my ($cnum,$cdom,$ignorecache)=@_;
                   10927:     my $hashid=$cnum.':'.$cdom;
                   10928:     my ($suppcount,$cached);
                   10929:     unless ($ignorecache) {
                   10930:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   10931:     }
                   10932:     unless (defined($cached)) {
                   10933:         my $chome=&homeserver($cnum,$cdom);
                   10934:         unless ($chome eq 'no_host') {
                   10935:             ($suppcount,my $errors) = (0,0);
                   10936:             my $suppmap = 'supplemental.sequence';
                   10937:             ($suppcount,$errors) = 
                   10938:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   10939:         }
                   10940:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   10941:     }
                   10942:     return $suppcount;
                   10943: }
                   10944: 
1.379     matthew  10945: #
                   10946: # EXT resource caching routines
                   10947: #
                   10948: 
1.1302    raeburn  10949: {
                   10950: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   10951: #
                   10952: # The course for which we cache
                   10953: my $cachedmapkey='';
                   10954: # The cached recursive maps for this course
                   10955: my %cachedmaps=();
                   10956: # When this was last done
                   10957: my $cachedmaptime='';
                   10958: 
1.379     matthew  10959: sub clear_EXT_cache_status {
1.383     albertel 10960:     &delenv('cache.EXT.');
1.379     matthew  10961: }
                   10962: 
                   10963: sub EXT_cache_status {
                   10964:     my ($target_domain,$target_user) = @_;
1.383     albertel 10965:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 10966:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  10967:         # We know already the user has no data
                   10968:         return 1;
                   10969:     } else {
                   10970:         return 0;
                   10971:     }
                   10972: }
                   10973: 
                   10974: sub EXT_cache_set {
                   10975:     my ($target_domain,$target_user) = @_;
1.383     albertel 10976:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  10977:     #&appenv({$cachename => time});
1.379     matthew  10978: }
                   10979: 
1.28      www      10980: # --------------------------------------------------------- Value of a Variable
1.58      www      10981: sub EXT {
1.715     albertel 10982: 
1.1228    raeburn  10983:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      10984:     unless ($varname) { return ''; }
1.218     albertel 10985:     #get real user name/domain, courseid and symb
                   10986:     my $courseid;
1.359     albertel 10987:     my $publicuser;
1.427     www      10988:     if ($symbparm) {
                   10989: 	$symbparm=&get_symb_from_alias($symbparm);
                   10990:     }
1.218     albertel 10991:     if (!($uname && $udom)) {
1.790     albertel 10992:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 10993:       if (!$symbparm) {	$symbparm=$cursymb; }
                   10994:     } else {
1.620     albertel 10995: 	$courseid=$env{'request.course.id'};
1.218     albertel 10996:     }
1.48      www      10997:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   10998:     my $rest;
1.320     albertel 10999:     if (defined($therest[0])) {
1.48      www      11000:        $rest=join('.',@therest);
                   11001:     } else {
                   11002:        $rest='';
                   11003:     }
1.320     albertel 11004: 
1.57      www      11005:     my $qualifierrest=$qualifier;
                   11006:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11007:     my $spacequalifierrest=$space;
                   11008:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11009:     if ($realm eq 'user') {
1.48      www      11010: # --------------------------------------------------------------- user.resource
                   11011: 	if ($space eq 'resource') {
1.651     albertel 11012: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11013: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11014: 		 &&
1.744     albertel 11015: 		 ($symbparm eq &symbread()) ) {	
                   11016: 		# if we are in the middle of processing the resource the
                   11017: 		# get the value we are planning on committing
                   11018:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11019:                     return $Apache::lonhomework::results{$qualifierrest};
                   11020:                 } else {
                   11021:                     return $Apache::lonhomework::history{$qualifierrest};
                   11022:                 }
1.335     albertel 11023: 	    } else {
1.359     albertel 11024: 		my %restored;
1.620     albertel 11025: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11026: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11027: 		} else {
                   11028: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11029: 		}
1.335     albertel 11030: 		return $restored{$qualifierrest};
                   11031: 	    }
1.48      www      11032: # ----------------------------------------------------------------- user.access
                   11033:         } elsif ($space eq 'access') {
1.218     albertel 11034: 	    # FIXME - not supporting calls for a specific user
1.48      www      11035:             return &allowed($qualifier,$rest);
                   11036: # ------------------------------------------ user.preferences, user.environment
                   11037:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11038: 	    if (($uname eq $env{'user.name'}) &&
                   11039: 		($udom eq $env{'user.domain'})) {
                   11040: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11041: 	    } else {
1.359     albertel 11042: 		my %returnhash;
                   11043: 		if (!$publicuser) {
                   11044: 		    %returnhash=&userenvironment($udom,$uname,
                   11045: 						 $qualifierrest);
                   11046: 		}
1.218     albertel 11047: 		return $returnhash{$qualifierrest};
                   11048: 	    }
1.48      www      11049: # ----------------------------------------------------------------- user.course
                   11050:         } elsif ($space eq 'course') {
1.218     albertel 11051: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11052:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11053: # ------------------------------------------------------------------- user.role
                   11054:         } elsif ($space eq 'role') {
1.218     albertel 11055: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11056:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11057:             if ($qualifier eq 'value') {
                   11058: 		return $role;
                   11059:             } elsif ($qualifier eq 'extent') {
                   11060:                 return $where;
                   11061:             }
                   11062: # ----------------------------------------------------------------- user.domain
                   11063:         } elsif ($space eq 'domain') {
1.218     albertel 11064:             return $udom;
1.48      www      11065: # ------------------------------------------------------------------- user.name
                   11066:         } elsif ($space eq 'name') {
1.218     albertel 11067:             return $uname;
1.48      www      11068: # ---------------------------------------------------- Any other user namespace
1.29      www      11069:         } else {
1.359     albertel 11070: 	    my %reply;
                   11071: 	    if (!$publicuser) {
                   11072: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11073: 	    }
                   11074: 	    return $reply{$qualifierrest};
1.48      www      11075:         }
1.236     www      11076:     } elsif ($realm eq 'query') {
                   11077: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11078:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11079: 						[$spacequalifierrest]);
1.620     albertel 11080: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11081:    } elsif ($realm eq 'request') {
1.48      www      11082: # ------------------------------------------------------------- request.browser
                   11083:         if ($space eq 'browser') {
1.1145    bisitz   11084:             return $env{'browser.'.$qualifier};
1.57      www      11085: # ------------------------------------------------------------ request.filename
                   11086:         } else {
1.620     albertel 11087:             return $env{'request.'.$spacequalifierrest};
1.29      www      11088:         }
1.28      www      11089:     } elsif ($realm eq 'course') {
1.48      www      11090: # ---------------------------------------------------------- course.description
1.620     albertel 11091:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11092:     } elsif ($realm eq 'resource') {
1.165     www      11093: 
1.620     albertel 11094: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11095: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11096: 	}
1.693     albertel 11097: 
1.1232    raeburn  11098:         if ($qualifier eq '') {
                   11099: 	    if ($space eq 'title') {
                   11100: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11101: 	        return &gettitle($symbparm);
                   11102: 	    }
1.693     albertel 11103: 	
1.1232    raeburn  11104: 	    if ($space eq 'map') {
                   11105: 	        my ($map) = &decode_symb($symbparm);
                   11106: 	        return &symbread($map);
                   11107: 	    }
                   11108:             if ($space eq 'maptitle') {
                   11109:                 my ($map) = &decode_symb($symbparm);
                   11110:                 return &gettitle($map);
                   11111:             }
                   11112: 	    if ($space eq 'filename') {
                   11113: 	        if ($symbparm) {
                   11114: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11115: 	        }
                   11116: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11117: 	    }
1.1232    raeburn  11118: 
1.1233    raeburn  11119:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11120:                 if ($space eq 'visibleparts') {
                   11121:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11122:                     my $item;
                   11123:                     if (ref($navmap)) {
                   11124:                         my $res = $navmap->getBySymb($symbparm);
                   11125:                         my $parts = $res->parts();
                   11126:                         if (ref($parts) eq 'ARRAY') {
                   11127:                             $item = join(',',@{$parts});
                   11128:                         }
                   11129:                         undef($navmap);
1.1232    raeburn  11130:                     }
1.1233    raeburn  11131:                     return $item;
1.1232    raeburn  11132:                 }
                   11133:             }
                   11134:         }
1.693     albertel 11135: 
1.1301    raeburn  11136: 	my ($section, $group, @groups, @recurseup, $recursed);
                   11137: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  11138:         if (($courseid eq '') && ($cid)) {
                   11139:             $courseid = $cid;
                   11140:         }
                   11141: 	if (($symbparm && $courseid) && 
                   11142: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      11143: 
1.218     albertel 11144: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11145: 
1.60      www      11146: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11147: 	    my $symbp=$symbparm;
1.1301    raeburn  11148: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11149: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  11150:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 11151: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 11152: 	    if (($env{'user.name'} eq $uname) &&
                   11153: 		($env{'user.domain'} eq $udom)) {
                   11154: 		$section=$env{'request.course.sec'};
1.733     raeburn  11155:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11156:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11157: 	    } else {
1.539     albertel 11158: 		if (! defined($usection)) {
1.551     albertel 11159: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11160: 		} else {
                   11161: 		    $section = $usection;
                   11162: 		}
1.733     raeburn  11163:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11164: 	    }
                   11165: 
                   11166: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11167: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  11168:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 11169: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11170: 
1.593     albertel 11171: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11172: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  11173:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 11174: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11175: 
1.60      www      11176: # ----------------------------------------------------------- first, check user
1.624     albertel 11177: 
1.1301    raeburn  11178: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   11179:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 11180: 				       ([$courselevelr,'resource'],
                   11181: 					[$courselevelm,'map'     ],
1.1301    raeburn  11182:                                         [$courseleveli,'map'     ],
1.927     albertel 11183: 					[$courselevel, 'course'  ]));
1.931     albertel 11184: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11185: 
1.594     albertel 11186: # ------------------------------------------------ second, check some of course
1.684     raeburn  11187:             my $coursereply;
1.691     raeburn  11188:             if (@groups > 0) {
                   11189:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  11190:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   11191:                                        $mapp,\$recursed,\@recurseup);
                   11192:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  11193:             }
1.96      www      11194: 
1.684     raeburn  11195: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11196: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  11197: 				  'course',$mapp,\$recursed,\@recurseup,
                   11198:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 11199: 				  ([$seclevelr,   'resource'],
                   11200: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  11201:                                    [$secleveli,   'map'     ],
1.927     albertel 11202: 				   [$seclevel,    'course'  ],
                   11203: 				   [$courselevelr,'resource']));
                   11204: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11205: 
1.60      www      11206: # ------------------------------------------------------ third, check map parms
1.218     albertel 11207: 	    my %parmhash=();
                   11208: 	    my $thisparm='';
                   11209: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11210: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11211: 		    &GDBM_READER(),0640)) {
1.218     albertel 11212: 		$thisparm=$parmhash{$symbparm};
                   11213: 		untie(%parmhash);
                   11214: 	    }
1.927     albertel 11215: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11216: 	}
1.594     albertel 11217: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  11218:  
                   11219:         my $what = $spacequalifierrest;
                   11220: 	$what=~s/\./\_/;
1.282     albertel 11221: 	my $filename;
                   11222: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11223: 	if ($symbparm) {
1.409     www      11224: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11225: 	} else {
1.620     albertel 11226: 	    $filename=$env{'request.filename'};
1.282     albertel 11227: 	}
1.1301    raeburn  11228: 	my $metadata=&metadata($filename,$what);
1.927     albertel 11229: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1301    raeburn  11230: 	$metadata=&metadata($filename,'parameter_'.$what);
1.927     albertel 11231: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11232: 
1.1301    raeburn  11233: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 11234: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11235: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11236: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11237: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  11238: 				     'course',$mapp,\$recursed,\@recurseup,
                   11239:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 11240: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  11241:                                       [$courseleveli,'map'   ],
1.927     albertel 11242: 				      [$courselevel, 'course']));
                   11243: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11244: 	}
1.145     www      11245: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11246: 	unless ($space eq '0') {
1.336     albertel 11247: 	    my @parts=split(/_/,$space);
                   11248: 	    my $id=pop(@parts);
                   11249: 	    my $part=join('_',@parts);
                   11250: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11251: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11252: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11253: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11254: 	}
1.395     albertel 11255: 	if ($recurse) { return undef; }
                   11256: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 11257: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11258: # ---------------------------------------------------- Any other user namespace
                   11259:     } elsif ($realm eq 'environment') {
                   11260: # ----------------------------------------------------------------- environment
1.620     albertel 11261: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11262: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11263: 	} else {
1.770     albertel 11264: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11265: 		return '';
                   11266: 	    }
1.219     albertel 11267: 	    my %returnhash=&userenvironment($udom,$uname,
                   11268: 					    $spacequalifierrest);
                   11269: 	    return $returnhash{$spacequalifierrest};
                   11270: 	}
1.28      www      11271:     } elsif ($realm eq 'system') {
1.48      www      11272: # ----------------------------------------------------------------- system.time
                   11273: 	if ($space eq 'time') {
                   11274: 	    return time;
                   11275:         }
1.696     albertel 11276:     } elsif ($realm eq 'server') {
                   11277: # ----------------------------------------------------------------- system.time
                   11278: 	if ($space eq 'name') {
                   11279: 	    return $ENV{'SERVER_NAME'};
                   11280:         }
1.28      www      11281:     }
1.48      www      11282:     return '';
1.61      www      11283: }
                   11284: 
1.927     albertel 11285: sub get_reply {
                   11286:     my ($reply_value) = @_;
1.940     raeburn  11287:     if (ref($reply_value) eq 'ARRAY') {
                   11288:         if (wantarray) {
                   11289: 	    return @$reply_value;
                   11290:         }
                   11291:         return $reply_value->[0];
                   11292:     } else {
                   11293:         return $reply_value;
1.927     albertel 11294:     }
                   11295: }
                   11296: 
1.691     raeburn  11297: sub check_group_parms {
1.1301    raeburn  11298:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   11299:         $recursed,$recurseupref) = @_;
                   11300:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   11301:                   [$what,'course']);
                   11302:     my $coursereply;
1.691     raeburn  11303:     foreach my $group (@{$groups}) {
1.1301    raeburn  11304:         my @groupitems = ();
1.691     raeburn  11305:         foreach my $level (@levels) {
1.927     albertel 11306:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11307:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11308:         }
1.1301    raeburn  11309:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11310:                                    $env{'course.'.$courseid.'.domain'},
                   11311:                                    'course',$mapp,$recursed,$recurseupref,
                   11312:                                    $courseid,'.['.$group.'].',$what,
                   11313:                                    @groupitems);
                   11314:         last if (defined($coursereply));
1.691     raeburn  11315:     }
                   11316:     return $coursereply;
                   11317: }
                   11318: 
1.1301    raeburn  11319: sub get_map_hierarchy {
1.1302    raeburn  11320:     my ($mapname,$courseid) = @_;
                   11321:     my @recurseup = ();
1.1301    raeburn  11322:     if ($mapname) {
1.1302    raeburn  11323:         if (($cachedmapkey eq $courseid) &&
                   11324:             (abs($cachedmaptime-time)<5)) {
                   11325:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   11326:                 return @{$cachedmaps{$mapname}};
                   11327:             }
                   11328:         }
1.1301    raeburn  11329:         my $navmap = Apache::lonnavmaps::navmap->new();
                   11330:         if (ref($navmap)) {
                   11331:             @recurseup = $navmap->recurseup_maps($mapname);
                   11332:             undef($navmap);
1.1302    raeburn  11333:             $cachedmaps{$mapname} = \@recurseup;
                   11334:             $cachedmaptime=time;
                   11335:             $cachedmapkey=$courseid;
1.1301    raeburn  11336:         }
                   11337:     }
                   11338:     return @recurseup;
                   11339: }
                   11340: 
1.1302    raeburn  11341: }
                   11342: 
1.691     raeburn  11343: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11344:     my ($courseid,@groups) = @_;
                   11345:     @groups = sort(@groups);
1.691     raeburn  11346:     return @groups;
                   11347: }
                   11348: 
1.395     albertel 11349: sub packages_tab_default {
                   11350:     my ($uri,$varname)=@_;
                   11351:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11352: 
                   11353:     my (@extension,@specifics,$do_default);
                   11354:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11355: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11356: 	if ($pack_type eq 'default') {
                   11357: 	    $do_default=1;
                   11358: 	} elsif ($pack_type eq 'extension') {
                   11359: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11360: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11361: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11362: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11363: 	}
                   11364:     }
                   11365:     # first look for a package that matches the requested part id
                   11366:     foreach my $package (@specifics) {
                   11367: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11368: 	next if ($pack_part ne $part);
                   11369: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11370: 	    return $packagetab{"$pack_type&$name&default"};
                   11371: 	}
                   11372:     }
                   11373:     # look for any possible matching non extension_ package
                   11374:     foreach my $package (@specifics) {
                   11375: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11376: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11377: 	    return $packagetab{"$pack_type&$name&default"};
                   11378: 	}
1.585     albertel 11379: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11380: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11381: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11382: 	}
                   11383:     }
1.738     albertel 11384:     # look for any posible extension_ match
                   11385:     foreach my $package (@extension) {
                   11386: 	my ($package,$pack_type)=@{$package};
                   11387: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11388: 	    return $packagetab{"$pack_type&$name&default"};
                   11389: 	}
                   11390: 	if (defined($packagetab{$package."&$name&default"})) {
                   11391: 	    return $packagetab{$package."&$name&default"};
                   11392: 	}
                   11393:     }
                   11394:     # look for a global default setting
                   11395:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11396: 	return $packagetab{"default&$name&default"};
                   11397:     }
1.395     albertel 11398:     return undef;
                   11399: }
                   11400: 
1.334     albertel 11401: sub add_prefix_and_part {
                   11402:     my ($prefix,$part)=@_;
                   11403:     my $keyroot;
                   11404:     if (defined($prefix) && $prefix !~ /^__/) {
                   11405: 	# prefix that has a part already
                   11406: 	$keyroot=$prefix;
                   11407:     } elsif (defined($prefix)) {
                   11408: 	# prefix that is missing a part
                   11409: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11410:     } else {
                   11411: 	# no prefix at all
                   11412: 	if (defined($part)) { $keyroot='_'.$part; }
                   11413:     }
                   11414:     return $keyroot;
                   11415: }
                   11416: 
1.71      www      11417: # ---------------------------------------------------------------- Get metadata
                   11418: 
1.599     albertel 11419: my %metaentry;
1.1070    www      11420: my %importedpartids;
1.71      www      11421: sub metadata {
1.176     www      11422:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11423:     $uri=&declutter($uri);
1.288     albertel 11424:     # if it is a non metadata possible uri return quickly
1.529     albertel 11425:     if (($uri eq '') || 
                   11426: 	(($uri =~ m|^/*adm/|) && 
1.1298    raeburn  11427: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|exttools?)$})) ||
1.1108    raeburn  11428:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11429: 	return undef;
                   11430:     }
1.1261    raeburn  11431:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11432: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11433: 	return undef;
1.288     albertel 11434:     }
1.73      www      11435:     my $filename=$uri;
                   11436:     $uri=~s/\.meta$//;
1.172     www      11437: #
                   11438: # Is the metadata already cached?
1.177     www      11439: # Look at timestamp of caching
1.172     www      11440: # Everything is cached by the main uri, libraries are never directly cached
                   11441: #
1.428     albertel 11442:     if (!defined($liburi)) {
1.599     albertel 11443: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11444: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11445:     }
                   11446:     {
1.1069    www      11447: # Imported parts would go here
1.1070    www      11448:         my %importedids=();
                   11449:         my @origfileimportpartids=();
1.1069    www      11450:         my $importedparts=0;
1.172     www      11451: #
                   11452: # Is this a recursive call for a library?
                   11453: #
1.599     albertel 11454: #	if (! exists($metacache{$uri})) {
                   11455: #	    $metacache{$uri}={};
                   11456: #	}
1.924     albertel 11457: 	my $cachetime = 60*60;
1.171     www      11458:         if ($liburi) {
                   11459: 	    $liburi=&declutter($liburi);
                   11460:             $filename=$liburi;
1.401     bowersj2 11461:         } else {
1.599     albertel 11462: 	    &devalidate_cache_new('meta',$uri);
                   11463: 	    undef(%metaentry);
1.401     bowersj2 11464: 	}
1.140     www      11465:         my %metathesekeys=();
1.73      www      11466:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11467: 	my $metastring;
1.1140    www      11468: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11469: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11470: 	    $metastring = 
1.929     albertel 11471: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11472: 					  ('grade_target' => 'meta'));
                   11473: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11474: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11475:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11476: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11477: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11478: 	    $metastring=&getfile($file);
1.489     albertel 11479: 	}
1.208     albertel 11480:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11481:         my $token;
1.140     www      11482:         undef %metathesekeys;
1.71      www      11483:         while ($token=$parser->get_token) {
1.339     albertel 11484: 	    if ($token->[0] eq 'S') {
                   11485: 		if (defined($token->[2]->{'package'})) {
1.172     www      11486: #
                   11487: # This is a package - get package info
                   11488: #
1.339     albertel 11489: 		    my $package=$token->[2]->{'package'};
                   11490: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11491: 		    if (defined($token->[2]->{'id'})) { 
                   11492: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11493: 		    }
1.599     albertel 11494: 		    if ($metaentry{':packages'}) {
                   11495: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11496: 		    } else {
1.599     albertel 11497: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11498: 		    }
1.736     albertel 11499: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11500: 			my $part=$keyroot;
                   11501: 			$part=~s/^\_//;
1.736     albertel 11502: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11503: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11504: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11505: 			    # ignore package.tab specified default values
                   11506:                             # here &package_tab_default() will fetch those
                   11507: 			    if ($subp eq 'default') { next; }
1.736     albertel 11508: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11509: 			    my $unikey;
                   11510: 			    if ($pack =~ /_0$/) {
                   11511: 				$unikey='parameter_0_'.$name;
                   11512: 				$part=0;
                   11513: 			    } else {
                   11514: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11515: 			    }
1.339     albertel 11516: 			    if ($subp eq 'display') {
                   11517: 				$value.=' [Part: '.$part.']';
                   11518: 			    }
1.599     albertel 11519: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11520: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11521: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11522: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11523: 			    }
1.599     albertel 11524: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11525: 				$metaentry{':'.$unikey}=
                   11526: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11527: 			    }
1.339     albertel 11528: 			}
                   11529: 		    }
                   11530: 		} else {
1.172     www      11531: #
                   11532: # This is not a package - some other kind of start tag
1.339     albertel 11533: #
                   11534: 		    my $entry=$token->[1];
1.1068    www      11535: 		    my $unikey='';
1.175     www      11536: 
1.339     albertel 11537: 		    if ($entry eq 'import') {
1.175     www      11538: #
                   11539: # Importing a library here
1.339     albertel 11540: #
1.1067    www      11541:                         my $location=$parser->get_text('/import');
                   11542:                         my $dir=$filename;
                   11543:                         $dir=~s|[^/]*$||;
                   11544:                         $location=&filelocation($dir,$location);
1.1069    www      11545:                        
1.1068    www      11546:                         my $importmode=$token->[2]->{'importmode'};
                   11547:                         if ($importmode eq 'problem') {
1.1069    www      11548: # Import as problem/response
1.1068    www      11549:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11550:                         } elsif ($importmode eq 'part') {
                   11551: # Import as part(s)
1.1069    www      11552:                            $importedparts=1;
                   11553: # We need to get the original file and the imported file to get the part order correct
                   11554: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   11555: # Load and inspect original file
1.1070    www      11556:                            if ($#origfileimportpartids<0) {
                   11557:                               undef(%importedpartids);
                   11558:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11559:                               my $origfile=&getfile($origfilelocation);
                   11560:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11561:                            }
                   11562: 
1.1069    www      11563: # Load and inspect imported file
                   11564:                            my $impfile=&getfile($location);
                   11565:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11566:                            if ($#impfilepartids>=0) {
                   11567: # This problem had parts
1.1070    www      11568:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11569:                            } else {
                   11570: # Importing by turning a single problem into a problem part
                   11571: # It gets the import-tags ID as part-ID
                   11572:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11573:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11574:                            }
1.1068    www      11575:                         } else {
                   11576: # Normal import
                   11577:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11578:                            if (defined($token->[2]->{'id'})) {
                   11579:                               $unikey.='_'.$token->[2]->{'id'};
                   11580:                            }
1.1067    www      11581:                         }
                   11582: 
1.339     albertel 11583: 			if ($depthcount<20) {
1.736     albertel 11584: 			    my $metadata = 
                   11585: 				&metadata($uri,'keys', $location,$unikey,
                   11586: 					  $depthcount+1);
                   11587: 			    foreach my $meta (split(',',$metadata)) {
                   11588: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   11589: 				$metathesekeys{$meta}=1;
1.339     albertel 11590: 			    }
1.1068    www      11591: 			
                   11592:                         }
1.1067    www      11593: 		    } else {
                   11594: #
                   11595: # Not importing, some other kind of non-package, non-library start tag
                   11596: # 
                   11597:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11598:                         if (defined($token->[2]->{'id'})) {
                   11599:                             $unikey.='_'.$token->[2]->{'id'};
                   11600:                         }
1.339     albertel 11601: 			if (defined($token->[2]->{'name'})) { 
                   11602: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   11603: 			}
                   11604: 			$metathesekeys{$unikey}=1;
1.736     albertel 11605: 			foreach my $param (@{$token->[3]}) {
                   11606: 			    $metaentry{':'.$unikey.'.'.$param} =
                   11607: 				$token->[2]->{$param};
1.339     albertel 11608: 			}
                   11609: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 11610: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 11611: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   11612: 		 # only ws inside the tag, and not in default, so use default
                   11613: 		 # as value
1.599     albertel 11614: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 11615: 			} elsif ( $internaltext =~ /\S/ ) {
                   11616: 		  # something interesting inside the tag
                   11617: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 11618: 			} else {
1.908     albertel 11619: 		  # no interesting values, don't set a default
1.339     albertel 11620: 			}
1.172     www      11621: # end of not-a-package not-a-library import
1.339     albertel 11622: 		    }
1.172     www      11623: # end of not-a-package start tag
1.339     albertel 11624: 		}
1.172     www      11625: # the next is the end of "start tag"
1.339     albertel 11626: 	    }
                   11627: 	}
1.483     albertel 11628: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 11629: 	$extension = lc($extension);
                   11630: 	if ($extension eq 'htm') { $extension='html'; }
                   11631: 
1.737     albertel 11632: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 11633: 	    #no specific packages #how's our extension
                   11634: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 11635: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 11636: 					 \%metathesekeys);
                   11637: 	}
1.883     albertel 11638: 
                   11639: 	if (!exists($metaentry{':packages'})
                   11640: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 11641: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 11642: 		#no specific packages well let's get default then
                   11643: 		if ($key!~/^default&/) { next; }
1.488     albertel 11644: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 11645: 					     \%metathesekeys);
                   11646: 	    }
                   11647: 	}
1.338     www      11648: # are there custom rights to evaluate
1.599     albertel 11649: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 11650: 
1.338     www      11651:     #
                   11652:     # Importing a rights file here
1.339     albertel 11653:     #
                   11654: 	    unless ($depthcount) {
1.599     albertel 11655: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 11656: 		my $dir=$filename;
                   11657: 		$dir=~s|[^/]*$||;
                   11658: 		$location=&filelocation($dir,$location);
1.736     albertel 11659: 		my $rights_metadata =
                   11660: 		    &metadata($uri,'keys',$location,'_rights',
                   11661: 			      $depthcount+1);
                   11662: 		foreach my $rights (split(',',$rights_metadata)) {
                   11663: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   11664: 		    $metathesekeys{$rights}=1;
1.339     albertel 11665: 		}
                   11666: 	    }
                   11667: 	}
1.737     albertel 11668: 	# uniqifiy package listing
                   11669: 	my %seen;
                   11670: 	my @uniq_packages =
                   11671: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   11672: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   11673: 
1.1070    www      11674:         if ($importedparts) {
                   11675: # We had imported parts and need to rebuild partorder
                   11676:            $metaentry{':partorder'}='';
                   11677:            $metathesekeys{'partorder'}=1;
                   11678:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   11679:                if ($origfileimportpartids[$index] eq 'part') {
                   11680: # original part, part of the problem
                   11681:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   11682:                } else {
                   11683: # we have imported parts at this position
                   11684:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   11685:                }
                   11686:            }
                   11687:            $metaentry{':partorder'}=~s/^\,//;
                   11688:         }
                   11689: 
1.737     albertel 11690: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 11691: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  11692: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 11693: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      11694: # this is the end of "was not already recently cached
1.71      www      11695:     }
1.599     albertel 11696:     return $metaentry{':'.$what};
1.261     albertel 11697: }
                   11698: 
1.488     albertel 11699: sub metadata_create_package_def {
1.483     albertel 11700:     my ($uri,$key,$package,$metathesekeys)=@_;
                   11701:     my ($pack,$name,$subp)=split(/\&/,$key);
                   11702:     if ($subp eq 'default') { next; }
                   11703:     
1.599     albertel 11704:     if (defined($metaentry{':packages'})) {
                   11705: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 11706:     } else {
1.599     albertel 11707: 	$metaentry{':packages'}=$package;
1.483     albertel 11708:     }
                   11709:     my $value=$packagetab{$key};
                   11710:     my $unikey;
                   11711:     $unikey='parameter_0_'.$name;
1.599     albertel 11712:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 11713:     $$metathesekeys{$unikey}=1;
1.599     albertel 11714:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11715: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 11716:     }
1.599     albertel 11717:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   11718: 	$metaentry{':'.$unikey}=
                   11719: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 11720:     }
                   11721: }
                   11722: 
1.261     albertel 11723: sub metadata_generate_part0 {
                   11724:     my ($metadata,$metacache,$uri) = @_;
                   11725:     my %allnames;
1.737     albertel 11726:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 11727: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 11728: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   11729: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 11730: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 11731: 	    $allnames{$name}=$part;
                   11732: 	  }
                   11733: 	}
                   11734:     }
                   11735:     foreach my $name (keys(%allnames)) {
                   11736:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 11737:       my $key=":parameter_0_$name";
1.261     albertel 11738:       $$metacache{"$key.part"}='0';
                   11739:       $$metacache{"$key.name"}=$name;
1.428     albertel 11740:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 11741: 					   $allnames{$name}.'_'.$name.
                   11742: 					   '.type'};
1.428     albertel 11743:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 11744: 			     '.display'};
1.644     www      11745:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 11746:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 11747:       $$metacache{"$key.display"}=$olddis;
                   11748:     }
1.71      www      11749: }
                   11750: 
1.764     albertel 11751: # ------------------------------------------------------ Devalidate title cache
                   11752: 
                   11753: sub devalidate_title_cache {
                   11754:     my ($url)=@_;
                   11755:     if (!$env{'request.course.id'}) { return; }
                   11756:     my $symb=&symbread($url);
                   11757:     if (!$symb) { return; }
                   11758:     my $key=$env{'request.course.id'}."\0".$symb;
                   11759:     &devalidate_cache_new('title',$key);
                   11760: }
                   11761: 
1.1014    droeschl 11762: # ------------------------------------------------- Get the title of a course
                   11763: 
                   11764: sub current_course_title {
                   11765:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   11766: }
1.301     www      11767: # ------------------------------------------------- Get the title of a resource
                   11768: 
                   11769: sub gettitle {
                   11770:     my $urlsymb=shift;
                   11771:     my $symb=&symbread($urlsymb);
1.534     albertel 11772:     if ($symb) {
1.620     albertel 11773: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 11774: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 11775: 	if (defined($cached)) { 
                   11776: 	    return $result;
                   11777: 	}
1.534     albertel 11778: 	my ($map,$resid,$url)=&decode_symb($symb);
                   11779: 	my $title='';
1.907     albertel 11780: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   11781: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   11782: 	} else {
                   11783: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11784: 		    &GDBM_READER(),0640)) {
                   11785: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   11786: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   11787: 		untie(%bighash);
                   11788: 	    }
1.534     albertel 11789: 	}
                   11790: 	$title=~s/\&colon\;/\:/gs;
                   11791: 	if ($title) {
1.1159    www      11792: # Remember both $symb and $title for dynamic metadata
                   11793:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      11794:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      11795: # Cache this title and then return it
1.599     albertel 11796: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 11797: 	}
                   11798: 	$urlsymb=$url;
                   11799:     }
                   11800:     my $title=&metadata($urlsymb,'title');
                   11801:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   11802:     return $title;
1.301     www      11803: }
1.613     albertel 11804: 
1.614     albertel 11805: sub get_slot {
                   11806:     my ($which,$cnum,$cdom)=@_;
                   11807:     if (!$cnum || !$cdom) {
1.790     albertel 11808: 	(undef,my $courseid)=&whichuser();
1.620     albertel 11809: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   11810: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 11811:     }
1.703     albertel 11812:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   11813:     my %slotinfo;
                   11814:     if (exists($remembered{$key})) {
                   11815: 	$slotinfo{$which} = $remembered{$key};
                   11816:     } else {
                   11817: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   11818: 	&Apache::lonhomework::showhash(%slotinfo);
                   11819: 	my ($tmp)=keys(%slotinfo);
                   11820: 	if ($tmp=~/^error:/) { return (); }
                   11821: 	$remembered{$key} = $slotinfo{$which};
                   11822:     }
1.616     albertel 11823:     if (ref($slotinfo{$which}) eq 'HASH') {
                   11824: 	return %{$slotinfo{$which}};
                   11825:     }
                   11826:     return $slotinfo{$which};
1.614     albertel 11827: }
1.1150    raeburn  11828: 
                   11829: sub get_reservable_slots {
                   11830:     my ($cnum,$cdom,$uname,$udom) = @_;
                   11831:     my $now = time;
                   11832:     my $reservable_info;
                   11833:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   11834:     if (exists($remembered{$key})) {
                   11835:         $reservable_info = $remembered{$key};
                   11836:     } else {
                   11837:         my %resv;
                   11838:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   11839:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   11840:         $reservable_info = \%resv;
                   11841:         $remembered{$key} = $reservable_info;
                   11842:     }
                   11843:     return $reservable_info;
                   11844: }
                   11845: 
                   11846: sub get_course_slots {
                   11847:     my ($cnum,$cdom) = @_;
                   11848:     my $hashid=$cnum.':'.$cdom;
                   11849:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   11850:     if (defined($cached)) {
                   11851:         if (ref($result) eq 'HASH') {
                   11852:             return %{$result};
                   11853:         }
                   11854:     } else {
                   11855:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   11856:         my ($tmp) = keys(%slots);
                   11857:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  11858:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  11859:             return %slots;
                   11860:         }
                   11861:     }
                   11862:     return;
                   11863: }
                   11864: 
                   11865: sub devalidate_slots_cache {
                   11866:     my ($cnum,$cdom)=@_;
                   11867:     my $hashid=$cnum.':'.$cdom;
                   11868:     &devalidate_cache_new('allslots',$hashid);
                   11869: }
                   11870: 
1.1181    raeburn  11871: sub get_coursechange {
                   11872:     my ($cdom,$cnum) = @_;
                   11873:     if ($cdom eq '' || $cnum eq '') {
                   11874:         return unless ($env{'request.course.id'});
                   11875:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   11876:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11877:     }
                   11878:     my $hashid=$cdom.'_'.$cnum;
                   11879:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   11880:     if ((defined($cached)) && ($change ne '')) {
                   11881:         return $change;
                   11882:     } else {
                   11883:         my %crshash;
                   11884:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   11885:         if ($crshash{'internal.contentchange'} eq '') {
                   11886:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   11887:             if ($change eq '') {
                   11888:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   11889:                 $change = $crshash{'internal.created'};
                   11890:             }
                   11891:         } else {
                   11892:             $change = $crshash{'internal.contentchange'};
                   11893:         }
                   11894:         my $cachetime = 600;
                   11895:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   11896:     }
                   11897:     return $change;
                   11898: }
                   11899: 
                   11900: sub devalidate_coursechange_cache {
                   11901:     my ($cnum,$cdom)=@_;
                   11902:     my $hashid=$cnum.':'.$cdom;
                   11903:     &devalidate_cache_new('crschange',$hashid);
                   11904: }
                   11905: 
1.31      www      11906: # ------------------------------------------------- Update symbolic store links
                   11907: 
                   11908: sub symblist {
                   11909:     my ($mapname,%newhash)=@_;
1.438     www      11910:     $mapname=&deversion(&declutter($mapname));
1.31      www      11911:     my %hash;
1.620     albertel 11912:     if (($env{'request.course.fn'}) && (%newhash)) {
                   11913:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11914:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  11915: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 11916: 		next if ($url eq 'last_known'
                   11917: 			 && $env{'form.no_update_last_known'});
                   11918: 		$hash{declutter($url)}=&encode_symb($mapname,
                   11919: 						    $newhash{$url}->[1],
                   11920: 						    $newhash{$url}->[0]);
1.191     harris41 11921:             }
1.31      www      11922:             if (untie(%hash)) {
                   11923: 		return 'ok';
                   11924:             }
                   11925:         }
                   11926:     }
                   11927:     return 'error';
1.212     www      11928: }
                   11929: 
                   11930: # --------------------------------------------------------------- Verify a symb
                   11931: 
                   11932: sub symbverify {
1.1190    raeburn  11933:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      11934:     my $thisfn=$thisurl;
1.439     www      11935:     $thisfn=&declutter($thisfn);
1.215     www      11936: # direct jump to resource in page or to a sequence - will construct own symbs
                   11937:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   11938: # check URL part
1.409     www      11939:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      11940: 
1.431     www      11941:     unless ($url eq $thisfn) { return 0; }
1.213     www      11942: 
1.216     www      11943:     $symb=&symbclean($symb);
1.510     www      11944:     $thisurl=&deversion($thisurl);
1.439     www      11945:     $thisfn=&deversion($thisfn);
1.213     www      11946: 
                   11947:     my %bighash;
                   11948:     my $okay=0;
1.431     www      11949: 
1.620     albertel 11950:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11951:                             &GDBM_READER(),0640)) {
1.1204    raeburn  11952:         my $noclutter;
1.1032    raeburn  11953:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   11954:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  11955:             if ($map =~ m{^uploaded/.+\.page$}) {
                   11956:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   11957:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   11958:                 $noclutter = 1;
                   11959:             }
                   11960:         }
                   11961:         my $ids;
                   11962:         if ($noclutter) {
                   11963:             $ids=$bighash{'ids_'.$thisurl};
                   11964:         } else {
                   11965:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  11966:         }
1.1102    raeburn  11967:         unless ($ids) {
                   11968:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   11969:             $ids=$bighash{$idkey};
1.216     www      11970:         }
                   11971:         if ($ids) {
                   11972: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  11973:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  11974:                 $symb =~ s/\?.+$//;
1.1202    raeburn  11975:             }
1.800     albertel 11976: 	    foreach my $id (split(/\,/,$ids)) {
                   11977: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      11978:                if (
                   11979:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  11980:    eq $symb) {
                   11981:                    if (ref($encstate)) {
                   11982:                        $$encstate = $bighash{'encrypted_'.$id};
                   11983:                    }
1.620     albertel 11984: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  11985: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   11986:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  11987: 		       $okay=1;
1.1202    raeburn  11988:                        last;
1.582     albertel 11989: 		   }
                   11990: 	       }
1.216     www      11991: 	   }
                   11992:         }
1.213     www      11993: 	untie(%bighash);
                   11994:     }
                   11995:     return $okay;
1.31      www      11996: }
                   11997: 
1.210     www      11998: # --------------------------------------------------------------- Clean-up symb
                   11999: 
                   12000: sub symbclean {
                   12001:     my $symb=shift;
1.568     albertel 12002:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12003: # remove version from map
                   12004:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12005: 
1.210     www      12006: # remove version from URL
                   12007:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12008: 
1.507     www      12009: # remove wrapper
                   12010: 
1.510     www      12011:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12012:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12013:     return $symb;
1.409     www      12014: }
                   12015: 
                   12016: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12017: 
                   12018: sub encode_symb {
                   12019:     my ($map,$resid,$url)=@_;
                   12020:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12021: }
1.409     www      12022: 
                   12023: sub decode_symb {
1.568     albertel 12024:     my $symb=shift;
                   12025:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12026:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12027:     return (&fixversion($map),$resid,&fixversion($url));
                   12028: }
                   12029: 
                   12030: sub fixversion {
                   12031:     my $fn=shift;
1.609     banghart 12032:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12033:     my %bighash;
                   12034:     my $uri=&clutter($fn);
1.620     albertel 12035:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12036: # is this cached?
1.599     albertel 12037:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12038:     if (defined($cached)) { return $result; }
                   12039: # unfortunately not cached, or expired
1.620     albertel 12040:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12041: 	    &GDBM_READER(),0640)) {
                   12042:  	if ($bighash{'version_'.$uri}) {
                   12043:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12044:  	    unless (($version eq 'mostrecent') || 
                   12045: 		    ($version==&getversion($uri))) {
1.440     www      12046:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12047:  	    }
                   12048:  	}
                   12049:  	untie %bighash;
1.413     www      12050:     }
1.599     albertel 12051:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12052: }
                   12053: 
                   12054: sub deversion {
                   12055:     my $url=shift;
                   12056:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12057:     return $url;
1.210     www      12058: }
                   12059: 
1.31      www      12060: # ------------------------------------------------------ Return symb list entry
                   12061: 
                   12062: sub symbread {
1.1282    raeburn  12063:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265    raeburn  12064:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1282    raeburn  12065:     if (defined($env{$cache_str})) {
                   12066:         if ($ignorecachednull) {
                   12067:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12068:         } else {
                   12069:             return $env{$cache_str};
                   12070:         }
                   12071:     }
1.242     www      12072: # no filename provided? try from environment
1.1265    raeburn  12073:     unless ($thisfn) {
1.620     albertel 12074:         if ($env{'request.symb'}) {
                   12075: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 12076: 	}
1.620     albertel 12077: 	$thisfn=$env{'request.filename'};
1.44      www      12078:     }
1.569     albertel 12079:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12080: # is that filename actually a symb? Verify, clean, and return
                   12081:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12082: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 12083: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12084: 	}
1.242     www      12085:     }
1.44      www      12086:     $thisfn=declutter($thisfn);
1.31      www      12087:     my %hash;
1.37      www      12088:     my %bighash;
                   12089:     my $syval='';
1.620     albertel 12090:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12091:         my $targetfn = $thisfn;
1.609     banghart 12092:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12093:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12094:         }
1.687     albertel 12095: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12096: 	    $targetfn=$1;
                   12097: 	}
1.620     albertel 12098:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12099:                       &GDBM_READER(),0640)) {
1.481     raeburn  12100: 	    $syval=$hash{$targetfn};
1.37      www      12101:             untie(%hash);
                   12102:         }
                   12103: # ---------------------------------------------------------- There was an entry
                   12104:         if ($syval) {
1.601     albertel 12105: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12106: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12107: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12108: 		    #return $env{$cache_str}='';
1.601     albertel 12109: 		#}    
                   12110: 		#$syval.=$1;
                   12111: 	    #}
1.37      www      12112:         } else {
                   12113: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12114:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12115:                             &GDBM_READER(),0640)) {
1.37      www      12116: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12117:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12118:               unless ($ids) { 
                   12119:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12120:               }
                   12121:               unless ($ids) {
                   12122: # alias?
                   12123: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12124:               }
1.37      www      12125:               if ($ids) {
                   12126: # ------------------------------------------------------------------- Has ID(s)
                   12127:                  my @possibilities=split(/\,/,$ids);
1.39      www      12128:                  if ($#possibilities==0) {
                   12129: # ----------------------------------------------- There is only one possibility
1.37      www      12130: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12131: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12132: 						    $resid,$thisfn);
1.1282    raeburn  12133:                      if (ref($possibles) eq 'HASH') {
                   12134:                          $possibles->{$syval} = 1;    
                   12135:                      }
                   12136:                      if ($checkforblock) {
                   12137:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   12138:                          if (@blockers) {
                   12139:                              $syval = '';
                   12140:                              return;
                   12141:                          }
                   12142:                      }
                   12143:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      12144: # ------------------------------------------ There is more than one possibility
                   12145:                      my $realpossible=0;
1.800     albertel 12146:                      foreach my $id (@possibilities) {
                   12147: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  12148:                          my $canaccess;
                   12149:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12150:                              $canaccess = 1;
                   12151:                          } else { 
                   12152:                              $canaccess = &allowed('bre',$file);
                   12153:                          }
                   12154:                          if ($canaccess) {
                   12155:          		     my ($mapid,$resid)=split(/\./,$id);
                   12156:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12157:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12158: 						             $resid,$thisfn);
                   12159:                                  if (ref($possibles) eq 'HASH') {
                   12160:                                      $possibles->{$syval} = 1;
                   12161:                                  }
                   12162:                                  if ($checkforblock) {
                   12163:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   12164:                                      unless (@blockers > 0) {
                   12165:                                          $syval = $poss_syval;
                   12166:                                          $realpossible++;
                   12167:                                      }
                   12168:                                  } else {
                   12169:                                      $syval = $poss_syval;
                   12170:                                      $realpossible++;
                   12171:                                  }
                   12172:                              }
1.39      www      12173: 			 }
1.191     harris41 12174:                      }
1.39      www      12175: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12176:                  } else {
                   12177:                      $syval='';
1.37      www      12178:                  }
                   12179: 	      }
1.1282    raeburn  12180:               untie(%bighash);
1.481     raeburn  12181:            }
1.31      www      12182:         }
1.62      www      12183:         if ($syval) {
1.620     albertel 12184: 	    return $env{$cache_str}=$syval;
1.62      www      12185:         }
1.31      www      12186:     }
1.949     raeburn  12187:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12188:     return $env{$cache_str}='';
1.31      www      12189: }
                   12190: 
                   12191: # ---------------------------------------------------------- Return random seed
                   12192: 
1.32      www      12193: sub numval {
                   12194:     my $txt=shift;
                   12195:     $txt=~tr/A-J/0-9/;
                   12196:     $txt=~tr/a-j/0-9/;
                   12197:     $txt=~tr/K-T/0-9/;
                   12198:     $txt=~tr/k-t/0-9/;
                   12199:     $txt=~tr/U-Z/0-5/;
                   12200:     $txt=~tr/u-z/0-5/;
                   12201:     $txt=~s/\D//g;
1.564     albertel 12202:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12203:     return int($txt);
1.368     albertel 12204: }
                   12205: 
1.484     albertel 12206: sub numval2 {
                   12207:     my $txt=shift;
                   12208:     $txt=~tr/A-J/0-9/;
                   12209:     $txt=~tr/a-j/0-9/;
                   12210:     $txt=~tr/K-T/0-9/;
                   12211:     $txt=~tr/k-t/0-9/;
                   12212:     $txt=~tr/U-Z/0-5/;
                   12213:     $txt=~tr/u-z/0-5/;
                   12214:     $txt=~s/\D//g;
                   12215:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12216:     my $total;
                   12217:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12218:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12219:     return int($total);
                   12220: }
                   12221: 
1.575     albertel 12222: sub numval3 {
                   12223:     use integer;
                   12224:     my $txt=shift;
                   12225:     $txt=~tr/A-J/0-9/;
                   12226:     $txt=~tr/a-j/0-9/;
                   12227:     $txt=~tr/K-T/0-9/;
                   12228:     $txt=~tr/k-t/0-9/;
                   12229:     $txt=~tr/U-Z/0-5/;
                   12230:     $txt=~tr/u-z/0-5/;
                   12231:     $txt=~s/\D//g;
                   12232:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12233:     my $total;
                   12234:     foreach my $val (@txts) { $total+=$val; }
                   12235:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12236:     return $total;
                   12237: }
                   12238: 
1.675     albertel 12239: sub digest {
                   12240:     my ($data)=@_;
                   12241:     my $digest=&Digest::MD5::md5($data);
                   12242:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12243:     my ($e,$f);
                   12244:     {
                   12245:         use integer;
                   12246:         $e=($a+$b);
                   12247:         $f=($c+$d);
                   12248:         if ($_64bit) {
                   12249:             $e=(($e<<32)>>32);
                   12250:             $f=(($f<<32)>>32);
                   12251:         }
                   12252:     }
                   12253:     if (wantarray) {
                   12254: 	return ($e,$f);
                   12255:     } else {
                   12256: 	my $g;
                   12257: 	{
                   12258: 	    use integer;
                   12259: 	    $g=($e+$f);
                   12260: 	    if ($_64bit) {
                   12261: 		$g=(($g<<32)>>32);
                   12262: 	    }
                   12263: 	}
                   12264: 	return $g;
                   12265:     }
                   12266: }
                   12267: 
1.368     albertel 12268: sub latest_rnd_algorithm_id {
1.675     albertel 12269:     return '64bit5';
1.366     albertel 12270: }
1.32      www      12271: 
1.503     albertel 12272: sub get_rand_alg {
                   12273:     my ($courseid)=@_;
1.790     albertel 12274:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12275:     if ($courseid) {
1.620     albertel 12276: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12277:     }
                   12278:     return &latest_rnd_algorithm_id();
                   12279: }
                   12280: 
1.562     albertel 12281: sub validCODE {
                   12282:     my ($CODE)=@_;
                   12283:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12284:     return 0;
                   12285: }
                   12286: 
1.491     albertel 12287: sub getCODE {
1.620     albertel 12288:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12289:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12290: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12291: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12292: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12293:     }
                   12294:     return undef;
                   12295: }
1.1133    foxr     12296: #
                   12297: #  Determines the random seed for a specific context:
                   12298: #
                   12299: # parameters:
                   12300: #   symb      - in course context the symb for the seed.
                   12301: #   course_id - The course id of the form domain_coursenum.
                   12302: #   domain    - Domain for the user.
                   12303: #   course    - Course for the user.
                   12304: #   cenv      - environment of the course.
                   12305: #
                   12306: # NOTE:
                   12307: #   All parameters are picked out of the environment if missing
                   12308: #   or not defined.
                   12309: #   If a symb cannot be determined the current time is used instead.
                   12310: #
                   12311: #  For a given well defined symb, courside, domain, username,
                   12312: #  and course environment, the seed is reproducible.
                   12313: #
1.31      www      12314: sub rndseed {
1.1133    foxr     12315:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12316:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12317:     if (!defined($symb)) {
1.366     albertel 12318: 	unless ($symb=$wsymb) { return time; }
                   12319:     }
1.1146    foxr     12320:     if (!defined $courseid) { 
                   12321: 	$courseid=$wcourseid; 
                   12322:     }
                   12323:     if (!defined $domain) { $domain=$wdomain; }
                   12324:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12325: 
                   12326:     my $which;
                   12327:     if (defined($cenv->{'rndseed'})) {
                   12328: 	$which = $cenv->{'rndseed'};
                   12329:     } else {
                   12330: 	$which =&get_rand_alg($courseid);
                   12331:     }
1.491     albertel 12332:     if (defined(&getCODE())) {
1.1133    foxr     12333: 
1.675     albertel 12334: 	if ($which eq '64bit5') {
                   12335: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12336: 	} elsif ($which eq '64bit4') {
1.575     albertel 12337: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12338: 	} else {
                   12339: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12340: 	}
1.675     albertel 12341:     } elsif ($which eq '64bit5') {
                   12342: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12343:     } elsif ($which eq '64bit4') {
                   12344: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12345:     } elsif ($which eq '64bit3') {
                   12346: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12347:     } elsif ($which eq '64bit2') {
                   12348: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12349:     } elsif ($which eq '64bit') {
                   12350: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12351:     }
                   12352:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12353: }
                   12354: 
                   12355: sub rndseed_32bit {
                   12356:     my ($symb,$courseid,$domain,$username)=@_;
                   12357:     {
                   12358: 	use integer;
                   12359: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12360: 	my $symbseed=numval($symb) << 22;
                   12361: 	my $namechck=unpack("%32C*",$username) << 17;
                   12362: 	my $nameseed=numval($username) << 12;
                   12363: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12364: 	my $courseseed=unpack("%32C*",$courseid);
                   12365: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12366: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12367: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12368: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12369: 	return $num;
                   12370:     }
                   12371: }
                   12372: 
                   12373: sub rndseed_64bit {
                   12374:     my ($symb,$courseid,$domain,$username)=@_;
                   12375:     {
                   12376: 	use integer;
                   12377: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12378: 	my $symbseed=numval($symb) << 10;
                   12379: 	my $namechck=unpack("%32S*",$username);
                   12380: 	
                   12381: 	my $nameseed=numval($username) << 21;
                   12382: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12383: 	my $courseseed=unpack("%32S*",$courseid);
                   12384: 	
                   12385: 	my $num1=$symbchck+$symbseed+$namechck;
                   12386: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12387: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12388: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12389: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12390: 	return "$num1,$num2";
1.155     albertel 12391:     }
1.366     albertel 12392: }
                   12393: 
1.443     albertel 12394: sub rndseed_64bit2 {
                   12395:     my ($symb,$courseid,$domain,$username)=@_;
                   12396:     {
                   12397: 	use integer;
                   12398: 	# strings need to be an even # of cahracters long, it it is odd the
                   12399:         # last characters gets thrown away
                   12400: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12401: 	my $symbseed=numval($symb) << 10;
                   12402: 	my $namechck=unpack("%32S*",$username.' ');
                   12403: 	
                   12404: 	my $nameseed=numval($username) << 21;
1.501     albertel 12405: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12406: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12407: 	
                   12408: 	my $num1=$symbchck+$symbseed+$namechck;
                   12409: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12410: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12411: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12412: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12413: 	return "$num1,$num2";
                   12414:     }
                   12415: }
                   12416: 
                   12417: sub rndseed_64bit3 {
                   12418:     my ($symb,$courseid,$domain,$username)=@_;
                   12419:     {
                   12420: 	use integer;
                   12421: 	# strings need to be an even # of cahracters long, it it is odd the
                   12422:         # last characters gets thrown away
                   12423: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12424: 	my $symbseed=numval2($symb) << 10;
                   12425: 	my $namechck=unpack("%32S*",$username.' ');
                   12426: 	
                   12427: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12428: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12429: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12430: 	
                   12431: 	my $num1=$symbchck+$symbseed+$namechck;
                   12432: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12433: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12434: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12435: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12436: 	
1.503     albertel 12437: 	return "$num1:$num2";
1.443     albertel 12438:     }
                   12439: }
                   12440: 
1.575     albertel 12441: sub rndseed_64bit4 {
                   12442:     my ($symb,$courseid,$domain,$username)=@_;
                   12443:     {
                   12444: 	use integer;
                   12445: 	# strings need to be an even # of cahracters long, it it is odd the
                   12446:         # last characters gets thrown away
                   12447: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12448: 	my $symbseed=numval3($symb) << 10;
                   12449: 	my $namechck=unpack("%32S*",$username.' ');
                   12450: 	
                   12451: 	my $nameseed=numval3($username) << 21;
                   12452: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12453: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12454: 	
                   12455: 	my $num1=$symbchck+$symbseed+$namechck;
                   12456: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12457: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12458: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12459: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12460: 	
1.575     albertel 12461: 	return "$num1:$num2";
                   12462:     }
                   12463: }
                   12464: 
1.675     albertel 12465: sub rndseed_64bit5 {
                   12466:     my ($symb,$courseid,$domain,$username)=@_;
                   12467:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12468:     return "$num1:$num2";
                   12469: }
                   12470: 
1.366     albertel 12471: sub rndseed_CODE_64bit {
                   12472:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12473:     {
1.366     albertel 12474: 	use integer;
1.443     albertel 12475: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12476: 	my $symbseed=numval2($symb);
1.491     albertel 12477: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12478: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12479: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12480: 	my $num1=$symbseed+$CODEchck;
                   12481: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12482: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12483: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12484: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12485: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12486: 	return "$num1:$num2";
1.366     albertel 12487:     }
                   12488: }
                   12489: 
1.575     albertel 12490: sub rndseed_CODE_64bit4 {
                   12491:     my ($symb,$courseid,$domain,$username)=@_;
                   12492:     {
                   12493: 	use integer;
                   12494: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12495: 	my $symbseed=numval3($symb);
                   12496: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12497: 	my $CODEseed=numval3(&getCODE());
                   12498: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12499: 	my $num1=$symbseed+$CODEchck;
                   12500: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12501: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12502: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12503: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12504: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12505: 	return "$num1:$num2";
                   12506:     }
                   12507: }
                   12508: 
1.675     albertel 12509: sub rndseed_CODE_64bit5 {
                   12510:     my ($symb,$courseid,$domain,$username)=@_;
                   12511:     my $code = &getCODE();
                   12512:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12513:     return "$num1:$num2";
                   12514: }
                   12515: 
1.366     albertel 12516: sub setup_random_from_rndseed {
                   12517:     my ($rndseed)=@_;
1.503     albertel 12518:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  12519:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12520:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12521:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   12522:         } else {
                   12523:             &Math::Random::random_set_seed($num1,$num2);
                   12524:         }
1.366     albertel 12525:     } else {
                   12526: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12527:     }
1.36      albertel 12528: }
                   12529: 
1.474     albertel 12530: sub latest_receipt_algorithm_id {
1.835     albertel 12531:     return 'receipt3';
1.474     albertel 12532: }
                   12533: 
1.480     www      12534: sub recunique {
                   12535:     my $fucourseid=shift;
                   12536:     my $unique;
1.835     albertel 12537:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   12538: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12539: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      12540:     } else {
                   12541: 	$unique=$perlvar{'lonReceipt'};
                   12542:     }
                   12543:     return unpack("%32C*",$unique);
                   12544: }
                   12545: 
                   12546: sub recprefix {
                   12547:     my $fucourseid=shift;
                   12548:     my $prefix;
1.835     albertel 12549:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   12550: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12551: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      12552:     } else {
                   12553: 	$prefix=$perlvar{'lonHostID'};
                   12554:     }
                   12555:     return unpack("%32C*",$prefix);
                   12556: }
                   12557: 
1.76      www      12558: sub ireceipt {
1.474     albertel 12559:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 12560: 
                   12561:     my $return =&recprefix($fucourseid).'-';
                   12562: 
                   12563:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   12564: 	$env{'request.state'} eq 'construct') {
                   12565: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   12566: 	return $return;
                   12567:     }
                   12568: 
1.76      www      12569:     my $cuname=unpack("%32C*",$funame);
                   12570:     my $cudom=unpack("%32C*",$fudom);
                   12571:     my $cucourseid=unpack("%32C*",$fucourseid);
                   12572:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      12573:     my $cunique=&recunique($fucourseid);
1.474     albertel 12574:     my $cpart=unpack("%32S*",$part);
1.835     albertel 12575:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   12576: 
1.790     albertel 12577: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 12578: 			       
                   12579: 	$return.= ($cunique%$cuname+
                   12580: 		   $cunique%$cudom+
                   12581: 		   $cusymb%$cuname+
                   12582: 		   $cusymb%$cudom+
                   12583: 		   $cucourseid%$cuname+
                   12584: 		   $cucourseid%$cudom+
                   12585: 		   $cpart%$cuname+
                   12586: 		   $cpart%$cudom);
                   12587:     } else {
                   12588: 	$return.= ($cunique%$cuname+
                   12589: 		   $cunique%$cudom+
                   12590: 		   $cusymb%$cuname+
                   12591: 		   $cusymb%$cudom+
                   12592: 		   $cucourseid%$cuname+
                   12593: 		   $cucourseid%$cudom);
                   12594:     }
                   12595:     return $return;
1.76      www      12596: }
                   12597: 
                   12598: sub receipt {
1.474     albertel 12599:     my ($part)=@_;
1.790     albertel 12600:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 12601:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      12602: }
1.260     ng       12603: 
1.790     albertel 12604: sub whichuser {
                   12605:     my ($passedsymb)=@_;
                   12606:     my ($symb,$courseid,$domain,$name,$publicuser);
                   12607:     if (defined($env{'form.grade_symb'})) {
                   12608: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   12609: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   12610: 	if (!$allowed &&
                   12611: 	    exists($env{'request.course.sec'}) &&
                   12612: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   12613: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   12614: 			      '/'.$env{'request.course.sec'});
                   12615: 	}
                   12616: 	if ($allowed) {
                   12617: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   12618: 	    $courseid=$tmp_courseid;
                   12619: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   12620: 	    ($name)=&get_env_multiple('form.grade_username');
                   12621: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   12622: 	}
                   12623:     }
                   12624:     if (!$passedsymb) {
                   12625: 	$symb=&symbread();
                   12626:     } else {
                   12627: 	$symb=$passedsymb;
                   12628:     }
                   12629:     $courseid=$env{'request.course.id'};
                   12630:     $domain=$env{'user.domain'};
                   12631:     $name=$env{'user.name'};
                   12632:     if ($name eq 'public' && $domain eq 'public') {
                   12633: 	if (!defined($env{'form.username'})) {
                   12634: 	    $env{'form.username'}.=time.rand(10000000);
                   12635: 	}
                   12636: 	$name.=$env{'form.username'};
                   12637:     }
                   12638:     return ($symb,$courseid,$domain,$name,$publicuser);
                   12639: 
                   12640: }
                   12641: 
1.36      albertel 12642: # ------------------------------------------------------------ Serves up a file
1.472     albertel 12643: # returns either the contents of the file or 
                   12644: # -1 if the file doesn't exist
1.481     raeburn  12645: #
                   12646: # if the target is a file that was uploaded via DOCS, 
                   12647: # a check will be made to see if a current copy exists on the local server,
                   12648: # if it does this will be served, otherwise a copy will be retrieved from
                   12649: # the home server for the course and stored in /home/httpd/html/userfiles on
                   12650: # the local server.   
1.472     albertel 12651: 
1.36      albertel 12652: sub getfile {
1.538     albertel 12653:     my ($file) = @_;
1.609     banghart 12654:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 12655:     &repcopy($file);
                   12656:     return &readfile($file);
                   12657: }
                   12658: 
                   12659: sub repcopy_userfile {
                   12660:     my ($file)=@_;
1.1142    raeburn  12661:     my $londocroot = $perlvar{'lonDocRoot'};
                   12662:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  12663:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 12664:     my ($cdom,$cnum,$filename) = 
1.811     albertel 12665: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 12666:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   12667:     if (-e "$file") {
1.828     www      12668: # we already have a local copy, check it out
1.538     albertel 12669: 	my @fileinfo = stat($file);
1.828     www      12670: 	my $rtncode;
                   12671: 	my $info;
1.538     albertel 12672: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 12673: 	if ($lwpresp ne 'ok') {
1.828     www      12674: # there is no such file anymore, even though we had a local copy
1.482     albertel 12675: 	    if ($rtncode eq '404') {
1.538     albertel 12676: 		unlink($file);
1.482     albertel 12677: 	    }
                   12678: 	    return -1;
                   12679: 	}
                   12680: 	if ($info < $fileinfo[9]) {
1.828     www      12681: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  12682: 	    return 'ok';
1.828     www      12683: 	} else {
                   12684: # the file is outdated, get rid of it
                   12685: 	    unlink($file);
1.482     albertel 12686: 	}
1.828     www      12687:     }
                   12688: # one way or the other, at this point, we don't have the file
                   12689: # construct the correct path for the file
                   12690:     my @parts = ($cdom,$cnum); 
                   12691:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   12692: 	push @parts, split(/\//,$1);
                   12693:     }
                   12694:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   12695:     foreach my $part (@parts) {
                   12696: 	$path .= '/'.$part;
                   12697: 	if (!-e $path) {
                   12698: 	    mkdir($path,0770);
1.482     albertel 12699: 	}
                   12700:     }
1.828     www      12701: # now the path exists for sure
                   12702: # get a user agent
                   12703:     my $ua=new LWP::UserAgent;
                   12704:     my $transferfile=$file.'.in.transfer';
                   12705: # FIXME: this should flock
                   12706:     if (-e $transferfile) { return 'ok'; }
                   12707:     my $request;
                   12708:     $uri=~s/^\///;
1.980     raeburn  12709:     my $homeserver = &homeserver($cnum,$cdom);
                   12710:     my $protocol = $protocol{$homeserver};
                   12711:     $protocol = 'http' if ($protocol ne 'https');
                   12712:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      12713:     my $response=$ua->request($request,$transferfile);
                   12714: # did it work?
                   12715:     if ($response->is_error()) {
                   12716: 	unlink($transferfile);
                   12717: 	&logthis("Userfile repcopy failed for $uri");
                   12718: 	return -1;
                   12719:     }
                   12720: # worked, rename the transfer file
                   12721:     rename($transferfile,$file);
1.607     raeburn  12722:     return 'ok';
1.481     raeburn  12723: }
                   12724: 
1.517     albertel 12725: sub tokenwrapper {
                   12726:     my $uri=shift;
1.980     raeburn  12727:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 12728:     $uri=~s|^/||;
1.620     albertel 12729:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 12730:     my $token=$1;
1.552     albertel 12731:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   12732:     if ($udom && $uname && $file) {
                   12733: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  12734:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  12735:         my $homeserver = &homeserver($uname,$udom);
                   12736:         my $protocol = $protocol{$homeserver};
                   12737:         $protocol = 'http' if ($protocol ne 'https');
                   12738:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 12739:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   12740:                                '&tokenissued='.$perlvar{'lonHostID'};
                   12741:     } else {
                   12742:         return '/adm/notfound.html';
                   12743:     }
                   12744: }
                   12745: 
1.828     www      12746: # call with reqtype HEAD: get last modification time
                   12747: # call with reqtype GET: get the file contents
                   12748: # Do not call this with reqtype GET for large files! It loads everything into memory
                   12749: #
1.481     raeburn  12750: sub getuploaded {
                   12751:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   12752:     $uri=~s/^\///;
1.980     raeburn  12753:     my $homeserver = &homeserver($cnum,$cdom);
                   12754:     my $protocol = $protocol{$homeserver};
                   12755:     $protocol = 'http' if ($protocol ne 'https');
                   12756:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  12757:     my $ua=new LWP::UserAgent;
                   12758:     my $request=new HTTP::Request($reqtype,$uri);
                   12759:     my $response=$ua->request($request);
                   12760:     $$rtncode = $response->code;
1.482     albertel 12761:     if (! $response->is_success()) {
                   12762: 	return 'failed';
                   12763:     }      
                   12764:     if ($reqtype eq 'HEAD') {
1.486     www      12765: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 12766:     } elsif ($reqtype eq 'GET') {
                   12767: 	$$info = $response->content;
1.472     albertel 12768:     }
1.482     albertel 12769:     return 'ok';
1.36      albertel 12770: }
                   12771: 
1.481     raeburn  12772: sub readfile {
                   12773:     my $file = shift;
                   12774:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   12775:     my $fh;
                   12776:     open($fh,"<$file");
                   12777:     my $a='';
1.800     albertel 12778:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  12779:     return $a;
                   12780: }
                   12781: 
1.36      albertel 12782: sub filelocation {
1.590     banghart 12783:     my ($dir,$file) = @_;
                   12784:     my $location;
                   12785:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 12786: 
                   12787:     if ($file =~ m-^/adm/-) {
                   12788: 	$file=~s-^/adm/wrapper/-/-;
                   12789: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   12790:     }
1.882     albertel 12791: 
1.1139    www      12792:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  12793:         $location = $file;
1.609     banghart 12794:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 12795:         my ($udom,$uname,$filename)=
1.811     albertel 12796:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 12797:         my $home=&homeserver($uname,$udom);
                   12798:         my $is_me=0;
                   12799:         my @ids=&current_machine_ids();
                   12800:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   12801:         if ($is_me) {
1.1117    foxr     12802:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 12803:         } else {
                   12804:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   12805:   	      $udom.'/'.$uname.'/'.$filename;
                   12806:         }
1.882     albertel 12807:     } elsif ($file =~ m-^/adm/-) {
                   12808: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 12809:     } else {
                   12810:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      12811:         $file=~s:^/(res|priv)/:/:;
                   12812:         my $space=$1;
1.590     banghart 12813:         if ( !( $file =~ m:^/:) ) {
                   12814:             $location = $dir. '/'.$file;
                   12815:         } else {
1.1142    raeburn  12816:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 12817:         }
1.59      albertel 12818:     }
1.590     banghart 12819:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 12820:     while ($location=~m{/\.\./}) {
                   12821: 	if ($location =~ m{/[^/]+/\.\./}) {
                   12822: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   12823: 	} else {
                   12824: 	    $location=~ s{/\.\./}{/}g;
                   12825: 	}
                   12826:     } #remove dir/..
1.590     banghart 12827:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   12828:     return $location;
1.46      www      12829: }
1.36      albertel 12830: 
1.46      www      12831: sub hreflocation {
                   12832:     my ($dir,$file)=@_;
1.980     raeburn  12833:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 12834: 	$file=filelocation($dir,$file);
1.700     albertel 12835:     } elsif ($file=~m-^/adm/-) {
                   12836: 	$file=~s-^/adm/wrapper/-/-;
                   12837: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 12838:     }
                   12839:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   12840: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   12841:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  12842: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   12843: 	        {/uploaded/$1/$2/}x;
1.46      www      12844:     }
1.913     albertel 12845:     if ($file=~ m{^/userfiles/}) {
                   12846: 	$file =~ s{^/userfiles/}{/uploaded/};
                   12847:     }
1.462     albertel 12848:     return $file;
1.465     albertel 12849: }
                   12850: 
1.1139    www      12851: 
                   12852: 
                   12853: 
                   12854: 
1.465     albertel 12855: sub current_machine_domains {
1.853     albertel 12856:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   12857: }
                   12858: 
                   12859: sub machine_domains {
                   12860:     my ($hostname) = @_;
1.465     albertel 12861:     my @domains;
1.838     albertel 12862:     my %hostname = &all_hostnames();
1.465     albertel 12863:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  12864: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 12865: 	if ($hostname eq $name) {
1.844     albertel 12866: 	    push(@domains,&host_domain($id));
1.465     albertel 12867: 	}
                   12868:     }
                   12869:     return @domains;
                   12870: }
                   12871: 
                   12872: sub current_machine_ids {
1.853     albertel 12873:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   12874: }
                   12875: 
                   12876: sub machine_ids {
                   12877:     my ($hostname) = @_;
                   12878:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 12879:     my @ids;
1.888     albertel 12880:     my %name_to_host = &all_names();
1.889     albertel 12881:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   12882: 	return @{ $name_to_host{$hostname} };
                   12883:     }
                   12884:     return;
1.31      www      12885: }
                   12886: 
1.824     raeburn  12887: sub additional_machine_domains {
                   12888:     my @domains;
                   12889:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   12890:     while( my $line = <$fh>) {
                   12891:         $line =~ s/\s//g;
                   12892:         push(@domains,$line);
                   12893:     }
                   12894:     return @domains;
                   12895: }
                   12896: 
                   12897: sub default_login_domain {
                   12898:     my $domain = $perlvar{'lonDefDomain'};
                   12899:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   12900:     foreach my $posdom (&current_machine_domains(),
                   12901:                         &additional_machine_domains()) {
                   12902:         if (lc($posdom) eq lc($testdomain)) {
                   12903:             $domain=$posdom;
                   12904:             last;
                   12905:         }
                   12906:     }
                   12907:     return $domain;
                   12908: }
                   12909: 
1.31      www      12910: # ------------------------------------------------------------- Declutters URLs
                   12911: 
                   12912: sub declutter {
                   12913:     my $thisfn=shift;
1.569     albertel 12914:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  12915:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   12916:         $thisfn=~s{^/home/httpd/html}{};
                   12917:     }
1.31      www      12918:     $thisfn=~s/^\///;
1.697     albertel 12919:     $thisfn=~s|^adm/wrapper/||;
                   12920:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      12921:     $thisfn=~s/^res\///;
1.1172    bisitz   12922:     $thisfn=~s/^priv\///;
1.1032    raeburn  12923:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   12924:         $thisfn=~s/\?.+$//;
                   12925:     }
1.268     www      12926:     return $thisfn;
                   12927: }
                   12928: 
                   12929: # ------------------------------------------------------------- Clutter up URLs
                   12930: 
                   12931: sub clutter {
                   12932:     my $thisfn='/'.&declutter(shift);
1.887     albertel 12933:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 12934: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      12935:        $thisfn='/res'.$thisfn; 
                   12936:     }
1.1031    raeburn  12937:     if ($thisfn !~m|^/adm|) {
                   12938: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 12939: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 12940: 	} else {
                   12941: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   12942: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 12943: 	    if ($embstyle eq 'ssi'
                   12944: 		|| ($embstyle eq 'hdn')
                   12945: 		|| ($embstyle eq 'rat')
                   12946: 		|| ($embstyle eq 'prv')
                   12947: 		|| ($embstyle eq 'ign')) {
                   12948: 		#do nothing with these
                   12949: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 12950: 		|| ($embstyle eq 'emb')
                   12951: 		|| ($embstyle eq 'wrp')) {
                   12952: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 12953: 	    } elsif ($embstyle eq 'unk'
                   12954: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 12955: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 12956: 	    } else {
1.718     www      12957: #		&logthis("Got a blank emb style");
1.695     albertel 12958: 	    }
1.694     albertel 12959: 	}
1.1298    raeburn  12960:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/exttools?$}) {
                   12961:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 12962:     }
1.31      www      12963:     return $thisfn;
1.12      www      12964: }
                   12965: 
1.787     albertel 12966: sub clutter_with_no_wrapper {
                   12967:     my $uri = &clutter(shift);
                   12968:     if ($uri =~ m-^/adm/-) {
                   12969: 	$uri =~ s-^/adm/wrapper/-/-;
                   12970: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   12971:     }
                   12972:     return $uri;
                   12973: }
                   12974: 
1.557     albertel 12975: sub freeze_escape {
                   12976:     my ($value)=@_;
                   12977:     if (ref($value)) {
                   12978: 	$value=&nfreeze($value);
                   12979: 	return '__FROZEN__'.&escape($value);
                   12980:     }
                   12981:     return &escape($value);
                   12982: }
                   12983: 
1.11      www      12984: 
1.557     albertel 12985: sub thaw_unescape {
                   12986:     my ($value)=@_;
                   12987:     if ($value =~ /^__FROZEN__/) {
                   12988: 	substr($value,0,10,undef);
                   12989: 	$value=&unescape($value);
                   12990: 	return &thaw($value);
                   12991:     }
                   12992:     return &unescape($value);
                   12993: }
                   12994: 
1.436     albertel 12995: sub correct_line_ends {
                   12996:     my ($result)=@_;
                   12997:     $$result =~s/\r\n/\n/mg;
                   12998:     $$result =~s/\r/\n/mg;
1.415     albertel 12999: }
1.1       albertel 13000: # ================================================================ Main Program
                   13001: 
1.184     www      13002: sub goodbye {
1.204     albertel 13003:    &logthis("Starting Shut down");
1.443     albertel 13004: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13005:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13006: #converted
1.599     albertel 13007: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13008:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13009: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13010: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13011: #1.1 only
1.870     albertel 13012: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13013: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13014: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13015: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13016:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13017:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13018:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13019:    &flushcourselogs();
                   13020:    &logthis("Shutting down");
                   13021: }
                   13022: 
1.852     albertel 13023: sub get_dns {
1.1210    raeburn  13024:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13025:     if (!$ignore_cache) {
                   13026: 	my ($content,$cached)=
                   13027: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13028: 	if ($cached) {
1.1210    raeburn  13029: 	    &$func($content,$hashref);
1.869     albertel 13030: 	    return;
                   13031: 	}
                   13032:     }
                   13033: 
                   13034:     my %alldns;
1.852     albertel 13035:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   13036:     foreach my $dns (<$config>) {
                   13037: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  13038:         my $line = $1;
                   13039:         my ($host,$protocol) = split(/:/,$line);
                   13040:         if ($protocol ne 'https') {
                   13041:             $protocol = 'http';
                   13042:         }
                   13043: 	$alldns{$host} = $protocol;
1.869     albertel 13044:     }
                   13045:     while (%alldns) {
1.1263    raeburn  13046: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 13047: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  13048:         $ua->timeout(30);
1.979     raeburn  13049: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 13050: 	my $response=$ua->request($request);
1.979     raeburn  13051:         delete($alldns{$dns});
1.852     albertel 13052: 	next if ($response->is_error());
                   13053: 	my @content = split("\n",$response->content);
1.1210    raeburn  13054: 	unless ($nocache) {
1.1219    raeburn  13055: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210    raeburn  13056: 	}
                   13057: 	&$func(\@content,$hashref);
1.869     albertel 13058: 	return;
1.852     albertel 13059:     }
                   13060:     close($config);
1.871     albertel 13061:     my $which = (split('/',$url))[3];
                   13062:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   13063:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 13064:     my @content = <$config>;
1.1210    raeburn  13065:     &$func(\@content,$hashref);
                   13066:     return;
                   13067: }
                   13068: 
                   13069: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  13070: sub parse_dns_checksums_tab {
1.1210    raeburn  13071:     my ($lines,$hashref) = @_;
1.1264    raeburn  13072:     my $lonhost = $perlvar{'lonHostID'};
                   13073:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  13074:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  13075:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13076:     my $webconfdir = '/etc/httpd/conf';
                   13077:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13078:         $webconfdir = '/etc/apache2';
                   13079:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13080:         if ($1 >= 10) {
                   13081:             $webconfdir = '/etc/apache2';
                   13082:         }
                   13083:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13084:         if ($1 >= 10.0) {
                   13085:             $webconfdir = '/etc/apache2';
                   13086:         }
                   13087:     }
1.1210    raeburn  13088:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13089:     my (%chksum,%revnum);
                   13090:     if (ref($lines) eq 'ARRAY') {
                   13091:         chomp(@{$lines});
1.1238    raeburn  13092:         my $version = shift(@{$lines});
                   13093:         if ($version eq $release) {  
1.1210    raeburn  13094:             foreach my $line (@{$lines}) {
1.1238    raeburn  13095:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  13096:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13097:                     if ($webconfdir eq '/etc/apache2') {
                   13098:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13099:                     }
                   13100:                 }
1.1238    raeburn  13101:                 $chksum{$file} = $shasum;
                   13102:                 $revnum{$file} = $version;
1.1210    raeburn  13103:             }
                   13104:             if (ref($hashref) eq 'HASH') {
                   13105:                 %{$hashref} = (
                   13106:                                 sums     => \%chksum,
                   13107:                                 versions => \%revnum,
                   13108:                               );
                   13109:             }
                   13110:         }
                   13111:     }
1.869     albertel 13112:     return;
1.852     albertel 13113: }
1.1210    raeburn  13114: 
                   13115: sub fetch_dns_checksums {
1.1238    raeburn  13116:     my %checksums;
                   13117:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  13118:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  13119:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13120:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  13121:              \%checksums);
1.1210    raeburn  13122:     return \%checksums;
                   13123: }
                   13124: 
1.327     albertel 13125: # ------------------------------------------------------------ Read domain file
                   13126: {
1.852     albertel 13127:     my $loaded;
1.846     albertel 13128:     my %domain;
                   13129: 
1.852     albertel 13130:     sub parse_domain_tab {
                   13131: 	my ($lines) = @_;
                   13132: 	foreach my $line (@$lines) {
                   13133: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13134: 
1.846     albertel 13135: 	    chomp($line);
1.852     albertel 13136: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13137: 	    my %this_domain;
                   13138: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13139: 			       'lang_def', 'city', 'longi', 'lati',
                   13140: 			       'primary') {
                   13141: 		$this_domain{$field} = shift(@elements);
                   13142: 	    }
                   13143: 	    $domain{$name} = \%this_domain;
1.852     albertel 13144: 	}
                   13145:     }
1.864     albertel 13146: 
                   13147:     sub reset_domain_info {
                   13148: 	undef($loaded);
                   13149: 	undef(%domain);
                   13150:     }
                   13151: 
1.852     albertel 13152:     sub load_domain_tab {
1.1293    raeburn  13153: 	my ($ignore_cache,$nocache) = @_;
                   13154: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13155: 	my $fh;
                   13156: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   13157: 	    my @lines = <$fh>;
                   13158: 	    &parse_domain_tab(\@lines);
1.448     albertel 13159: 	}
1.852     albertel 13160: 	close($fh);
                   13161: 	$loaded = 1;
1.327     albertel 13162:     }
1.846     albertel 13163: 
                   13164:     sub domain {
1.852     albertel 13165: 	&load_domain_tab() if (!$loaded);
                   13166: 
1.846     albertel 13167: 	my ($name,$what) = @_;
                   13168: 	return if ( !exists($domain{$name}) );
                   13169: 
                   13170: 	if (!$what) {
                   13171: 	    return $domain{$name}{'description'};
                   13172: 	}
                   13173: 	return $domain{$name}{$what};
                   13174:     }
1.974     raeburn  13175: 
                   13176:     sub domain_info {
                   13177:         &load_domain_tab() if (!$loaded);
                   13178:         return %domain;
                   13179:     }
                   13180: 
1.327     albertel 13181: }
                   13182: 
                   13183: 
1.1       albertel 13184: # ------------------------------------------------------------- Read hosts file
                   13185: {
1.838     albertel 13186:     my %hostname;
1.844     albertel 13187:     my %hostdom;
1.845     albertel 13188:     my %libserv;
1.852     albertel 13189:     my $loaded;
1.888     albertel 13190:     my %name_to_host;
1.1074    raeburn  13191:     my %internetdom;
1.1107    raeburn  13192:     my %LC_dns_serv;
1.852     albertel 13193: 
                   13194:     sub parse_hosts_tab {
                   13195: 	my ($file) = @_;
                   13196: 	foreach my $configline (@$file) {
                   13197: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13198:             chomp($configline);
                   13199: 	    if ($configline =~ /^\^/) {
                   13200:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13201:                     $LC_dns_serv{$1} = 1;
                   13202:                 }
                   13203:                 next;
                   13204:             }
1.1074    raeburn  13205: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13206: 	    $name=~s/\s//g;
                   13207: 	    if ($id && $domain && $role && $name) {
                   13208: 		$hostname{$id}=$name;
1.888     albertel 13209: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 13210: 		$hostdom{$id}=$domain;
                   13211: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13212:                 if (defined($protocol)) {
                   13213:                     if ($protocol eq 'https') {
                   13214:                         $protocol{$id} = $protocol;
                   13215:                     } else {
                   13216:                         $protocol{$id} = 'http'; 
                   13217:                     }
1.968     raeburn  13218:                 } else {
1.969     raeburn  13219:                     $protocol{$id} = 'http';
1.968     raeburn  13220:                 }
1.1074    raeburn  13221:                 if (defined($intdom)) {
                   13222:                     $internetdom{$id} = $intdom;
                   13223:                 }
1.852     albertel 13224: 	    }
                   13225: 	}
                   13226:     }
1.864     albertel 13227:     
                   13228:     sub reset_hosts_info {
1.897     albertel 13229: 	&purge_remembered();
1.864     albertel 13230: 	&reset_domain_info();
                   13231: 	&reset_hosts_ip_info();
1.892     albertel 13232: 	undef(%name_to_host);
1.864     albertel 13233: 	undef(%hostname);
                   13234: 	undef(%hostdom);
                   13235: 	undef(%libserv);
                   13236: 	undef($loaded);
                   13237:     }
1.1       albertel 13238: 
1.852     albertel 13239:     sub load_hosts_tab {
1.1293    raeburn  13240: 	my ($ignore_cache,$nocache) = @_;
                   13241: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852     albertel 13242: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   13243: 	my @config = <$config>;
                   13244: 	&parse_hosts_tab(\@config);
                   13245: 	close($config);
                   13246: 	$loaded=1;
1.1       albertel 13247:     }
1.852     albertel 13248: 
1.838     albertel 13249:     sub hostname {
1.852     albertel 13250: 	&load_hosts_tab() if (!$loaded);
                   13251: 
1.838     albertel 13252: 	my ($lonid) = @_;
                   13253: 	return $hostname{$lonid};
                   13254:     }
1.845     albertel 13255: 
1.838     albertel 13256:     sub all_hostnames {
1.852     albertel 13257: 	&load_hosts_tab() if (!$loaded);
                   13258: 
1.838     albertel 13259: 	return %hostname;
                   13260:     }
1.845     albertel 13261: 
1.888     albertel 13262:     sub all_names {
1.1293    raeburn  13263:         my ($ignore_cache,$nocache) = @_;
                   13264: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13265: 
                   13266: 	return %name_to_host;
                   13267:     }
                   13268: 
1.974     raeburn  13269:     sub all_host_domain {
                   13270:         &load_hosts_tab() if (!$loaded);
                   13271:         return %hostdom;
                   13272:     }
                   13273: 
1.845     albertel 13274:     sub is_library {
1.852     albertel 13275: 	&load_hosts_tab() if (!$loaded);
                   13276: 
1.845     albertel 13277: 	return exists($libserv{$_[0]});
                   13278:     }
                   13279: 
                   13280:     sub all_library {
1.852     albertel 13281: 	&load_hosts_tab() if (!$loaded);
                   13282: 
1.845     albertel 13283: 	return %libserv;
                   13284:     }
                   13285: 
1.1062    droeschl 13286:     sub unique_library {
                   13287: 	#2x reverse removes all hostnames that appear more than once
                   13288:         my %unique = reverse &all_library();
                   13289:         return reverse %unique;
                   13290:     }
                   13291: 
1.841     albertel 13292:     sub get_servers {
1.852     albertel 13293: 	&load_hosts_tab() if (!$loaded);
                   13294: 
1.841     albertel 13295: 	my ($domain,$type) = @_;
                   13296: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13297: 	                                          : %hostname;
                   13298: 	my %result;
1.842     albertel 13299: 	if (ref($domain) eq 'ARRAY') {
                   13300: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13301: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13302: 		    $result{$host} = $hostname;
                   13303: 		}
                   13304: 	    }
                   13305: 	} else {
                   13306: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13307: 		if ($hostdom{$host} eq $domain) {
                   13308: 		    $result{$host} = $hostname;
                   13309: 		}
1.841     albertel 13310: 	    }
                   13311: 	}
                   13312: 	return %result;
                   13313:     }
1.845     albertel 13314: 
1.1062    droeschl 13315:     sub get_unique_servers {
                   13316:         my %unique = reverse &get_servers(@_);
                   13317: 	return reverse %unique;
                   13318:     }
                   13319: 
1.844     albertel 13320:     sub host_domain {
1.852     albertel 13321: 	&load_hosts_tab() if (!$loaded);
                   13322: 
1.844     albertel 13323: 	my ($lonid) = @_;
                   13324: 	return $hostdom{$lonid};
                   13325:     }
                   13326: 
1.841     albertel 13327:     sub all_domains {
1.852     albertel 13328: 	&load_hosts_tab() if (!$loaded);
                   13329: 
1.841     albertel 13330: 	my %seen;
                   13331: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13332: 	return @uniq;
                   13333:     }
1.1074    raeburn  13334: 
                   13335:     sub internet_dom {
                   13336:         &load_hosts_tab() if (!$loaded);
                   13337: 
                   13338:         my ($lonid) = @_;
                   13339:         return $internetdom{$lonid};
                   13340:     }
1.1107    raeburn  13341: 
                   13342:     sub is_LC_dns {
                   13343:         &load_hosts_tab() if (!$loaded);
                   13344: 
                   13345:         my ($hostname) = @_;
                   13346:         return exists($LC_dns_serv{$hostname});
                   13347:     }
                   13348: 
1.1       albertel 13349: }
                   13350: 
1.847     albertel 13351: { 
                   13352:     my %iphost;
1.856     albertel 13353:     my %name_to_ip;
                   13354:     my %lonid_to_ip;
1.869     albertel 13355: 
1.847     albertel 13356:     sub get_hosts_from_ip {
                   13357: 	my ($ip) = @_;
                   13358: 	my %iphosts = &get_iphost();
                   13359: 	if (ref($iphosts{$ip})) {
                   13360: 	    return @{$iphosts{$ip}};
                   13361: 	}
                   13362: 	return;
1.839     albertel 13363:     }
1.864     albertel 13364:     
                   13365:     sub reset_hosts_ip_info {
                   13366: 	undef(%iphost);
                   13367: 	undef(%name_to_ip);
                   13368: 	undef(%lonid_to_ip);
                   13369:     }
1.856     albertel 13370: 
                   13371:     sub get_host_ip {
                   13372: 	my ($lonid) = @_;
                   13373: 	if (exists($lonid_to_ip{$lonid})) {
                   13374: 	    return $lonid_to_ip{$lonid};
                   13375: 	}
                   13376: 	my $name=&hostname($lonid);
                   13377:    	my $ip = gethostbyname($name);
                   13378: 	return if (!$ip || length($ip) ne 4);
                   13379: 	$ip=inet_ntoa($ip);
                   13380: 	$name_to_ip{$name}   = $ip;
                   13381: 	$lonid_to_ip{$lonid} = $ip;
                   13382: 	return $ip;
                   13383:     }
1.847     albertel 13384:     
                   13385:     sub get_iphost {
1.1293    raeburn  13386: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13387: 
1.869     albertel 13388: 	if (!$ignore_cache) {
                   13389: 	    if (%iphost) {
                   13390: 		return %iphost;
                   13391: 	    }
                   13392: 	    my ($ip_info,$cached)=
                   13393: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13394: 	    if ($cached) {
                   13395: 		%iphost      = %{$ip_info->[0]};
                   13396: 		%name_to_ip  = %{$ip_info->[1]};
                   13397: 		%lonid_to_ip = %{$ip_info->[2]};
                   13398: 		return %iphost;
                   13399: 	    }
                   13400: 	}
1.894     albertel 13401: 
                   13402: 	# get yesterday's info for fallback
                   13403: 	my %old_name_to_ip;
                   13404: 	my ($ip_info,$cached)=
                   13405: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13406: 	if ($cached) {
                   13407: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13408: 	}
                   13409: 
1.1293    raeburn  13410: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13411: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13412: 	    my $ip;
                   13413: 	    if (!exists($name_to_ip{$name})) {
                   13414: 		$ip = gethostbyname($name);
                   13415: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13416: 		    if (defined($old_name_to_ip{$name})) {
                   13417: 			$ip = $old_name_to_ip{$name};
                   13418: 			&logthis("Can't find $name defaulting to old $ip");
                   13419: 		    } else {
                   13420: 			&logthis("Name $name no IP found");
                   13421: 			next;
                   13422: 		    }
                   13423: 		} else {
                   13424: 		    $ip=inet_ntoa($ip);
1.847     albertel 13425: 		}
                   13426: 		$name_to_ip{$name} = $ip;
                   13427: 	    } else {
                   13428: 		$ip = $name_to_ip{$name};
1.653     albertel 13429: 	    }
1.888     albertel 13430: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13431: 		$lonid_to_ip{$id} = $ip;
                   13432: 	    }
                   13433: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13434: 	}
1.1293    raeburn  13435:         unless ($nocache) {
                   13436: 	    &do_cache_new('iphost','iphost',
                   13437: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   13438: 		          48*60*60);
                   13439:         }
1.869     albertel 13440: 
1.847     albertel 13441: 	return %iphost;
1.598     albertel 13442:     }
                   13443: 
1.992     raeburn  13444:     #
                   13445:     #  Given a DNS returns the loncapa host name for that DNS 
                   13446:     # 
                   13447:     sub host_from_dns {
                   13448:         my ($dns) = @_;
                   13449:         my @hosts;
                   13450:         my $ip;
                   13451: 
1.993     raeburn  13452:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  13453:             $ip = $name_to_ip{$dns};
                   13454:         }
                   13455:         if (!$ip) {
                   13456:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   13457:             if (length($ip) == 4) { 
                   13458: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   13459:             }
                   13460:         }
                   13461:         if ($ip) {
                   13462: 	    @hosts = get_hosts_from_ip($ip);
                   13463: 	    return $hosts[0];
                   13464:         }
                   13465:         return undef;
1.986     foxr     13466:     }
1.992     raeburn  13467: 
1.1074    raeburn  13468:     sub get_internet_names {
                   13469:         my ($lonid) = @_;
                   13470:         return if ($lonid eq '');
                   13471:         my ($idnref,$cached)=
                   13472:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   13473:         if ($cached) {
                   13474:             return $idnref;
                   13475:         }
                   13476:         my $ip = &get_host_ip($lonid);
                   13477:         my @hosts = &get_hosts_from_ip($ip);
                   13478:         my %iphost = &get_iphost();
                   13479:         my (@idns,%seen);
                   13480:         foreach my $id (@hosts) {
                   13481:             my $dom = &host_domain($id);
                   13482:             my $prim_id = &domain($dom,'primary');
                   13483:             my $prim_ip = &get_host_ip($prim_id);
                   13484:             next if ($seen{$prim_ip});
                   13485:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   13486:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   13487:                     my $intdom = &internet_dom($id);
                   13488:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   13489:                         push(@idns,$intdom);
                   13490:                     }
                   13491:                 }
                   13492:             }
                   13493:             $seen{$prim_ip} = 1;
                   13494:         }
1.1219    raeburn  13495:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  13496:     }
                   13497: 
1.986     foxr     13498: }
                   13499: 
1.1079    raeburn  13500: sub all_loncaparevs {
1.1249    raeburn  13501:     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  13502: }
                   13503: 
1.1227    raeburn  13504: # ---------------------------------------------------------- Read loncaparev table
                   13505: {
                   13506:     sub load_loncaparevs { 
                   13507:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   13508:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   13509:                 while (my $configline=<$config>) {
                   13510:                     chomp($configline);
                   13511:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   13512:                     $loncaparevs{$hostid}=$loncaparev;
                   13513:                 }
                   13514:                 close($config);
                   13515:             }
                   13516:         }
                   13517:     }
                   13518: }
                   13519: 
                   13520: # ---------------------------------------------------------- Read serverhostID table
                   13521: {
                   13522:     sub load_serverhomeIDs {
                   13523:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   13524:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   13525:                 while (my $configline=<$config>) {
                   13526:                     chomp($configline);
                   13527:                     my ($name,$id)=split(/:/,$configline);
                   13528:                     $serverhomeIDs{$name}=$id;
                   13529:                 }
                   13530:                 close($config);
                   13531:             }
                   13532:         }
                   13533:     }
                   13534: }
                   13535: 
                   13536: 
1.862     albertel 13537: BEGIN {
                   13538: 
                   13539: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   13540:     unless ($readit) {
                   13541: {
                   13542:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   13543:     %perlvar = (%perlvar,%{$configvars});
                   13544: }
                   13545: 
                   13546: 
1.1       albertel 13547: # ------------------------------------------------------ Read spare server file
                   13548: {
1.448     albertel 13549:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 13550: 
                   13551:     while (my $configline=<$config>) {
                   13552:        chomp($configline);
1.284     matthew  13553:        if ($configline) {
1.784     albertel 13554: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 13555: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 13556: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 13557:        }
                   13558:     }
1.448     albertel 13559:     close($config);
1.1       albertel 13560: }
1.11      www      13561: # ------------------------------------------------------------ Read permissions
                   13562: {
1.448     albertel 13563:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      13564: 
                   13565:     while (my $configline=<$config>) {
1.448     albertel 13566: 	chomp($configline);
                   13567: 	if ($configline) {
                   13568: 	    my ($role,$perm)=split(/ /,$configline);
                   13569: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   13570: 	}
1.11      www      13571:     }
1.448     albertel 13572:     close($config);
1.11      www      13573: }
                   13574: 
                   13575: # -------------------------------------------- Read plain texts for permissions
                   13576: {
1.448     albertel 13577:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      13578: 
                   13579:     while (my $configline=<$config>) {
1.448     albertel 13580: 	chomp($configline);
                   13581: 	if ($configline) {
1.742     raeburn  13582: 	    my ($short,@plain)=split(/:/,$configline);
                   13583:             %{$prp{$short}} = ();
                   13584: 	    if (@plain > 0) {
                   13585:                 $prp{$short}{'std'} = $plain[0];
                   13586:                 for (my $i=1; $i<@plain; $i++) {
                   13587:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   13588:                 }
                   13589:             }
1.448     albertel 13590: 	}
1.135     www      13591:     }
1.448     albertel 13592:     close($config);
1.135     www      13593: }
                   13594: 
                   13595: # ---------------------------------------------------------- Read package table
                   13596: {
1.448     albertel 13597:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      13598: 
                   13599:     while (my $configline=<$config>) {
1.483     albertel 13600: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 13601: 	chomp($configline);
                   13602: 	my ($short,$plain)=split(/:/,$configline);
                   13603: 	my ($pack,$name)=split(/\&/,$short);
                   13604: 	if ($plain ne '') {
                   13605: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   13606: 	    $packagetab{$short}=$plain; 
                   13607: 	}
1.11      www      13608:     }
1.448     albertel 13609:     close($config);
1.329     matthew  13610: }
                   13611: 
1.1073    raeburn  13612: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  13613: 
                   13614: &load_loncaparevs();
1.1073    raeburn  13615: 
1.1074    raeburn  13616: # ---------------------------------------------------------- Read serverhostID table
                   13617: 
1.1227    raeburn  13618: &load_serverhomeIDs();
                   13619: 
                   13620: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  13621: {
                   13622:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   13623:     if (-e $file) {
                   13624:         my $parser = HTML::LCParser->new($file);
                   13625:         while (my $token = $parser->get_token()) {
                   13626:             if ($token->[0] eq 'S') {
                   13627:                 my $item = $token->[1];
                   13628:                 my $name = $token->[2]{'name'};
                   13629:                 my $value = $token->[2]{'value'};
1.1285    raeburn  13630:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  13631:                 my $namematch = $token->[2]{'namematch'};
                   13632:                 if ($item eq 'parameter') {
                   13633:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   13634:                         my $release = $parser->get_text();
                   13635:                         $release =~ s/(^\s*|\s*$ )//gx;
                   13636:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   13637:                     }
                   13638:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  13639:                     my $release = $parser->get_text();
                   13640:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  13641:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  13642:                 }
                   13643:             }
                   13644:         }
                   13645:     }
1.1073    raeburn  13646: }
                   13647: 
1.1138    raeburn  13648: # ---------------------------------------------------------- Read managers table
                   13649: {
                   13650:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   13651:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   13652:             while (my $configline=<$config>) {
                   13653:                 chomp($configline);
                   13654:                 next if ($configline =~ /^\#/);
                   13655:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   13656:                     $managerstab{$configline} = 1;
                   13657:                 }
                   13658:             }
                   13659:             close($config);
                   13660:         }
                   13661:     }
                   13662: }
                   13663: 
1.329     matthew  13664: # ------------- set up temporary directory
                   13665: {
1.1117    foxr     13666:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  13667: 
1.11      www      13668: }
                   13669: 
1.794     albertel 13670: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   13671: 				'compress_threshold'=> 20_000,
                   13672:  			        });
1.185     www      13673: 
1.281     www      13674: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      13675: $dumpcount=0;
1.958     www      13676: $locknum=0;
1.22      www      13677: 
1.163     harris41 13678: &logtouch();
1.672     albertel 13679: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      13680: $readit=1;
1.564     albertel 13681:     {
                   13682: 	use integer;
                   13683: 	my $test=(2**32)+1;
1.568     albertel 13684: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 13685: 	&logthis(" Detected 64bit platform ($_64bit)");
                   13686:     }
1.195     www      13687: }
1.1       albertel 13688: }
1.179     www      13689: 
1.1       albertel 13690: 1;
1.191     harris41 13691: __END__
                   13692: 
1.243     albertel 13693: =pod
                   13694: 
1.191     harris41 13695: =head1 NAME
                   13696: 
1.243     albertel 13697: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 13698: 
                   13699: =head1 SYNOPSIS
                   13700: 
1.243     albertel 13701: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 13702: 
                   13703:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   13704: 
1.243     albertel 13705: Common parameters:
                   13706: 
                   13707: =over 4
                   13708: 
                   13709: =item *
                   13710: 
                   13711: $uname : an internal username (if $cname expecting a course Id specifically)
                   13712: 
                   13713: =item *
                   13714: 
                   13715: $udom : a domain (if $cdom expecting a course's domain specifically)
                   13716: 
                   13717: =item *
                   13718: 
                   13719: $symb : a resource instance identifier
                   13720: 
                   13721: =item *
                   13722: 
                   13723: $namespace : the name of a .db file that contains the data needed or
                   13724: being set.
                   13725: 
                   13726: =back
                   13727: 
1.394     bowersj2 13728: =head1 OVERVIEW
1.191     harris41 13729: 
1.394     bowersj2 13730: lonnet provides subroutines which interact with the
                   13731: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   13732: about classes, users, and resources.
1.243     albertel 13733: 
                   13734: For many of these objects you can also use this to store data about
                   13735: them or modify them in various ways.
1.191     harris41 13736: 
1.394     bowersj2 13737: =head2 Symbs
1.191     harris41 13738: 
1.394     bowersj2 13739: To identify a specific instance of a resource, LON-CAPA uses symbols
                   13740: or "symbs"X<symb>. These identifiers are built from the URL of the
                   13741: map, the resource number of the resource in the map, and the URL of
                   13742: the resource itself. The latter is somewhat redundant, but might help
                   13743: if maps change.
                   13744: 
                   13745: An example is
                   13746: 
                   13747:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   13748: 
                   13749: The respective map entry is
                   13750: 
                   13751:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   13752:   title="Problem 2">
                   13753:  </resource>
                   13754: 
                   13755: Symbs are used by the random number generator, as well as to store and
                   13756: restore data specific to a certain instance of for example a problem.
                   13757: 
                   13758: =head2 Storing And Retrieving Data
                   13759: 
                   13760: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   13761: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   13762: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   13763: is is the non-critical message twin of cstore. These functions are for
                   13764: handlers to store a perl hash to a user's permanent data space in an
                   13765: easy manner, and to retrieve it again on another call. It is expected
                   13766: that a handler would use this once at the beginning to retrieve data,
                   13767: and then again once at the end to send only the new data back.
                   13768: 
                   13769: The data is stored in the user's data directory on the user's
                   13770: homeserver under the ID of the course.
                   13771: 
                   13772: The hash that is returned by restore will have all of the previous
                   13773: value for all of the elements of the hash.
                   13774: 
                   13775: Example:
                   13776: 
                   13777:  #creating a hash
                   13778:  my %hash;
                   13779:  $hash{'foo'}='bar';
                   13780: 
                   13781:  #storing it
                   13782:  &Apache::lonnet::cstore(\%hash);
                   13783: 
                   13784:  #changing a value
                   13785:  $hash{'foo'}='notbar';
                   13786: 
                   13787:  #adding a new value
                   13788:  $hash{'bar'}='foo';
                   13789:  &Apache::lonnet::cstore(\%hash);
                   13790: 
                   13791:  #retrieving the hash
                   13792:  my %history=&Apache::lonnet::restore();
                   13793: 
                   13794:  #print the hash
                   13795:  foreach my $key (sort(keys(%history))) {
                   13796:    print("\%history{$key} = $history{$key}");
                   13797:  }
                   13798: 
                   13799: Will print out:
1.191     harris41 13800: 
1.394     bowersj2 13801:  %history{1:foo} = bar
                   13802:  %history{1:keys} = foo:timestamp
                   13803:  %history{1:timestamp} = 990455579
                   13804:  %history{2:bar} = foo
                   13805:  %history{2:foo} = notbar
                   13806:  %history{2:keys} = foo:bar:timestamp
                   13807:  %history{2:timestamp} = 990455580
                   13808:  %history{bar} = foo
                   13809:  %history{foo} = notbar
                   13810:  %history{timestamp} = 990455580
                   13811:  %history{version} = 2
                   13812: 
                   13813: Note that the special hash entries C<keys>, C<version> and
                   13814: C<timestamp> were added to the hash. C<version> will be equal to the
                   13815: total number of versions of the data that have been stored. The
                   13816: C<timestamp> attribute will be the UNIX time the hash was
                   13817: stored. C<keys> is available in every historical section to list which
                   13818: keys were added or changed at a specific historical revision of a
                   13819: hash.
                   13820: 
                   13821: B<Warning>: do not store the hash that restore returns directly. This
                   13822: will cause a mess since it will restore the historical keys as if the
                   13823: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 13824: 
1.394     bowersj2 13825: Calling convention:
1.191     harris41 13826: 
1.1225    raeburn  13827:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  13828:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 13829: 
1.394     bowersj2 13830: For more detailed information, see lonnet specific documentation.
1.191     harris41 13831: 
1.394     bowersj2 13832: =head1 RETURN MESSAGES
1.191     harris41 13833: 
1.394     bowersj2 13834: =over 4
1.191     harris41 13835: 
1.394     bowersj2 13836: =item * B<con_lost>: unable to contact remote host
1.191     harris41 13837: 
1.394     bowersj2 13838: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   13839: when the connection is brought back up
1.191     harris41 13840: 
1.394     bowersj2 13841: =item * B<con_failed>: unable to contact remote host and unable to save message
                   13842: for later delivery
1.191     harris41 13843: 
1.967     bisitz   13844: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 13845: 
1.394     bowersj2 13846: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 13847: that was requested
1.191     harris41 13848: 
1.243     albertel 13849: =back
1.191     harris41 13850: 
1.243     albertel 13851: =head1 PUBLIC SUBROUTINES
1.191     harris41 13852: 
1.243     albertel 13853: =head2 Session Environment Functions
1.191     harris41 13854: 
1.243     albertel 13855: =over 4
1.191     harris41 13856: 
1.394     bowersj2 13857: =item * 
                   13858: X<appenv()>
1.949     raeburn  13859: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 13860: the user envirnoment file, and will be restored for each access this
1.620     albertel 13861: user makes during this session, also modifies the %env for the current
1.949     raeburn  13862: process. Optional rolesarrayref - if defined contains a reference to an array
                   13863: of roles which are exempt from the restriction on modifying user.role entries 
                   13864: in the user's environment.db and in %env.    
1.191     harris41 13865: 
                   13866: =item *
1.394     bowersj2 13867: X<delenv()>
1.987     raeburn  13868: B<delenv($delthis,$regexp)>: removes all items from the session
                   13869: environment file that begin with $delthis. If the 
                   13870: optional second arg - $regexp - is true, $delthis is treated as a 
                   13871: regular expression, otherwise \Q$delthis\E is used. 
                   13872: The values are also deleted from the current processes %env.
1.191     harris41 13873: 
1.795     albertel 13874: =item * get_env_multiple($name) 
                   13875: 
                   13876: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   13877: values may be defined and end up as an array ref.
                   13878: 
                   13879: returns an array of values
                   13880: 
1.243     albertel 13881: =back
                   13882: 
                   13883: =head2 User Information
1.191     harris41 13884: 
1.243     albertel 13885: =over 4
1.191     harris41 13886: 
                   13887: =item *
1.394     bowersj2 13888: X<queryauthenticate()>
                   13889: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 13890: authentication scheme
                   13891: 
                   13892: =item *
1.394     bowersj2 13893: X<authenticate()>
1.1073    raeburn  13894: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 13895: authenticate user from domain's lib servers (first use the current
                   13896: one). C<$upass> should be the users password.
1.1073    raeburn  13897: $checkdefauth is optional (value is 1 if a check should be made to
                   13898:    authenticate user using default authentication method, and allow
                   13899:    account creation if username does not have account in the domain).
                   13900: $clientcancheckhost is optional (value is 1 if checking whether the
                   13901:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 13902: 
                   13903: =item *
1.394     bowersj2 13904: X<homeserver()>
                   13905: B<homeserver($uname,$udom)>: find the server which has
                   13906: the user's directory and files (there must be only one), this caches
                   13907: the answer, and also caches if there is a borken connection.
1.191     harris41 13908: 
                   13909: =item *
1.394     bowersj2 13910: X<idget()>
1.1300    raeburn  13911: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   13912: a list of student/employee IDs or clicker IDs
                   13913: (student/employee IDs are a unique resource in a domain, there must be 
                   13914: only 1 ID per username, and only 1 username per ID in a specific domain).
                   13915: clickerIDs are not necessarily unique, as students might share clickers.
                   13916: (returns hash: id=>name,id=>name)
1.191     harris41 13917: 
                   13918: =item *
1.394     bowersj2 13919: X<idrget()>
                   13920: B<idrget($udom,@unames)>: find the IDs behind a list of
                   13921: usernames (returns hash: name=>id,name=>id)
1.191     harris41 13922: 
                   13923: =item *
1.394     bowersj2 13924: X<idput()>
1.1300    raeburn  13925: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   13926: names and associated student/employee IDs or clicker IDs.
                   13927: 
                   13928: =item *
                   13929: X<iddel()>
                   13930: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   13931: student/employee ID or clicker ID username look-ups from domain.
                   13932: The homeserver ($uhome) and namespace ($namespace) are optional.
                   13933: If no $uhome is provided, it will be determined usig &homeserver()
                   13934: for each user.  If no $namespace is provided, the default is ids.
                   13935: 
                   13936: =item *
                   13937: X<updateclickers()>
                   13938: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   13939: clicker ID-to-username look-ups in clickers.db on library server.
                   13940: Permitted actions are add or del (i.e., add or delete). The 
                   13941: clickers.db contains clickerID as keys (escaped), and each corresponding
                   13942: value is an escaped comma-separated list of usernames (for whom the
                   13943: library server is the homeserver), who registered that particular ID.
                   13944: If $critical is true, the update will be sent via &critical, otherwise
                   13945: &reply() will be used.
1.191     harris41 13946: 
                   13947: =item *
1.394     bowersj2 13948: X<rolesinit()>
1.1169    droeschl 13949: B<rolesinit($udom,$username)>: get user privileges.
                   13950: returns user role, first access and timer interval hashes
1.243     albertel 13951: 
                   13952: =item *
1.1171    droeschl 13953: X<privileged()>
                   13954: B<privileged($username,$domain)>: returns a true if user has a
                   13955: privileged and active role (i.e. su or dc), false otherwise.
                   13956: 
                   13957: =item *
1.551     albertel 13958: X<getsection()>
                   13959: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 13960: course $cname, return section name/number or '' for "not in course"
                   13961: and '-1' for "no section"
                   13962: 
                   13963: =item *
1.394     bowersj2 13964: X<userenvironment()>
                   13965: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 13966: passed in @what from the requested user's environment, returns a hash
                   13967: 
1.858     raeburn  13968: =item * 
                   13969: X<userlog_query()>
1.859     albertel 13970: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   13971: activity.log file. %filters defines filters applied when parsing the
                   13972: log file. These can be start or end timestamps, or the type of action
                   13973: - log to look for Login or Logout events, check for Checkin or
                   13974: Checkout, role for role selection. The response is in the form
                   13975: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   13976: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  13977: 
1.243     albertel 13978: =back
                   13979: 
                   13980: =head2 User Roles
                   13981: 
                   13982: =over 4
                   13983: 
                   13984: =item *
                   13985: 
1.1284    raeburn  13986: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   13987: returns codes for allowed actions.
                   13988: 
                   13989: The first argument is required, all others are optional.
                   13990: 
                   13991: $priv is the privilege being checked.
                   13992: $uri contains additional information about what is being checked for access (e.g.,
                   13993: URL, course ID etc.). 
                   13994: $symb is the unique resource instance identifier in a course; if needed,
                   13995: but not provided, it will be retrieved via a call to &symbread(). 
                   13996: $role is the role for which a priv is being checked (only used if priv is evb). 
                   13997: $clientip is the user's IP address (only used when checking for access to portfolio 
                   13998: files).
                   13999: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   14000: prevents recursive calls to &allowed.
                   14001: 
1.243     albertel 14002:  F: full access
                   14003:  U,I,K: authentication modes (cxx only)
                   14004:  '': forbidden
                   14005:  1: user needs to choose course
                   14006:  2: browse allowed
1.766     albertel 14007:  A: passphrase authentication needed
1.1284    raeburn  14008:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14009: 
                   14010: =item *
                   14011: 
1.1192    raeburn  14012: constructaccess($url,$setpriv) : check for access to construction space URL
                   14013: 
                   14014: See if the owner domain and name in the URL match those in the
                   14015: expected environment.  If so, return three element list
                   14016: ($ownername,$ownerdomain,$ownerhome).
                   14017: 
                   14018: Otherwise return the null string.
                   14019: 
                   14020: If second argument 'setpriv' is true, it assigns the privileges,
                   14021: and returns the same three element list, unless the owner has
                   14022: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14023: in which case the null string is returned.
                   14024: 
                   14025: =item *
                   14026: 
1.1326    raeburn  14027: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14028: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14029: for system, domain, and course level. $uname and $udom are optional (current
                   14030: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14031: 
                   14032: =item *
                   14033: 
1.988     raeburn  14034: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14035: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14036: $type is Course (default) or Community.
1.988     raeburn  14037: If $forcedefault evaluates to true, text returned will be default 
                   14038: text for $type. Otherwise, if this is a course, the text returned 
                   14039: will be a custom name for the role (if defined in the course's 
                   14040: environment).  If no custom name is defined the default is returned.
                   14041:    
1.832     raeburn  14042: =item *
                   14043: 
1.1219    raeburn  14044: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14045: All arguments are optional. Returns a hash of a roles, either for
                   14046: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14047: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14048: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14049: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14050: For each key, value is set to colon-separated start and end times for
                   14051: the role.  If no username and domain are specified, will default to
1.934     raeburn  14052: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14053: of role statuses (active, future or previous), roles 
                   14054: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14055: to restrict the list of roles reported. If no array ref is 
                   14056: provided for types, will default to return only active roles.
1.834     albertel 14057: 
1.1195    raeburn  14058: =item *
                   14059: 
                   14060: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  14061: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   14062: 
                   14063: Additional optional arguments are: $type (if role checking is to be restricted 
                   14064: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  14065: available roles) or future (roles available in the future), and
                   14066: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  14067: have active Domain Coordinator role in course's domain or in additional
                   14068: domains (specified in 'Domains to check for privileged users' in course
                   14069: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14070: 
                   14071: =item *
                   14072: 
                   14073: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14074: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14075: $possdomains and $possroles are optional array refs -- to domains to check and
                   14076: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14077: users' roles.db to check for a dc or su role in any domain. This can be
                   14078: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14079: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14080: this then allows &privileged_by_domain() to be used, which caches the identity
                   14081: of privileged users, eliminating the need for repeated calls to &dump().
                   14082: 
                   14083: =item *
                   14084: 
                   14085: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14086: where the outer hash keys are domains specified in the $possdomains array ref,
                   14087: next inner hash keys are privileged roles specified in the $roles array ref,
                   14088: and the innermost hash contains key = value pairs for username:domain = end:start
                   14089: for active or future "privileged" users with that role in that domain. To avoid
                   14090: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14091: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  14092: 
1.243     albertel 14093: =back
                   14094: 
                   14095: =head2 User Modification
                   14096: 
                   14097: =over 4
                   14098: 
                   14099: =item *
                   14100: 
1.957     raeburn  14101: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14102: user for the level given by URL.  Optional start and end dates (leave empty
                   14103: string or zero for "no date")
1.191     harris41 14104: 
                   14105: =item *
                   14106: 
1.243     albertel 14107: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14108: change a users, password, possible return values are: ok,
                   14109: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14110: refused
1.191     harris41 14111: 
                   14112: =item *
                   14113: 
1.243     albertel 14114: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14115: 
                   14116: =item *
                   14117: 
1.1058    raeburn  14118: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14119:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14120: 
                   14121: will update user information (firstname,middlename,lastname,generation,
                   14122: permanentemail), and if forceid is true, student/employee ID also.
                   14123: A user's institutional affiliation(s) can also be updated.
                   14124: User information fields will not be overwritten with empty entries 
                   14125: unless the field is included in the $candelete array reference.
                   14126: This array is included when a single user is modified via "Manage Users",
                   14127: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14128: 
                   14129: =item *
                   14130: 
1.286     matthew  14131: modifystudent
                   14132: 
1.957     raeburn  14133: modify a student's enrollment and identification information.
1.1235    raeburn  14134: The course id is resolved based on the current user's environment.  
                   14135: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14136: associated with a course.
                   14137: 
1.297     matthew  14138: This call is essentially a wrapper for lonnet::modifyuser and
                   14139: lonnet::modify_student_enrollment
1.286     matthew  14140: 
                   14141: Inputs: 
                   14142: 
                   14143: =over 4
                   14144: 
1.957     raeburn  14145: =item B<$udom> Student's loncapa domain
1.286     matthew  14146: 
1.957     raeburn  14147: =item B<$uname> Student's loncapa login name
1.286     matthew  14148: 
1.964     bisitz   14149: =item B<$uid> Student/Employee ID
1.286     matthew  14150: 
1.957     raeburn  14151: =item B<$umode> Student's authentication mode
1.286     matthew  14152: 
1.957     raeburn  14153: =item B<$upass> Student's password
1.286     matthew  14154: 
1.957     raeburn  14155: =item B<$first> Student's first name
1.286     matthew  14156: 
1.957     raeburn  14157: =item B<$middle> Student's middle name
1.286     matthew  14158: 
1.957     raeburn  14159: =item B<$last> Student's last name
1.286     matthew  14160: 
1.957     raeburn  14161: =item B<$gene> Student's generation
1.286     matthew  14162: 
1.957     raeburn  14163: =item B<$usec> Student's section in course
1.286     matthew  14164: 
                   14165: =item B<$end> Unix time of the roles expiration
                   14166: 
                   14167: =item B<$start> Unix time of the roles start date
                   14168: 
                   14169: =item B<$forceid> If defined, allow $uid to be changed
                   14170: 
                   14171: =item B<$desiredhome> server to use as home server for student
                   14172: 
1.957     raeburn  14173: =item B<$email> Student's permanent e-mail address
                   14174: 
                   14175: =item B<$type> Type of enrollment (auto or manual)
                   14176: 
1.963     raeburn  14177: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14178: 
                   14179: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14180: 
1.963     raeburn  14181: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14182: 
1.963     raeburn  14183: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14184: 
1.1216    raeburn  14185: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14186: 
                   14187: =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  14188: 
1.286     matthew  14189: =back
1.297     matthew  14190: 
                   14191: =item *
                   14192: 
                   14193: modify_student_enrollment
                   14194: 
1.1235    raeburn  14195: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14196: 'role.request.course' must be defined for this function to proceed.
                   14197: 
                   14198: Inputs:
                   14199: 
                   14200: =over 4
                   14201: 
1.1235    raeburn  14202: =item $udom, student's domain
1.297     matthew  14203: 
1.1235    raeburn  14204: =item $uname, student's name
1.297     matthew  14205: 
1.1235    raeburn  14206: =item $uid, student's user id
1.297     matthew  14207: 
1.1235    raeburn  14208: =item $first, student's first name
1.297     matthew  14209: 
                   14210: =item $middle
                   14211: 
                   14212: =item $last
                   14213: 
                   14214: =item $gene
                   14215: 
                   14216: =item $usec
                   14217: 
                   14218: =item $end
                   14219: 
                   14220: =item $start
                   14221: 
1.957     raeburn  14222: =item $type
                   14223: 
                   14224: =item $locktype
                   14225: 
                   14226: =item $cid
                   14227: 
                   14228: =item $selfenroll
                   14229: 
                   14230: =item $context
                   14231: 
1.1216    raeburn  14232: =item $credits, number of credits student will earn from this class
                   14233: 
1.1314    raeburn  14234: =item $instsec, institutional course section code for student
                   14235: 
1.297     matthew  14236: =back
                   14237: 
1.191     harris41 14238: 
                   14239: =item *
                   14240: 
1.243     albertel 14241: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14242: custom role; give a custom role to a user for the level given by URL.  Specify
                   14243: name and domain of role author, and role name
1.191     harris41 14244: 
                   14245: =item *
                   14246: 
1.243     albertel 14247: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14248: 
                   14249: =item *
                   14250: 
1.243     albertel 14251: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14252: 
                   14253: =back
                   14254: 
                   14255: =head2 Course Infomation
                   14256: 
                   14257: =over 4
1.191     harris41 14258: 
                   14259: =item *
                   14260: 
1.1118    foxr     14261: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14262: specified course id, including all environment settings for the
                   14263: course, the description of the course will be in the hash under the
                   14264: key 'description'
1.191     harris41 14265: 
1.1118    foxr     14266: $options is an optional parameter that if supplied is a hash reference that controls
                   14267: what how this function works.  It has the following key/values:
                   14268: 
                   14269: =over 4
                   14270: 
                   14271: =item freshen_cache
                   14272: 
                   14273: If defined, and the environment cache for the course is valid, it is 
                   14274: returned in the returned hash.
                   14275: 
                   14276: =item one_time
                   14277: 
                   14278: If defined, the last cache time is set to _now_
                   14279: 
                   14280: =item user
                   14281: 
                   14282: If defined, the supplied username is used instead of the current user.
                   14283: 
                   14284: 
                   14285: =back
                   14286: 
1.191     harris41 14287: =item *
                   14288: 
1.624     albertel 14289: resdata($name,$domain,$type,@which) : request for current parameter
                   14290: setting for a specific $type, where $type is either 'course' or 'user',
                   14291: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  14292: answers for 10 minutes.
1.243     albertel 14293: 
1.877     foxr     14294: =item *
                   14295: 
                   14296: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14297: data base, returning a hash that is keyed by the resource name and has
                   14298: values that are the resource value.  I believe that the timestamps and
                   14299: versions are also returned.
                   14300: 
1.1236    raeburn  14301: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14302: supplemental content area. This routine caches the number of files for 
                   14303: 10 minutes.
                   14304: 
1.243     albertel 14305: =back
                   14306: 
                   14307: =head2 Course Modification
                   14308: 
                   14309: =over 4
1.191     harris41 14310: 
                   14311: =item *
                   14312: 
1.243     albertel 14313: writecoursepref($courseid,%prefs) : write preferences (environment
                   14314: database) for a course
1.191     harris41 14315: 
                   14316: =item *
                   14317: 
1.1011    raeburn  14318: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14319: 
                   14320: =item *
                   14321: 
1.1038    raeburn  14322: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14323: 
1.1167    droeschl 14324: =item *
                   14325: 
                   14326: is_course($courseid), is_course($cdom, $cnum)
                   14327: 
                   14328: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14329: two component version $cdom, $cnum. It checks if the specified course exists.
                   14330: 
                   14331: Returns:
                   14332:     undef if the course doesn't exist, otherwise
                   14333:     in scalar context the combined courseid.
                   14334:     in list context the two components of the course identifier, domain and 
                   14335:     courseid.    
                   14336: 
1.243     albertel 14337: =back
                   14338: 
                   14339: =head2 Resource Subroutines
                   14340: 
                   14341: =over 4
1.191     harris41 14342: 
                   14343: =item *
                   14344: 
1.243     albertel 14345: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 14346: 
                   14347: =item *
                   14348: 
1.243     albertel 14349: repcopy($filename) : subscribes to the requested file, and attempts to
                   14350: replicate from the owning library server, Might return
1.607     raeburn  14351: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   14352: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 14353: resource. Expects the local filesystem pathname
                   14354: (/home/httpd/html/res/....)
                   14355: 
                   14356: =back
                   14357: 
                   14358: =head2 Resource Information
                   14359: 
                   14360: =over 4
1.191     harris41 14361: 
                   14362: =item *
                   14363: 
1.1228    raeburn  14364: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   14365: and returns the value of a variety of different possible values,
                   14366: $varname should be a request string, and the other parameters can be
                   14367: used to specify who and what one is asking about. Ordinarily, $cid 
                   14368: does not need to be specified, as it is retrived from 
                   14369: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14370: within lonuserstate::loadmap() when initializing a course, before
                   14371: $env{'request.course.id'} has been set, so it needs to be provided
                   14372: in that one case.
1.243     albertel 14373: 
                   14374: Possible values for $varname are environment.lastname (or other item
                   14375: from the envirnment hash), user.name (or someother aspect about the
                   14376: user), resource.0.maxtries (or some other part and parameter of a
                   14377: resource)
1.204     albertel 14378: 
                   14379: =item *
                   14380: 
1.243     albertel 14381: directcondval($number) : get current value of a condition; reads from a state
                   14382: string
1.204     albertel 14383: 
                   14384: =item *
                   14385: 
1.243     albertel 14386: condval($condidx) : value of condition index based on state
1.204     albertel 14387: 
                   14388: =item *
                   14389: 
1.243     albertel 14390: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   14391: resource's metadata, $what should be either a specific key, or either
                   14392: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   14393: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   14394: 
                   14395: this function automatically caches all requests
1.191     harris41 14396: 
                   14397: =item *
                   14398: 
1.243     albertel 14399: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   14400: network of library servers; returns file handle of where SQL and regex results
                   14401: will be stored for query
1.191     harris41 14402: 
                   14403: =item *
                   14404: 
1.1282    raeburn  14405: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   14406: return symbolic list entry (all arguments optional). 
                   14407: 
                   14408: Args: filename is the filename (including path) for the file for which a symb 
                   14409: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   14410: to check access status if more than one resource was found in the bighash 
                   14411: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   14412: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   14413: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   14414: cause possible symbs to be checked to determine if they are subject to content
                   14415: blocking, if so they will not be included as possible symbs; possibles is a
                   14416: ref to a hash, which, as a side effect, will be populated with all possible 
                   14417: symbs (content blocking not tested).
                   14418:  
1.243     albertel 14419: returns the data handle
1.191     harris41 14420: 
                   14421: =item *
                   14422: 
1.1190    raeburn  14423: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   14424: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 14425: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  14426: on failure, user must be in a course, as it assumes the existence of
                   14427: the course initial hash, and uses $env('request.course.id'}.  The third
                   14428: arg is an optional reference to a scalar.  If this arg is passed in the 
                   14429: call to symbverify, it will be set to 1 if the symb has been set to be 
                   14430: encrypted; otherwise it will be null.  
1.191     harris41 14431: 
                   14432: =item *
                   14433: 
1.243     albertel 14434: symbclean($symb) : removes versions numbers from a symb, returns the
                   14435: cleaned symb
1.191     harris41 14436: 
                   14437: =item *
                   14438: 
1.243     albertel 14439: is_on_map($uri) : checks if the $uri is somewhere on the current
                   14440: course map, user must be in a course for it to work.
1.191     harris41 14441: 
                   14442: =item *
                   14443: 
1.243     albertel 14444: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 14445: 
                   14446: =item *
                   14447: 
1.243     albertel 14448: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   14449: a random seed, all arguments are optional, if they aren't sent it uses the
                   14450: environment to derive them. Note: if symb isn't sent and it can't get one
                   14451: from &symbread it will use the current time as its return value
1.191     harris41 14452: 
                   14453: =item *
                   14454: 
1.243     albertel 14455: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   14456: unfakeable, receipt
1.191     harris41 14457: 
                   14458: =item *
                   14459: 
1.620     albertel 14460: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 14461: 
                   14462: =item *
                   14463: 
1.243     albertel 14464: countacc($url) : count the number of accesses to a given URL
1.191     harris41 14465: 
                   14466: =item *
                   14467: 
1.243     albertel 14468: 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 14469: 
                   14470: =item *
                   14471: 
1.243     albertel 14472: 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 14473: 
                   14474: =item *
                   14475: 
1.243     albertel 14476: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 14477: 
                   14478: =item *
                   14479: 
1.243     albertel 14480: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   14481: forcing spreadsheet to reevaluate the resource scores next time.
                   14482: 
1.1195    raeburn  14483: =item * 
                   14484: 
1.1196    raeburn  14485: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   14486: when viewing in course context.
1.1195    raeburn  14487: 
1.1196    raeburn  14488:  input: six args -- filename (decluttered), course number, course domain,
                   14489:                     url, symb (if registered) and group (if this is a 
                   14490:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  14491: 
1.1196    raeburn  14492:  output: array of five scalars --
1.1195    raeburn  14493:          $cfile -- url for file editing if editable on current server
                   14494:          $home -- homeserver of resource (i.e., for author if published,
                   14495:                                           or course if uploaded.).
                   14496:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  14497:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   14498:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  14499: 
                   14500: =item *
                   14501: 
                   14502: is_course_upload($file,$cnum,$cdom)
                   14503: 
                   14504: Used in course context to determine if current file was uploaded to 
                   14505: the course (i.e., would be found in /userfiles/docs on the course's 
                   14506: homeserver.
                   14507: 
                   14508:   input: 3 args -- filename (decluttered), course number and course domain.
                   14509:   output: boolean -- 1 if file was uploaded.
                   14510: 
1.243     albertel 14511: =back
                   14512: 
                   14513: =head2 Storing/Retreiving Data
                   14514: 
                   14515: =over 4
1.191     harris41 14516: 
                   14517: =item *
                   14518: 
1.1269    raeburn  14519: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   14520: permanently for this url; hashref needs to be given and should be a \%hashname;
                   14521: the remaining args aren't required and if they aren't passed or are '' they will
                   14522: be derived from the env (with the exception of $laststore, which is an 
                   14523: optional arg used when a user's submission is stored in grading).
                   14524: $laststore is $version=$timestamp, where $version is the most recent version
                   14525: number retrieved for the corresponding $symb in the $namespace db file, and
                   14526: $timestamp is the timestamp for that transaction (UNIX time).
                   14527: $laststore is currently only passed when cstore() is called by 
                   14528: structuretags::finalize_storage().
1.191     harris41 14529: 
                   14530: =item *
                   14531: 
1.1269    raeburn  14532: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   14533: but uses critical subroutine
1.191     harris41 14534: 
                   14535: =item *
                   14536: 
1.243     albertel 14537: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   14538: all args are optional
1.191     harris41 14539: 
                   14540: =item *
                   14541: 
1.717     albertel 14542: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   14543: dumps the complete (or key matching regexp) namespace into a hash
                   14544: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   14545: normally &store()ed into
                   14546: 
                   14547: $range should be either an integer '100' (give me the first 100
                   14548:                                            matching records)
                   14549:               or be  two integers sperated by a - with no spaces
                   14550:                  '30-50' (give me the 30th through the 50th matching
                   14551:                           records)
                   14552: 
                   14553: 
                   14554: =item *
                   14555: 
1.1269    raeburn  14556: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 14557: replaces a &store() version of data with a replacement set of data
                   14558: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  14559: reference. If $tolog is true, the transaction is logged in the courselog
                   14560: with an action=PUTSTORE.
1.717     albertel 14561: 
                   14562: =item *
                   14563: 
1.243     albertel 14564: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   14565: works very similar to store/cstore, but all data is stored in a
                   14566: temporary location and can be reset using tmpreset, $storehash should
                   14567: be a hash reference, returns nothing on success
1.191     harris41 14568: 
                   14569: =item *
                   14570: 
1.243     albertel 14571: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   14572: similar to restore, but all data is stored in a temporary location and
                   14573: can be reset using tmpreset. Returns a hash of values on success,
                   14574: error string otherwise.
1.191     harris41 14575: 
                   14576: =item *
                   14577: 
1.243     albertel 14578: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   14579: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 14580: 
                   14581: =item *
                   14582: 
1.243     albertel 14583: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14584: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 14585: 
                   14586: =item *
                   14587: 
1.243     albertel 14588: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   14589: namesp ($udom and $uname are optional)
1.191     harris41 14590: 
                   14591: =item *
                   14592: 
1.702     albertel 14593: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 14594: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 14595: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  14596: 
1.702     albertel 14597: $range should be either an integer '100' (give me the first 100
                   14598:                                            matching records)
                   14599:               or be  two integers sperated by a - with no spaces
                   14600:                  '30-50' (give me the 30th through the 50th matching
                   14601:                           records)
1.449     matthew  14602: =item *
                   14603: 
                   14604: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   14605: $store can be a scalar, an array reference, or if the amount to be 
                   14606: incremented is > 1, a hash reference.
                   14607: 
                   14608: ($udom and $uname are optional)
1.191     harris41 14609: 
                   14610: =item *
                   14611: 
1.243     albertel 14612: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   14613: ($udom and $uname are optional)
1.191     harris41 14614: 
                   14615: =item *
                   14616: 
1.243     albertel 14617: cput($namespace,$storehash,$udom,$uname) : critical put
                   14618: ($udom and $uname are optional)
1.191     harris41 14619: 
                   14620: =item *
                   14621: 
1.748     albertel 14622: newput($namespace,$storehash,$udom,$uname) :
                   14623: 
                   14624: Attempts to store the items in the $storehash, but only if they don't
                   14625: currently exist, if this succeeds you can be certain that you have 
                   14626: successfully created a new key value pair in the $namespace db.
                   14627: 
                   14628: 
                   14629: Args:
                   14630:  $namespace: name of database to store values to
                   14631:  $storehash: hashref to store to the db
                   14632:  $udom: (optional) domain of user containing the db
                   14633:  $uname: (optional) name of user caontaining the db
                   14634: 
                   14635: Returns:
                   14636:  'ok' -> succeeded in storing all keys of $storehash
                   14637:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   14638:                         least <key> already existed in the db (other
                   14639:                         requested keys may also already exist)
1.967     bisitz   14640:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 14641:  'con_lost' -> unable to contact request server
                   14642:  'refused' -> action was not allowed by remote machine
                   14643: 
                   14644: 
                   14645: =item *
                   14646: 
1.243     albertel 14647: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14648: reference filled in from namesp (encrypts the return communication)
                   14649: ($udom and $uname are optional)
1.191     harris41 14650: 
                   14651: =item *
                   14652: 
1.243     albertel 14653: log($udom,$name,$home,$message) : write to permanent log for user; use
                   14654: critical subroutine
                   14655: 
1.806     raeburn  14656: =item *
                   14657: 
1.860     raeburn  14658: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   14659: array reference filled in from namespace found in domain level on either
                   14660: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  14661: 
                   14662: =item *
                   14663: 
1.860     raeburn  14664: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   14665: domain level either on specified domain server ($uhome) or primary domain 
                   14666: server ($udom and $uhome are optional)
1.806     raeburn  14667: 
1.943     raeburn  14668: =item * 
                   14669: 
1.1240    raeburn  14670: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   14671: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   14672: the target domain.
                   14673: 
                   14674: May also include additional key => value pairs for the following groups:
                   14675: 
                   14676: =over
                   14677: 
                   14678: =item
                   14679: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   14680: 
                   14681: =over
                   14682: 
                   14683: =item defaultquota, authorquota
                   14684: 
                   14685: =back
                   14686: 
                   14687: =item
                   14688: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   14689: portfolio for users).
                   14690: 
                   14691: =over
                   14692: 
                   14693: =item
                   14694: aboutme, blog, webdav, portfolio
                   14695: 
                   14696: =back
                   14697: 
                   14698: =item
                   14699: requestcourses: ability to request courses, and how requests are processed.
                   14700: 
                   14701: =over
                   14702: 
                   14703: =item
1.1305    raeburn  14704: official, unofficial, community, textbook, placement
1.1240    raeburn  14705: 
                   14706: =back
                   14707: 
                   14708: =item
                   14709: inststatus: types of institutional affiliation, and order in which they are displayed.
                   14710: 
                   14711: =over
                   14712: 
                   14713: =item
1.1256    raeburn  14714: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  14715: 
                   14716: =back
                   14717: 
                   14718: =item
                   14719: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   14720: for course's uploaded content.
                   14721: 
                   14722: =over
                   14723: 
                   14724: =item
1.1246    raeburn  14725: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  14726: communityquota, textbookquota, placementquota
1.1240    raeburn  14727: 
                   14728: =back
                   14729: 
                   14730: =item
                   14731: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   14732: on your servers.
                   14733: 
                   14734: =over
                   14735: 
                   14736: =item 
                   14737: remotesessions, hostedsessions
                   14738: 
                   14739: =back
                   14740: 
                   14741: =back
                   14742: 
                   14743: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   14744: utility to create a configuration.db file on a domain's primary library server 
                   14745: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   14746: -- corresponding values are authentication type (internal, krb4, krb5,
                   14747: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   14748: will be available. Values are retrieved from cache (if current), unless the
                   14749: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   14750: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   14751: 
                   14752: Typical usage:
1.943     raeburn  14753: 
1.1240    raeburn  14754: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  14755: 
1.243     albertel 14756: =back
                   14757: 
                   14758: =head2 Network Status Functions
                   14759: 
                   14760: =over 4
1.191     harris41 14761: 
                   14762: =item *
                   14763: 
1.1137    raeburn  14764: dirlist() : return directory list based on URI (first arg).
                   14765: 
                   14766: Inputs: 1 required, 5 optional.
                   14767: 
                   14768: =over
                   14769: 
                   14770: =item 
                   14771: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   14772: 
                   14773: =item
                   14774: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   14775: 
                   14776: =item
                   14777: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   14778: 
                   14779: =item
                   14780: $getpropath - boolean: 1 if prepend path using &propath(). 
                   14781: 
                   14782: =item
                   14783: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   14784: 
                   14785: =item 
                   14786: $alternateRoot - path to prepend in place of path from $uri.
                   14787: 
                   14788: =back
                   14789: 
                   14790: Returns: Array of up to two items.
                   14791: 
                   14792: =over
                   14793: 
                   14794: a reference to an array of files/subdirectories
                   14795: 
                   14796: =over
                   14797: 
                   14798: Each element in the array of files/subdirectories is a & separated list of
                   14799: item name and the result of running stat on the item.  If dirlist was requested
                   14800: for a file instead of a directory, the item name will be ''. For a directory 
                   14801: listing, if the item is a metadata file, the element will end &N&M 
                   14802: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   14803: default copyright set (1).  
                   14804: 
                   14805: =back
                   14806: 
                   14807: a scalar containing error condition (if encountered).
                   14808: 
                   14809: =over
                   14810: 
                   14811: =item 
                   14812: no_host (no homeserver identified for $username:$domain).
                   14813: 
                   14814: =item 
                   14815: no_such_host (server contacted for listing not identified as valid host).
                   14816: 
                   14817: =item 
                   14818: con_lost (connection to remote server failed).
                   14819: 
                   14820: =item 
                   14821: refused (invalid $username:$domain received on lond side).
                   14822: 
                   14823: =item 
                   14824: no_such_dir (directory at specified path on lond side does not exist). 
                   14825: 
                   14826: =item 
                   14827: empty (directory at specified path on lond side is empty).
                   14828: 
                   14829: =over
                   14830: 
                   14831: This is currently not encountered because the &ls3, &ls2, 
                   14832: &ls (_handler) routines on the lond side do not filter out
                   14833: . and .. from a directory listing. 
                   14834: 
                   14835: =back
                   14836: 
                   14837: =back
                   14838: 
                   14839: =back
1.191     harris41 14840: 
                   14841: =item *
                   14842: 
1.243     albertel 14843: spareserver() : find server with least workload from spare.tab
                   14844: 
1.986     foxr     14845: 
                   14846: =item *
                   14847: 
                   14848: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   14849: if there is no corresponding loncapa host.
                   14850: 
1.243     albertel 14851: =back
                   14852: 
1.986     foxr     14853: 
1.243     albertel 14854: =head2 Apache Request
                   14855: 
                   14856: =over 4
1.191     harris41 14857: 
                   14858: =item *
                   14859: 
1.243     albertel 14860: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   14861: localhost, posts hash
                   14862: 
                   14863: =back
                   14864: 
                   14865: =head2 Data to String to Data
                   14866: 
                   14867: =over 4
1.191     harris41 14868: 
                   14869: =item *
                   14870: 
1.243     albertel 14871: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   14872: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 14873: 
                   14874: =item *
                   14875: 
1.243     albertel 14876: hashref2str($hashref) : convert a hashref into a string complete with
                   14877: escaping and '=' and '&' separators, supports elements that are
                   14878: arrayrefs and hashrefs
1.191     harris41 14879: 
                   14880: =item *
                   14881: 
1.243     albertel 14882: arrayref2str($arrayref) : convert an arrayref into a string complete
                   14883: with escaping and '&' separators, supports elements that are arrayrefs
                   14884: and hashrefs
1.191     harris41 14885: 
                   14886: =item *
                   14887: 
1.243     albertel 14888: str2hash($string) : convert string to hash using unescaping and
                   14889: splitting on '=' and '&', supports elements that are arrayrefs and
                   14890: hashrefs
1.191     harris41 14891: 
                   14892: =item *
                   14893: 
1.243     albertel 14894: str2array($string) : convert string to hash using unescaping and
                   14895: splitting on '&', supports elements that are arrayrefs and hashrefs
                   14896: 
                   14897: =back
                   14898: 
                   14899: =head2 Logging Routines
                   14900: 
                   14901: 
                   14902: These routines allow one to make log messages in the lonnet.log and
                   14903: lonnet.perm logfiles.
1.191     harris41 14904: 
1.1119    foxr     14905: =over 4
                   14906: 
1.191     harris41 14907: =item *
                   14908: 
1.243     albertel 14909: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 14910: 
                   14911: =item *
                   14912: 
1.243     albertel 14913: logthis() : append message to the normal lonnet.log file, it gets
                   14914: preiodically rolled over and deleted.
1.191     harris41 14915: 
                   14916: =item *
                   14917: 
1.243     albertel 14918: logperm() : append a permanent message to lonnet.perm.log, this log
                   14919: file never gets deleted by any automated portion of the system, only
                   14920: messages of critical importance should go in here.
                   14921: 
1.1119    foxr     14922: 
1.243     albertel 14923: =back
                   14924: 
                   14925: =head2 General File Helper Routines
                   14926: 
                   14927: =over 4
1.191     harris41 14928: 
                   14929: =item *
                   14930: 
1.481     raeburn  14931: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   14932: (a) files in /uploaded
                   14933:   (i) If a local copy of the file exists - 
                   14934:       compares modification date of local copy with last-modified date for 
                   14935:       definitive version stored on home server for course. If local copy is 
                   14936:       stale, requests a new version from the home server and stores it. 
                   14937:       If the original has been removed from the home server, then local copy 
                   14938:       is unlinked.
                   14939:   (ii) If local copy does not exist -
                   14940:       requests the file from the home server and stores it. 
                   14941:   
                   14942:   If $caller is 'uploadrep':  
                   14943:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   14944:     for request for files originally uploaded via DOCS. 
                   14945:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   14946:   
                   14947:   Otherwise:
                   14948:      This indicates a call from the content generation phase of the request.
                   14949:      -  returns the entire contents of the file or -1.
                   14950:      
                   14951: (b) files in /res
                   14952:    - returns the entire contents of a file or -1; 
                   14953:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 14954: 
1.712     albertel 14955: 
                   14956: =item *
                   14957: 
                   14958: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   14959:                   reference
                   14960: 
                   14961: returns either a stat() list of data about the file or an empty list
                   14962: if the file doesn't exist or couldn't find out about it (connection
                   14963: problems or user unknown)
                   14964: 
1.191     harris41 14965: =item *
                   14966: 
1.243     albertel 14967: filelocation($dir,$file) : returns file system location of a file
                   14968: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   14969: directory that relative $file lookups are to looked in ($dir of /a/dir
                   14970: and a file of ../bob will become /a/bob)
1.191     harris41 14971: 
                   14972: =item *
                   14973: 
                   14974: hreflocation($dir,$file) : returns file system location or a URL; same as
                   14975: filelocation except for hrefs
                   14976: 
                   14977: =item *
                   14978: 
1.1261    raeburn  14979: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   14980: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 14981: 
1.243     albertel 14982: =back
                   14983: 
1.608     albertel 14984: =head2 Usererfile file routines (/uploaded*)
                   14985: 
                   14986: =over 4
                   14987: 
                   14988: =item *
                   14989: 
                   14990: userfileupload(): main rotine for putting a file in a user or course's
                   14991:                   filespace, arguments are,
                   14992: 
1.620     albertel 14993:  formname - required - this is the name of the element in $env where the
1.608     albertel 14994:            filename, and the contents of the file to create/modifed exist
1.620     albertel 14995:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   14996:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  14997:  context - if coursedoc, store the file in the course of the active role
                   14998:              of the current user; 
                   14999:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15000:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15001:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15002:          if undefined, it will be placed in "unknown"
                   15003: 
                   15004:  (This routine calls clean_filename() to remove any dangerous
                   15005:  characters from the filename, and then calls finuserfileupload() to
                   15006:  complete the transaction)
                   15007: 
                   15008:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15009:  and /adm/notfound.html if unsuccessful
                   15010: 
                   15011: =item *
                   15012: 
                   15013: clean_filename(): routine for cleaing a filename up for storage in
                   15014:                  userfile space, argument is:
                   15015: 
                   15016:  filename - proposed filename
                   15017: 
                   15018: returns: the new clean filename
                   15019: 
                   15020: =item *
                   15021: 
1.1090    raeburn  15022: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15023: userspace, probably shouldn't be called directly
                   15024: 
                   15025:   docuname: username or courseid of destination for the file
                   15026:   docudom: domain of user/course of destination for the file
                   15027:   formname: same as for userfileupload()
1.1090    raeburn  15028:   fname: filename (including subdirectories) for the file
                   15029:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   15030:   allfiles: reference to hash used to store objects found by parser
                   15031:   codebase: reference to hash used for codebases of java objects found by parser
                   15032:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15033:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15034:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15035:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15036:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15037:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15038:   mimetype: reference to scalar to accommodate mime type determined
                   15039:             from File::MMagic if $parser = parse.
1.608     albertel 15040: 
                   15041:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15042:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15043:  was 'overwrite').
                   15044:  
1.608     albertel 15045: 
                   15046: =item *
                   15047: 
                   15048: renameuserfile(): renames an existing userfile to a new name
                   15049: 
                   15050:   Args:
                   15051:    docuname: username or courseid of destination for the file
                   15052:    docudom: domain of user/course of destination for the file
                   15053:    old: current file name (including any subdirs under userfiles)
                   15054:    new: desired file name (including any subdirs under userfiles)
                   15055: 
                   15056: =item *
                   15057: 
                   15058: mkdiruserfile(): creates a directory is a userfiles dir
                   15059: 
                   15060:   Args:
                   15061:    docuname: username or courseid of destination for the file
                   15062:    docudom: domain of user/course of destination for the file
                   15063:    dir: dir to create (including any subdirs under userfiles)
                   15064: 
                   15065: =item *
                   15066: 
                   15067: removeuserfile(): removes a file that exists in userfiles
                   15068: 
                   15069:   Args:
                   15070:    docuname: username or courseid of destination for the file
                   15071:    docudom: domain of user/course of destination for the file
                   15072:    fname: filname to delete (including any subdirs under userfiles)
                   15073: 
                   15074: =item *
                   15075: 
                   15076: removeuploadedurl(): convience function for removeuserfile()
                   15077: 
                   15078:   Args:
                   15079:    url:  a full /uploaded/... url to delete
                   15080: 
1.747     albertel 15081: =item * 
                   15082: 
                   15083: get_portfile_permissions():
                   15084:   Args:
                   15085:     domain: domain of user or course contain the portfolio files
                   15086:     user: name of user or num of course contain the portfolio files
                   15087:   Returns:
                   15088:     hashref of a dump of the proper file_permissions.db
                   15089:    
                   15090: 
                   15091: =item * 
                   15092: 
                   15093: get_access_controls():
                   15094: 
                   15095: Args:
                   15096:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15097:   group: (optional) the group you want the files associated with
                   15098:   file: (optional) the file you want access info on
                   15099: 
                   15100: Returns:
1.749     raeburn  15101:     a hash (keys are file names) of hashes containing
                   15102:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15103:         values are XML containing access control settings (see below) 
1.747     albertel 15104: 
                   15105: Internal notes:
                   15106: 
1.749     raeburn  15107:  access controls are stored in file_permissions.db as key=value pairs.
                   15108:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15109:         where scope -> public,guest,course,group,domains or users.
                   15110:               end -> UNIX time for end of access (0 -> no end date)
                   15111:               start -> UNIX time for start of access
                   15112: 
                   15113:     value -> XML description of access control
                   15114:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15115:             <start></start>
                   15116:             <end></end>
                   15117: 
                   15118:             <password></password>  for scope type = guest
                   15119: 
                   15120:             <domain></domain>     for scope type = course or group
                   15121:             <number></number>
                   15122:             <roles id="">
                   15123:              <role></role>
                   15124:              <access></access>
                   15125:              <section></section>
                   15126:              <group></group>
                   15127:             </roles>
                   15128: 
                   15129:             <dom></dom>         for scope type = domains
                   15130: 
                   15131:             <users>             for scope type = users
                   15132:              <user>
                   15133:               <uname></uname>
                   15134:               <udom></udom>
                   15135:              </user>
                   15136:             </users>
                   15137:            </scope> 
                   15138:               
                   15139:  Access data is also aggregated for each file in an additional key=value pair:
                   15140:  key -> path to file/file_name\0accesscontrol 
                   15141:  value -> reference to hash
                   15142:           hash contains key = value pairs
                   15143:           where key = uniqueID:scope_end_start
                   15144:                 value = UNIX time record was last updated
                   15145: 
                   15146:           Used to improve speed of look-ups of access controls for each file.  
                   15147:  
                   15148:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15149: 
1.1198    raeburn  15150: =item *
                   15151: 
1.749     raeburn  15152: modify_access_controls():
                   15153: 
                   15154: Modifies access controls for a portfolio file
                   15155: Args
                   15156: 1. file name
                   15157: 2. reference to hash of required changes,
                   15158: 3. domain
                   15159: 4. username
                   15160:   where domain,username are the domain of the portfolio owner 
                   15161:   (either a user or a course) 
                   15162: 
                   15163: Returns:
                   15164: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15165: 2. result of deletions ('ok' or 'error', with error message).
                   15166: 3. reference to hash of any new or updated access controls.
                   15167: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15168:    key = integer (inbound ID)
1.1198    raeburn  15169:    value = uniqueID
                   15170: 
                   15171: =item *
                   15172: 
                   15173: get_timebased_id():
                   15174: 
                   15175: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   15176: course via the Course Editor (e.g., folders, composite pages, 
                   15177: group bulletin boards).
                   15178: 
                   15179: Args: (first three required; six others optional)
                   15180: 
                   15181: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15182:    docssequence, or name of group
                   15183: 
                   15184: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15185:    e.g., num, boardids
                   15186: 
                   15187: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   15188:    file will be named nohist_namespace.db
                   15189: 
                   15190: 4. cdom: domain of course; default is current course domain from %env
                   15191: 
                   15192: 5. cnum: course number; default is current course number from %env
                   15193: 
                   15194: 6. idtype: set to concat if an additional digit is to be appended to the 
                   15195:    unix timestamp to form the suffix, if the plain timestamp is already
                   15196:    in use.  Default is to not do this, but simply increment the unix 
                   15197:    timestamp by 1 until a unique key is obtained.
                   15198: 
                   15199: 7. who: holder of locking key; defaults to user:domain for user.
                   15200: 
                   15201: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   15202:    retrying); default is 3.
                   15203: 
                   15204: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   15205: 
                   15206: Returns:
                   15207: 
                   15208: 1. suffix obtained (numeric)
                   15209: 
                   15210: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15211: 
                   15212: 3. error: contains (localized) error message if an error occurred.
                   15213: 
1.747     albertel 15214: 
1.608     albertel 15215: =back
                   15216: 
1.243     albertel 15217: =head2 HTTP Helper Routines
                   15218: 
                   15219: =over 4
                   15220: 
1.191     harris41 15221: =item *
                   15222: 
                   15223: escape() : unpack non-word characters into CGI-compatible hex codes
                   15224: 
                   15225: =item *
                   15226: 
                   15227: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15228: 
1.243     albertel 15229: =back
                   15230: 
                   15231: =head1 PRIVATE SUBROUTINES
                   15232: 
                   15233: =head2 Underlying communication routines (Shouldn't call)
                   15234: 
                   15235: =over 4
                   15236: 
                   15237: =item *
                   15238: 
                   15239: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15240: 
                   15241: =item *
                   15242: 
                   15243: reply() : uses subreply to send a message to remote machine, logs all failures
                   15244: 
                   15245: =item *
                   15246: 
                   15247: critical() : passes a critical message to another server; if cannot
                   15248: get through then place message in connection buffer directory and
                   15249: returns con_delayed, if incapable of saving message, returns
                   15250: con_failed
                   15251: 
                   15252: =item *
                   15253: 
                   15254: reconlonc() : tries to reconnect lonc client processes.
                   15255: 
                   15256: =back
                   15257: 
                   15258: =head2 Resource Access Logging
                   15259: 
                   15260: =over 4
                   15261: 
                   15262: =item *
                   15263: 
                   15264: flushcourselogs() : flush (save) buffer logs and access logs
                   15265: 
                   15266: =item *
                   15267: 
                   15268: courselog($what) : save message for course in hash
                   15269: 
                   15270: =item *
                   15271: 
                   15272: courseacclog($what) : save message for course using &courselog().  Perform
                   15273: special processing for specific resource types (problems, exams, quizzes, etc).
                   15274: 
1.191     harris41 15275: =item *
                   15276: 
                   15277: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15278: as a PerlChildExitHandler
1.243     albertel 15279: 
                   15280: =back
                   15281: 
                   15282: =head2 Other
                   15283: 
                   15284: =over 4
                   15285: 
                   15286: =item *
                   15287: 
                   15288: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15289: 
                   15290: =back
                   15291: 
                   15292: =cut
1.877     foxr     15293: 

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