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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1333  ! raeburn     4: # $Id: lonnet.pm,v 1.1332 2017/01/02 19:44:20 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.1327    raeburn  4119: # Reverse lookup of domain roles (dc, ad, li, sc, dh, 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.1327    raeburn  4266:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh)/ ) {
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.1332    raeburn  4550:         if ($env{"user.role.dh./$cdom/"}) {
                   4551:             my $then=$env{'user.login.time'};
                   4552:             my $update=$env{'user.update.time'};
                   4553:             my $liverole = 1;
                   4554:             my ($tstart,$tend)=split(/\./,$env{'user.role.dh./'.$cdom});
                   4555:             my $limit = $update;
                   4556:             if ($env{'request.role'} eq 'dh./'.$cdom.'/') {
                   4557:                 $limit = $then;
                   4558:             }
                   4559:             if ($tstart && $tstart>$limit) { $liverole = 0; }
                   4560:             if ($tend   && $tend  <$limit) { $liverole = 0; }
                   4561:             if ($liverole) {
                   4562:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333  ! raeburn  4563:                     my ($accessref,$accessinfo,%access_in_dom);
        !          4564:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
        !          4565:                     if (ref($roles_by_num) eq 'ARRAY') {
        !          4566:                         if (@{$roles_by_num}) {
1.1332    raeburn  4567:                             my %settings;
                   4568:                             if ($env{'request.course.id'} eq $cid) {
                   4569:                                 foreach my $envkey (keys(%env)) {
                   4570:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   4571:                                         $settings{$1} = $env{$envkey};
                   4572:                                     }
                   4573:                                 }
                   4574:                             } else {
                   4575:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   4576:                             }
                   4577:                             my %setincrs;
                   4578:                             if ($settings{'internal.adhocaccess'}) {
                   4579:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   4580:                             }
                   4581:                             my @statuses;
                   4582:                             if ($env{'environment.inststatus'}) {
                   4583:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   4584:                             }
                   4585:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333  ! raeburn  4586:                             if (ref($accessref) eq 'HASH') {
        !          4587:                                 %access_in_dom = %{$accessref};
        !          4588:                             }
        !          4589:                             foreach my $role (@{$roles_by_num}) {
1.1332    raeburn  4590:                                 my ($curraccess,@okstatus,@personnel);
                   4591:                                 if ($setincrs{$role}) {
                   4592:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   4593:                                     if ($curraccess eq 'status') {
                   4594:                                         @okstatus = split(/\&/,$rest);
                   4595:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4596:                                         @personnel = split(/\&/,$rest);
                   4597:                                     }
                   4598:                                 } else {
                   4599:                                     $curraccess = $access_in_dom{$role};
1.1333  ! raeburn  4600:                                     if (ref($accessinfo) eq 'HASH') {
        !          4601:                                         if ($curraccess eq 'status') {
        !          4602:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
        !          4603:                                                 @okstatus = @{$accessinfo->{$role}};
        !          4604:                                             }
        !          4605:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
        !          4606:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
        !          4607:                                                 @personnel = @{$accessinfo->{$role}};
        !          4608:                                             }
1.1332    raeburn  4609:                                         }
                   4610:                                     }
                   4611:                                 }
                   4612:                                 if ($curraccess eq 'none') {
                   4613:                                     next;
                   4614:                                 } elsif ($curraccess eq 'all') {
                   4615:                                     push(@possroles,$role);
                   4616:                                 } elsif ($curraccess eq 'status') {
                   4617:                                     if (@okstatus) {
                   4618:                                         if (!@statuses) {
                   4619:                                             if (grep(/^default$/,@okstatus)) {
                   4620:                                                 push(@possroles,$role);
                   4621:                                             }
                   4622:                                         } else {
                   4623:                                             foreach my $status (@okstatus) {
                   4624:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   4625:                                                     push(@possroles,$role);
                   4626:                                                     last;
                   4627:                                                 }
                   4628:                                             }
                   4629:                                         }
                   4630:                                     }
                   4631:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4632:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   4633:                                         if ($curraccess eq 'exc') {
                   4634:                                             push(@possroles,$role);
                   4635:                                         }
                   4636:                                     } elsif ($curraccess eq 'inc') {
                   4637:                                         push(@possroles,$role);
                   4638:                                     }
                   4639:                                 }
                   4640:                             }
                   4641:                         }
                   4642:                     }
                   4643:                 }
                   4644:             }
                   4645:         }
                   4646:     }
1.1333  ! raeburn  4647:     unless (ref($description) eq 'HASH') {
        !          4648:         if (ref($roles_by_num) eq 'ARRAY') {
        !          4649:             my %desc;
        !          4650:             map { $desc{$_} = $_; } (@{$roles_by_num});
        !          4651:             $description = \%desc;
        !          4652:         } else {
        !          4653:             $description = {};
        !          4654:         }
        !          4655:     }
        !          4656:     return (\@possroles,$description);
1.1332    raeburn  4657: }
                   4658: 
1.399     www      4659: # ----------------------------------------------------- Frontpage Announcements
                   4660: #
                   4661: #
                   4662: 
                   4663: sub postannounce {
                   4664:     my ($server,$text)=@_;
1.844     albertel 4665:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4666:     unless ($text=~/\w/) { $text=''; }
                   4667:     return &reply('setannounce:'.&escape($text),$server);
                   4668: }
                   4669: 
                   4670: sub getannounce {
1.448     albertel 4671: 
                   4672:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4673: 	my $announcement='';
1.800     albertel 4674: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4675: 	close($fh);
1.399     www      4676: 	if ($announcement=~/\w/) { 
                   4677: 	    return 
                   4678:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4679:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4680: 	} else {
                   4681: 	    return '';
                   4682: 	}
                   4683:     } else {
                   4684: 	return '';
                   4685:     }
1.351     www      4686: }
1.353     www      4687: 
                   4688: # ---------------------------------------------------------- Course ID routines
                   4689: # Deal with domain's nohist_courseid.db files
                   4690: #
                   4691: 
                   4692: sub courseidput {
1.921     raeburn  4693:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4694:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4695:     my $outcome;
                   4696:     if ($caller eq 'timeonly') {
                   4697:         my $cids = '';
                   4698:         foreach my $item (keys(%$storehash)) {
                   4699:             $cids.=&escape($item).'&';
                   4700:         }
                   4701:         $cids=~s/\&$//;
                   4702:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4703:                           $coursehome);       
                   4704:     } else {
                   4705:         my $items = '';
                   4706:         foreach my $item (keys(%$storehash)) {
                   4707:             $items.= &escape($item).'='.
                   4708:                      &freeze_escape($$storehash{$item}).'&';
                   4709:         }
                   4710:         $items=~s/\&$//;
                   4711:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4712:                           $coursehome);
1.918     raeburn  4713:     }
                   4714:     if ($outcome eq 'unknown_cmd') {
                   4715:         my $what;
                   4716:         foreach my $cid (keys(%$storehash)) {
                   4717:             $what .= &escape($cid).'=';
1.921     raeburn  4718:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4719:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4720:             }
                   4721:             $what =~ s/\:$/&/;
                   4722:         }
                   4723:         $what =~ s/\&$//;  
                   4724:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4725:     } else {
                   4726:         return $outcome;
                   4727:     }
1.353     www      4728: }
                   4729: 
                   4730: sub courseiddump {
1.921     raeburn  4731:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4732:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4733:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  4734:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  4735:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  4736:     my $as_hash = 1;
                   4737:     my %returnhash;
                   4738:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4739:     my %libserv = &all_library();
                   4740:     foreach my $tryserver (keys(%libserv)) {
                   4741:         if ( (  $hostidflag == 1 
                   4742: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4743: 	     || (!defined($hostidflag)) ) {
                   4744: 
1.918     raeburn  4745: 	    if (($domfilter eq '') ||
                   4746: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 4747:                 my $rep;
                   4748:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   4749:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   4750:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   4751:                                 &escape($descfilter), &escape($instcodefilter), 
                   4752:                                 &escape($ownerfilter), &escape($coursefilter),
                   4753:                                 &escape($typefilter), &escape($regexp_ok), 
                   4754:                                 $as_hash, &escape($selfenrollonly), 
                   4755:                                 &escape($catfilter), $showhidden, $caller, 
                   4756:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   4757:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  4758:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   4759:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 4760:                 } else {
                   4761:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4762:                              $sincefilter.':'.&escape($descfilter).':'.
                   4763:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4764:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4765:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4766:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4767:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4768:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4769:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  4770:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   4771:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 4772:                 }
                   4773:                      
1.918     raeburn  4774:                 my @pairs=split(/\&/,$rep);
                   4775:                 foreach my $item (@pairs) {
                   4776:                     my ($key,$value)=split(/\=/,$item,2);
                   4777:                     $key = &unescape($key);
                   4778:                     next if ($key =~ /^error: 2 /);
                   4779:                     my $result = &thaw_unescape($value);
                   4780:                     if (ref($result) eq 'HASH') {
                   4781:                         $returnhash{$key}=$result;
                   4782:                     } else {
1.921     raeburn  4783:                         my @responses = split(/:/,$value);
                   4784:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4785:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4786:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4787:                         }
1.1008    raeburn  4788:                     }
1.353     www      4789:                 }
                   4790:             }
                   4791:         }
                   4792:     }
                   4793:     return %returnhash;
                   4794: }
                   4795: 
1.1055    raeburn  4796: sub courselastaccess {
                   4797:     my ($cdom,$cnum,$hostidref) = @_;
                   4798:     my %returnhash;
                   4799:     if ($cdom && $cnum) {
                   4800:         my $chome = &homeserver($cnum,$cdom);
                   4801:         if ($chome ne 'no_host') {
                   4802:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4803:             &extract_lastaccess(\%returnhash,$rep);
                   4804:         }
                   4805:     } else {
                   4806:         if (!$cdom) { $cdom=''; }
                   4807:         my %libserv = &all_library();
                   4808:         foreach my $tryserver (keys(%libserv)) {
                   4809:             if (ref($hostidref) eq 'ARRAY') {
                   4810:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4811:             } 
                   4812:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4813:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4814:                 &extract_lastaccess(\%returnhash,$rep);
                   4815:             }
                   4816:         }
                   4817:     }
                   4818:     return %returnhash;
                   4819: }
                   4820: 
                   4821: sub extract_lastaccess {
                   4822:     my ($returnhash,$rep) = @_;
                   4823:     if (ref($returnhash) eq 'HASH') {
                   4824:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4825:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4826:                  $rep eq '') {
                   4827:             my @pairs=split(/\&/,$rep);
                   4828:             foreach my $item (@pairs) {
                   4829:                 my ($key,$value)=split(/\=/,$item,2);
                   4830:                 $key = &unescape($key);
                   4831:                 next if ($key =~ /^error: 2 /);
                   4832:                 $returnhash->{$key} = &thaw_unescape($value);
                   4833:             }
                   4834:         }
                   4835:     }
                   4836:     return;
                   4837: }
                   4838: 
1.658     raeburn  4839: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4840: 
                   4841: sub dcmailput {
1.685     raeburn  4842:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4843:     my $status = &Apache::lonnet::critical(
1.740     www      4844:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4845:        &escape($message),$server);
1.662     raeburn  4846:     return $status;
                   4847: }
                   4848: 
1.658     raeburn  4849: sub dcmaildump {
                   4850:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4851:     my %returnhash=();
1.846     albertel 4852: 
                   4853:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4854:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4855:                                                          &escape($enddate).':';
                   4856: 	my @esc_senders=map { &escape($_)} @$senders;
                   4857: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4858: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4859:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4860:             if (($key) && ($value)) {
                   4861:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4862:             }
                   4863:         }
                   4864:     }
                   4865:     return %returnhash;
                   4866: }
1.662     raeburn  4867: # ---------------------------------------------------------- Domain roles
                   4868: 
                   4869: sub get_domain_roles {
                   4870:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4871:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4872:         $startdate = '.';
                   4873:     }
1.1018    raeburn  4874:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4875:         $enddate = '.';
                   4876:     }
1.922     raeburn  4877:     my $rolelist;
                   4878:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  4879:         $rolelist = join('&',@{$roles});
1.922     raeburn  4880:     }
1.662     raeburn  4881:     my %personnel = ();
1.841     albertel 4882: 
                   4883:     my %servers = &get_servers($dom,'library');
                   4884:     foreach my $tryserver (keys(%servers)) {
                   4885: 	%{$personnel{$tryserver}}=();
                   4886: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4887: 					    &escape($startdate).':'.
                   4888: 					    &escape($enddate).':'.
                   4889: 					    &escape($rolelist), $tryserver))) {
                   4890: 	    my ($key,$value) = split(/\=/,$line,2);
                   4891: 	    if (($key) && ($value)) {
                   4892: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4893: 	    }
                   4894: 	}
1.662     raeburn  4895:     }
                   4896:     return %personnel;
                   4897: }
1.658     raeburn  4898: 
1.1332    raeburn  4899: sub get_active_domroles {
                   4900:     my ($dom,$roles) = @_;
                   4901:     return () unless (ref($roles) eq 'ARRAY');
                   4902:     my $now = time;
                   4903:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   4904:     my %domroles;
                   4905:     foreach my $server (keys(%dompersonnel)) {
                   4906:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   4907:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   4908:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   4909:         }
                   4910:     }
                   4911:     return %domroles;
                   4912: }
                   4913: 
1.1057    www      4914: # ----------------------------------------------------------- Interval timing 
1.149     www      4915: 
1.1153    www      4916: {
                   4917: # Caches needed for speedup of navmaps
                   4918: # We don't want to cache this for very long at all (5 seconds at most)
                   4919: # 
                   4920: # The user for whom we cache
                   4921: my $cachedkey='';
                   4922: # The cached times for this user
                   4923: my %cachedtimes=();
                   4924: # When this was last done
1.1282    raeburn  4925: my $cachedtime='';
1.1153    www      4926: 
                   4927: sub load_all_first_access {
1.1308    raeburn  4928:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      4929:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  4930:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   4931:         (!$ignorecache)) {
1.1154    raeburn  4932:         return;
                   4933:     }
                   4934:     $cachedtime=time;
                   4935:     $cachedkey=$uname.':'.$udom;
                   4936:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4937: }
                   4938: 
1.504     albertel 4939: sub get_first_access {
1.1308    raeburn  4940:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 4941:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4942:     if ($argsymb) { $symb=$argsymb; }
                   4943:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4944:     if ($argmap) { $map = $argmap; }
1.926     albertel 4945:     if ($type eq 'course') {
                   4946: 	$res='course';
                   4947:     } elsif ($type eq 'map') {
1.588     albertel 4948: 	$res=&symbread($map);
                   4949:     } else {
                   4950: 	$res=$symb;
                   4951:     }
1.1308    raeburn  4952:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      4953:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4954: }
                   4955: 
                   4956: sub set_first_access {
1.1162    raeburn  4957:     my ($type,$interval)=@_;
1.790     albertel 4958:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4959:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4960:     if ($type eq 'course') {
                   4961: 	$res='course';
                   4962:     } elsif ($type eq 'map') {
1.588     albertel 4963: 	$res=&symbread($map);
                   4964:     } else {
                   4965: 	$res=$symb;
                   4966:     }
1.1153    www      4967:     $cachedkey='';
1.1162    raeburn  4968:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4969:     if (!$firstaccess) {
1.1162    raeburn  4970:         my $start = time;
                   4971: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4972:                           $udom,$uname);
                   4973:         if ($putres eq 'ok') {
                   4974:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4975:                  $udom,$uname); 
                   4976:             &appenv(
                   4977:                      {
                   4978:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4979:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4980:                      }
                   4981:                   );
                   4982:         }
                   4983:         return $putres;
1.505     albertel 4984:     }
                   4985:     return 'already_set';
1.504     albertel 4986: }
1.1153    www      4987: }
1.1282    raeburn  4988: 
1.110     www      4989: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4990: 
                   4991: sub expirespread {
                   4992:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4993:     my $cid=$env{'request.course.id'}; 
1.110     www      4994:     if ($cid) {
                   4995:        my $now=time;
                   4996:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4997:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4998:                             $env{'course.'.$cid.'.num'}.
1.110     www      4999: 	        	    ':nohist_expirationdates:'.
                   5000:                             &escape($key).'='.$now,
1.620     albertel 5001:                             $env{'course.'.$cid.'.home'})
1.110     www      5002:     }
                   5003:     return 'ok';
1.14      www      5004: }
                   5005: 
1.109     www      5006: # ----------------------------------------------------- Devalidate Spreadsheets
                   5007: 
                   5008: sub devalidate {
1.325     www      5009:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5010:     my $cid=$env{'request.course.id'}; 
1.109     www      5011:     if ($cid) {
1.391     matthew  5012:         # delete the stored spreadsheets for
                   5013:         # - the student level sheet of this user in course's homespace
                   5014:         # - the assessment level sheet for this resource 
                   5015:         #   for this user in user's homespace
1.553     albertel 5016: 	# - current conditional state info
1.325     www      5017: 	my $key=$uname.':'.$udom.':';
1.109     www      5018:         my $status=
1.299     matthew  5019: 	    &del('nohist_calculatedsheets',
1.391     matthew  5020: 		 [$key.'studentcalc:'],
1.620     albertel 5021: 		 $env{'course.'.$cid.'.domain'},
                   5022: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5023: 		.' '.
                   5024: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5025: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5026:         unless ($status eq 'ok ok') {
                   5027:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5028:                     $uname.' at '.$udom.' for '.
1.109     www      5029: 		    $symb.': '.$status);
1.133     albertel 5030:         }
1.553     albertel 5031: 	&delenv('user.state.'.$cid);
1.109     www      5032:     }
                   5033: }
                   5034: 
1.265     albertel 5035: sub get_scalar {
                   5036:     my ($string,$end) = @_;
                   5037:     my $value;
                   5038:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5039: 	$value = $1;
                   5040:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5041: 	$value = $1;
                   5042:     }
                   5043:     return &unescape($value);
                   5044: }
                   5045: 
                   5046: sub array2str {
                   5047:   my (@array) = @_;
                   5048:   my $result=&arrayref2str(\@array);
                   5049:   $result=~s/^__ARRAY_REF__//;
                   5050:   $result=~s/__END_ARRAY_REF__$//;
                   5051:   return $result;
                   5052: }
                   5053: 
1.204     albertel 5054: sub arrayref2str {
                   5055:   my ($arrayref) = @_;
1.265     albertel 5056:   my $result='__ARRAY_REF__';
1.204     albertel 5057:   foreach my $elem (@$arrayref) {
1.265     albertel 5058:     if(ref($elem) eq 'ARRAY') {
                   5059:       $result.=&arrayref2str($elem).'&';
                   5060:     } elsif(ref($elem) eq 'HASH') {
                   5061:       $result.=&hashref2str($elem).'&';
                   5062:     } elsif(ref($elem)) {
                   5063:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5064:     } else {
                   5065:       $result.=&escape($elem).'&';
                   5066:     }
                   5067:   }
                   5068:   $result=~s/\&$//;
1.265     albertel 5069:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5070:   return $result;
                   5071: }
                   5072: 
1.168     albertel 5073: sub hash2str {
1.204     albertel 5074:   my (%hash) = @_;
                   5075:   my $result=&hashref2str(\%hash);
1.265     albertel 5076:   $result=~s/^__HASH_REF__//;
                   5077:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5078:   return $result;
                   5079: }
                   5080: 
                   5081: sub hashref2str {
                   5082:   my ($hashref)=@_;
1.265     albertel 5083:   my $result='__HASH_REF__';
1.800     albertel 5084:   foreach my $key (sort(keys(%$hashref))) {
                   5085:     if (ref($key) eq 'ARRAY') {
                   5086:       $result.=&arrayref2str($key).'=';
                   5087:     } elsif (ref($key) eq 'HASH') {
                   5088:       $result.=&hashref2str($key).'=';
                   5089:     } elsif (ref($key)) {
1.265     albertel 5090:       $result.='=';
1.800     albertel 5091:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5092:     } else {
1.1132    raeburn  5093: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5094:     }
                   5095: 
1.800     albertel 5096:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5097:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5098:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5099:       $result.=&hashref2str($hashref->{$key}).'&';
                   5100:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5101:        $result.='&';
1.800     albertel 5102:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5103:     } else {
1.800     albertel 5104:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5105:     }
                   5106:   }
1.168     albertel 5107:   $result=~s/\&$//;
1.265     albertel 5108:   $result .= '__END_HASH_REF__';
1.168     albertel 5109:   return $result;
                   5110: }
                   5111: 
                   5112: sub str2hash {
1.265     albertel 5113:     my ($string)=@_;
                   5114:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5115:     return %$hash;
                   5116: }
                   5117: 
                   5118: sub str2hashref {
1.168     albertel 5119:   my ($string) = @_;
1.265     albertel 5120: 
                   5121:   my %hash;
                   5122: 
                   5123:   if($string !~ /^__HASH_REF__/) {
                   5124:       if (! ($string eq '' || !defined($string))) {
                   5125: 	  $hash{'error'}='Not hash reference';
                   5126:       }
                   5127:       return (\%hash, $string);
                   5128:   }
                   5129: 
                   5130:   $string =~ s/^__HASH_REF__//;
                   5131: 
                   5132:   while($string !~ /^__END_HASH_REF__/) {
                   5133:       #key
                   5134:       my $key='';
                   5135:       if($string =~ /^__HASH_REF__/) {
                   5136:           ($key, $string)=&str2hashref($string);
                   5137:           if(defined($key->{'error'})) {
                   5138:               $hash{'error'}='Bad data';
                   5139:               return (\%hash, $string);
                   5140:           }
                   5141:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5142:           ($key, $string)=&str2arrayref($string);
                   5143:           if($key->[0] eq 'Array reference error') {
                   5144:               $hash{'error'}='Bad data';
                   5145:               return (\%hash, $string);
                   5146:           }
                   5147:       } else {
                   5148:           $string =~ s/^(.*?)=//;
1.267     albertel 5149: 	  $key=&unescape($1);
1.265     albertel 5150:       }
                   5151:       $string =~ s/^=//;
                   5152: 
                   5153:       #value
                   5154:       my $value='';
                   5155:       if($string =~ /^__HASH_REF__/) {
                   5156:           ($value, $string)=&str2hashref($string);
                   5157:           if(defined($value->{'error'})) {
                   5158:               $hash{'error'}='Bad data';
                   5159:               return (\%hash, $string);
                   5160:           }
                   5161:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5162:           ($value, $string)=&str2arrayref($string);
                   5163:           if($value->[0] eq 'Array reference error') {
                   5164:               $hash{'error'}='Bad data';
                   5165:               return (\%hash, $string);
                   5166:           }
                   5167:       } else {
                   5168: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5169:       }
                   5170:       $string =~ s/^&//;
                   5171: 
                   5172:       $hash{$key}=$value;
1.204     albertel 5173:   }
1.265     albertel 5174: 
                   5175:   $string =~ s/^__END_HASH_REF__//;
                   5176: 
                   5177:   return (\%hash, $string);
1.204     albertel 5178: }
                   5179: 
                   5180: sub str2array {
1.265     albertel 5181:     my ($string)=@_;
                   5182:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5183:     return @$array;
                   5184: }
                   5185: 
                   5186: sub str2arrayref {
1.204     albertel 5187:   my ($string) = @_;
1.265     albertel 5188:   my @array;
                   5189: 
                   5190:   if($string !~ /^__ARRAY_REF__/) {
                   5191:       if (! ($string eq '' || !defined($string))) {
                   5192: 	  $array[0]='Array reference error';
                   5193:       }
                   5194:       return (\@array, $string);
                   5195:   }
                   5196: 
                   5197:   $string =~ s/^__ARRAY_REF__//;
                   5198: 
                   5199:   while($string !~ /^__END_ARRAY_REF__/) {
                   5200:       my $value='';
                   5201:       if($string =~ /^__HASH_REF__/) {
                   5202:           ($value, $string)=&str2hashref($string);
                   5203:           if(defined($value->{'error'})) {
                   5204:               $array[0] ='Array reference error';
                   5205:               return (\@array, $string);
                   5206:           }
                   5207:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5208:           ($value, $string)=&str2arrayref($string);
                   5209:           if($value->[0] eq 'Array reference error') {
                   5210:               $array[0] ='Array reference error';
                   5211:               return (\@array, $string);
                   5212:           }
                   5213:       } else {
                   5214: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5215:       }
                   5216:       $string =~ s/^&//;
                   5217: 
                   5218:       push(@array, $value);
1.191     harris41 5219:   }
1.265     albertel 5220: 
                   5221:   $string =~ s/^__END_ARRAY_REF__//;
                   5222: 
                   5223:   return (\@array, $string);
1.168     albertel 5224: }
                   5225: 
1.167     albertel 5226: # -------------------------------------------------------------------Temp Store
                   5227: 
1.168     albertel 5228: sub tmpreset {
                   5229:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5230:   if (!$symb) {
                   5231:     $symb=&symbread();
1.620     albertel 5232:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5233:   }
                   5234:   $symb=escape($symb);
                   5235: 
1.620     albertel 5236:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5237:   $namespace=~s/\//\_/g;
                   5238:   $namespace=~s/\W//g;
                   5239: 
1.620     albertel 5240:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5241:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5242:   if ($domain eq 'public' && $stuname eq 'public') {
                   5243:       $stuname=$ENV{'REMOTE_ADDR'};
                   5244:   }
1.1117    foxr     5245:   my $path=LONCAPA::tempdir();
1.168     albertel 5246:   my %hash;
                   5247:   if (tie(%hash,'GDBM_File',
                   5248: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5249: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5250:     foreach my $key (keys(%hash)) {
1.180     albertel 5251:       if ($key=~ /:$symb/) {
1.168     albertel 5252: 	delete($hash{$key});
                   5253:       }
                   5254:     }
                   5255:   }
                   5256: }
                   5257: 
1.167     albertel 5258: sub tmpstore {
1.168     albertel 5259:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5260: 
                   5261:   if (!$symb) {
                   5262:     $symb=&symbread();
1.620     albertel 5263:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5264:   }
                   5265:   $symb=escape($symb);
                   5266: 
                   5267:   if (!$namespace) {
                   5268:     # I don't think we would ever want to store this for a course.
                   5269:     # it seems this will only be used if we don't have a course.
1.620     albertel 5270:     #$namespace=$env{'request.course.id'};
1.168     albertel 5271:     #if (!$namespace) {
1.620     albertel 5272:       $namespace=$env{'request.state'};
1.168     albertel 5273:     #}
                   5274:   }
                   5275:   $namespace=~s/\//\_/g;
                   5276:   $namespace=~s/\W//g;
1.620     albertel 5277:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5278:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5279:   if ($domain eq 'public' && $stuname eq 'public') {
                   5280:       $stuname=$ENV{'REMOTE_ADDR'};
                   5281:   }
1.168     albertel 5282:   my $now=time;
                   5283:   my %hash;
1.1117    foxr     5284:   my $path=LONCAPA::tempdir();
1.168     albertel 5285:   if (tie(%hash,'GDBM_File',
                   5286: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5287: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5288:     $hash{"version:$symb"}++;
                   5289:     my $version=$hash{"version:$symb"};
                   5290:     my $allkeys=''; 
                   5291:     foreach my $key (keys(%$storehash)) {
                   5292:       $allkeys.=$key.':';
1.591     albertel 5293:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5294:     }
                   5295:     $hash{"$version:$symb:timestamp"}=$now;
                   5296:     $allkeys.='timestamp';
                   5297:     $hash{"$version:keys:$symb"}=$allkeys;
                   5298:     if (untie(%hash)) {
                   5299:       return 'ok';
                   5300:     } else {
                   5301:       return "error:$!";
                   5302:     }
                   5303:   } else {
                   5304:     return "error:$!";
                   5305:   }
                   5306: }
1.167     albertel 5307: 
1.168     albertel 5308: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5309: 
1.168     albertel 5310: sub tmprestore {
                   5311:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5312: 
1.168     albertel 5313:   if (!$symb) {
                   5314:     $symb=&symbread();
1.620     albertel 5315:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5316:   }
                   5317:   $symb=escape($symb);
                   5318: 
1.620     albertel 5319:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5320: 
1.620     albertel 5321:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5322:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5323:   if ($domain eq 'public' && $stuname eq 'public') {
                   5324:       $stuname=$ENV{'REMOTE_ADDR'};
                   5325:   }
1.168     albertel 5326:   my %returnhash;
                   5327:   $namespace=~s/\//\_/g;
                   5328:   $namespace=~s/\W//g;
                   5329:   my %hash;
1.1117    foxr     5330:   my $path=LONCAPA::tempdir();
1.168     albertel 5331:   if (tie(%hash,'GDBM_File',
                   5332: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5333: 	  &GDBM_READER(),0640)) {
1.168     albertel 5334:     my $version=$hash{"version:$symb"};
                   5335:     $returnhash{'version'}=$version;
                   5336:     my $scope;
                   5337:     for ($scope=1;$scope<=$version;$scope++) {
                   5338:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5339:       my @keys=split(/:/,$vkeys);
                   5340:       my $key;
                   5341:       $returnhash{"$scope:keys"}=$vkeys;
                   5342:       foreach $key (@keys) {
1.591     albertel 5343: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5344: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5345:       }
                   5346:     }
1.168     albertel 5347:     if (!(untie(%hash))) {
                   5348:       return "error:$!";
                   5349:     }
                   5350:   } else {
                   5351:     return "error:$!";
                   5352:   }
                   5353:   return %returnhash;
1.167     albertel 5354: }
                   5355: 
1.9       www      5356: # ----------------------------------------------------------------------- Store
                   5357: 
                   5358: sub store {
1.1269    raeburn  5359:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5360:     my $home='';
                   5361: 
1.168     albertel 5362:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5363: 
1.213     www      5364:     $symb=&symbclean($symb);
1.122     albertel 5365:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5366: 
1.620     albertel 5367:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5368:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5369: 
                   5370:     &devalidate($symb,$stuname,$domain);
1.109     www      5371: 
                   5372:     $symb=escape($symb);
1.187     www      5373:     if (!$namespace) { 
1.620     albertel 5374:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5375:           return ''; 
                   5376:        } 
                   5377:     }
1.620     albertel 5378:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5379: 
                   5380:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5381:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5382: 
1.12      www      5383:     my $namevalue='';
1.800     albertel 5384:     foreach my $key (keys(%$storehash)) {
                   5385:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5386:     }
1.12      www      5387:     $namevalue=~s/\&$//;
1.187     www      5388:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  5389:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5390: }
                   5391: 
1.47      www      5392: # -------------------------------------------------------------- Critical Store
                   5393: 
                   5394: sub cstore {
1.1269    raeburn  5395:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5396:     my $home='';
                   5397: 
1.168     albertel 5398:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5399: 
1.213     www      5400:     $symb=&symbclean($symb);
1.122     albertel 5401:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5402: 
1.620     albertel 5403:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5404:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5405: 
                   5406:     &devalidate($symb,$stuname,$domain);
1.109     www      5407: 
                   5408:     $symb=escape($symb);
1.187     www      5409:     if (!$namespace) { 
1.620     albertel 5410:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5411:           return ''; 
                   5412:        } 
                   5413:     }
1.620     albertel 5414:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5415: 
                   5416:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5417:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5418: 
1.47      www      5419:     my $namevalue='';
1.800     albertel 5420:     foreach my $key (keys(%$storehash)) {
                   5421:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5422:     }
1.47      www      5423:     $namevalue=~s/\&$//;
1.187     www      5424:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5425:     return critical
1.1269    raeburn  5426:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5427: }
                   5428: 
1.9       www      5429: # --------------------------------------------------------------------- Restore
                   5430: 
                   5431: sub restore {
1.124     www      5432:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5433:     my $home='';
                   5434: 
1.168     albertel 5435:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5436: 
1.122     albertel 5437:     if (!$symb) {
1.1224    raeburn  5438:         return if ($namespace eq 'courserequests');
                   5439:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5440:     } else {
1.1224    raeburn  5441:         unless ($namespace eq 'courserequests') {
                   5442:             $symb=&escape(&symbclean($symb));
                   5443:         }
1.122     albertel 5444:     }
1.188     www      5445:     if (!$namespace) { 
1.620     albertel 5446:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5447:           return ''; 
                   5448:        } 
                   5449:     }
1.620     albertel 5450:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5451:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5452:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5453:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5454: 
1.12      www      5455:     my %returnhash=();
1.800     albertel 5456:     foreach my $line (split(/\&/,$answer)) {
                   5457: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5458:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5459:     }
1.75      www      5460:     my $version;
                   5461:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5462:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5463:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5464:        }
1.75      www      5465:     }
1.13      www      5466:     return %returnhash;
1.34      www      5467: }
                   5468: 
                   5469: # ---------------------------------------------------------- Course Description
1.1118    foxr     5470: #
                   5471: #  
1.34      www      5472: 
                   5473: sub coursedescription {
1.731     albertel 5474:     my ($courseid,$args)=@_;
1.34      www      5475:     $courseid=~s/^\///;
1.49      www      5476:     $courseid=~s/\_/\//g;
1.34      www      5477:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5478:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5479:     my $normalid=$cdomain.'_'.$cnum;
                   5480:     # need to always cache even if we get errors otherwise we keep 
                   5481:     # trying and trying and trying to get the course description.
                   5482:     my %envhash=();
                   5483:     my %returnhash=();
1.731     albertel 5484:     
                   5485:     my $expiretime=600;
                   5486:     if ($env{'request.course.id'} eq $normalid) {
                   5487: 	$expiretime=120;
                   5488:     }
                   5489: 
                   5490:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5491:     if (!$args->{'freshen_cache'}
                   5492: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5493: 	foreach my $key (keys(%env)) {
                   5494: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5495: 	    my ($setting) = $1;
                   5496: 	    $returnhash{$setting} = $env{$key};
                   5497: 	}
                   5498: 	return %returnhash;
                   5499:     }
                   5500: 
1.1118    foxr     5501:     # get the data again
                   5502: 
1.731     albertel 5503:     if (!$args->{'one_time'}) {
                   5504: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5505:     }
1.811     albertel 5506: 
1.34      www      5507:     if ($chome ne 'no_host') {
1.302     albertel 5508:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5509:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5510: 	   my $username = $env{'user.name'}; # Defult username
                   5511: 	   if(defined $args->{'user'}) {
                   5512: 	       $username = $args->{'user'};
                   5513: 	   }
1.129     albertel 5514:            $returnhash{'home'}= $chome;
                   5515: 	   $returnhash{'domain'} = $cdomain;
                   5516: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5517:            if (!defined($returnhash{'type'})) {
                   5518:                $returnhash{'type'} = 'Course';
                   5519:            }
1.130     albertel 5520:            while (my ($name,$value) = each %returnhash) {
1.53      www      5521:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5522:            }
1.270     www      5523:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5524:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5525: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5526:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5527:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5528:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5529:        }
                   5530:     }
1.731     albertel 5531:     if (!$args->{'one_time'}) {
1.949     raeburn  5532: 	&appenv(\%envhash);
1.731     albertel 5533:     }
1.302     albertel 5534:     return %returnhash;
1.461     www      5535: }
                   5536: 
1.1080    raeburn  5537: sub update_released_required {
                   5538:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5539:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5540:         $cid = $env{'request.course.id'};
                   5541:         $cdom = $env{'course.'.$cid.'.domain'};
                   5542:         $cnum = $env{'course.'.$cid.'.num'};
                   5543:         $chome = $env{'course.'.$cid.'.home'};
                   5544:     }
                   5545:     if ($needsrelease) {
                   5546:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5547:         my $needsupdate;
                   5548:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5549:             $needsupdate = 1;
                   5550:         } else {
                   5551:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5552:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5553:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5554:                 $needsupdate = 1;
                   5555:             }
                   5556:         }
                   5557:         if ($needsupdate) {
                   5558:             my %needshash = (
                   5559:                              'internal.releaserequired' => $needsrelease,
                   5560:                             );
                   5561:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5562:             if ($putresult eq 'ok') {
                   5563:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5564:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5565:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5566:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5567:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5568:                 }
                   5569:             }
                   5570:         }
                   5571:     }
                   5572:     return;
                   5573: }
                   5574: 
1.461     www      5575: # -------------------------------------------------See if a user is privileged
                   5576: 
                   5577: sub privileged {
1.1219    raeburn  5578:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5579:     my $now = time;
1.1219    raeburn  5580:     my $roles;
                   5581:     if (ref($possroles) eq 'ARRAY') {
                   5582:         $roles = $possroles; 
                   5583:     } else {
                   5584:         $roles = ['dc','su'];
                   5585:     }
                   5586:     if (ref($possdomains) eq 'ARRAY') {
                   5587:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5588:         foreach my $dom (@{$possdomains}) {
                   5589:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5590:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5591:                 foreach my $role (@{$roles}) {
                   5592:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5593:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5594:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5595:                             return 1 unless (($end && $end < $now) ||
                   5596:                                              ($start && $start > $now));
                   5597:                         }
                   5598:                     }
                   5599:                 }
                   5600:             }
                   5601:         }
                   5602:     } else {
                   5603:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5604:         my $now = time;
1.1170    droeschl 5605: 
1.1275    musolffc 5606:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5607:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  5608:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 5609:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  5610:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5611:             }
1.1219    raeburn  5612:         }
                   5613:     }
                   5614:     return 0;
                   5615: }
1.1170    droeschl 5616: 
1.1219    raeburn  5617: sub privileged_by_domain {
                   5618:     my ($domains,$roles) = @_;
                   5619:     my %privileged = ();
                   5620:     my $cachetime = 60*60*24;
                   5621:     my $now = time;
                   5622:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5623:         return %privileged;
                   5624:     }
                   5625:     foreach my $dom (@{$domains}) {
                   5626:         next if (ref($privileged{$dom}) eq 'HASH');
                   5627:         my $needroles;
                   5628:         foreach my $role (@{$roles}) {
                   5629:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5630:             if (defined($cached)) {
                   5631:                 if (ref($result) eq 'HASH') {
                   5632:                     $privileged{$dom}{$role} = $result;
                   5633:                 }
                   5634:             } else {
                   5635:                 $needroles = 1;
                   5636:             }
                   5637:         }
                   5638:         if ($needroles) {
                   5639:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5640:             $privileged{$dom} = {};
                   5641:             foreach my $server (keys(%dompersonnel)) {
                   5642:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5643:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5644:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5645:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5646:                         next if ($end && $end < $now);
                   5647:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   5648:                             $dompersonnel{$server}{$item};
                   5649:                     }
                   5650:                 }
                   5651:             }
                   5652:             if (ref($privileged{$dom}) eq 'HASH') {
                   5653:                 foreach my $role (@{$roles}) {
                   5654:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5655:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5656:                     } else {
                   5657:                         my %hash = ();
                   5658:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5659:                     }
                   5660:                 }
                   5661:             }
                   5662:         }
                   5663:     }
                   5664:     return %privileged;
1.9       www      5665: }
1.1       albertel 5666: 
1.103     harris41 5667: # -------------------------------------------------------- Get user privileges
1.11      www      5668: 
                   5669: sub rolesinit {
1.1169    droeschl 5670:     my ($domain, $username) = @_;
                   5671:     my %userroles = ('user.login.time' => time);
                   5672:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5673: 
                   5674:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5675:     # also, blocking can be triggered by an activating timer
                   5676:     # it's saved in the user's %env.
                   5677:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5678:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5679:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5680:         %timerintchk, %timerintenv);
                   5681: 
1.1162    raeburn  5682:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5683:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5684:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5685:     }
1.1169    droeschl 5686: 
1.1162    raeburn  5687:     foreach my $key (keys(%timerinterval)) {
                   5688:         my ($cid,$rest) = split(/\0/,$key);
                   5689:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5690:     }
1.1169    droeschl 5691: 
1.11      www      5692:     my %allroles=();
1.1162    raeburn  5693:     my %allgroups=();
1.11      www      5694: 
1.1274    raeburn  5695:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5696:         my $role = $rolesdump{$area};
                   5697:         $area =~ s/\_\w\w$//;
                   5698: 
                   5699:         my ($trole, $tend, $tstart, $group_privs);
                   5700: 
                   5701:         if ($role =~ /^cr/) {
                   5702:         # Custom role, defined by a user 
                   5703:         # e.g., user.role.cr/msu/smith/mynewrole
                   5704:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5705:                 $trole = $1;
                   5706:                 ($tend, $tstart) = split('_', $2);
                   5707:             } else {
                   5708:                 $trole = $role;
                   5709:             }
                   5710:         } elsif ($role =~ m|^gr/|) {
                   5711:         # Role of member in a group, defined within a course/community
                   5712:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5713:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5714:             next if $tstart eq '-1';
                   5715:             ($trole, $group_privs) = split(/\//, $trole);
                   5716:             $group_privs = &unescape($group_privs);
                   5717:         } else {
                   5718:         # Just a normal role, defined in roles.tab
                   5719:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5720:         }
                   5721: 
                   5722:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5723:                  $username);
                   5724:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5725: 
                   5726:         # role expired or not available yet?
                   5727:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5728:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5729: 
                   5730:         next if $area eq '' or $trole eq '';
                   5731: 
                   5732:         my $spec = "$trole.$area";
                   5733:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5734: 
                   5735:         if ($trole =~ /^cr\//) {
                   5736:         # Custom role, defined by a user
                   5737:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5738:         } elsif ($trole eq 'gr') {
                   5739:         # Role of a member in a group, defined within a course/community
                   5740:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5741:             next;
                   5742:         } else {
                   5743:         # Normal role, defined in roles.tab
                   5744:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5745:         }
                   5746: 
                   5747:         my $cid = $tdomain.'_'.$trest;
                   5748:         unless ($firstaccchk{$cid}) {
                   5749:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5750:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5751:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5752:                         $coursetimerstarts{$cid}{$item}; 
                   5753:                 }
                   5754:             }
                   5755:             $firstaccchk{$cid} = 1;
                   5756:         }
                   5757:         unless ($timerintchk{$cid}) {
                   5758:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5759:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5760:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5761:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5762:                 }
1.12      www      5763:             }
1.1169    droeschl 5764:             $timerintchk{$cid} = 1;
1.191     harris41 5765:         }
1.11      www      5766:     }
1.1169    droeschl 5767: 
                   5768:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5769:         \%allroles, \%allgroups);
                   5770:     $env{'user.adv'} = $userroles{'user.adv'};
                   5771: 
1.1162    raeburn  5772:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5773: }
                   5774: 
1.567     raeburn  5775: sub set_arearole {
1.1215    raeburn  5776:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5777:     unless ($nolog) {
1.567     raeburn  5778: # log the associated role with the area
1.1215    raeburn  5779:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5780:     }
1.743     albertel 5781:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5782: }
                   5783: 
                   5784: sub custom_roleprivs {
                   5785:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5786:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  5787:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5788:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5789:         my ($rdummy,$roledef)=
                   5790:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5791:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5792:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5793:             if (defined($syspriv)) {
1.1043    raeburn  5794:                 if ($trest =~ /^$match_community$/) {
                   5795:                     $syspriv =~ s/bre\&S//; 
                   5796:                 }
1.567     raeburn  5797:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5798:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5799:             }
                   5800:             if ($tdomain ne '') {
                   5801:                 if (defined($dompriv)) {
                   5802:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5803:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5804:                 }
                   5805:                 if (($trest ne '') && (defined($coursepriv))) {
1.1332    raeburn  5806:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   5807:                         my $rolename = $1;
                   5808:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   5809:                     }
1.567     raeburn  5810:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5811:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5812:                 }
                   5813:             }
                   5814:         }
                   5815:     }
                   5816: }
                   5817: 
1.1332    raeburn  5818: sub course_adhocrole_privs {
                   5819:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   5820:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   5821:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   5822:         my (%currprivs,%storeprivs);
                   5823:         foreach my $item (split(/:/,$coursepriv)) {
                   5824:             my ($priv,$restrict) = split(/\&/,$item);
                   5825:             $currprivs{$priv} = $restrict;
                   5826:         }
                   5827:         my (%possadd,%possremove,%full);
                   5828:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   5829:             my ($priv,$restrict)=split(/\&/,$item);
                   5830:             $full{$priv} = $restrict;
                   5831:         }
                   5832:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   5833:              next if ($item eq '');
                   5834:              my ($rule,$rest) = split(/=/,$item);
                   5835:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   5836:              foreach my $priv (split(/:/,$rest)) {
                   5837:                  if ($priv ne '') {
                   5838:                      if ($rule eq 'off') {
                   5839:                          $possremove{$priv} = 1;
                   5840:                      } else {
                   5841:                          $possadd{$priv} = 1;
                   5842:                      }
                   5843:                  }
                   5844:              }
                   5845:          }
                   5846:          foreach my $priv (sort(keys(%full))) {
                   5847:              if (exists($currprivs{$priv})) {
                   5848:                  unless (exists($possremove{$priv})) {
                   5849:                      $storeprivs{$priv} = $currprivs{$priv};
                   5850:                  }
                   5851:              } elsif (exists($possadd{$priv})) {
                   5852:                  $storeprivs{$priv} = $full{$priv};
                   5853:              }
                   5854:          }
                   5855:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   5856:      }
                   5857:      return $coursepriv;
                   5858: }
                   5859: 
1.678     raeburn  5860: sub group_roleprivs {
                   5861:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5862:     my $access = 1;
                   5863:     my $now = time;
                   5864:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5865:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5866:     if ($access) {
1.811     albertel 5867:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5868:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5869:     }
                   5870: }
1.567     raeburn  5871: 
                   5872: sub standard_roleprivs {
                   5873:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5874:     if (defined($pr{$trole.':s'})) {
                   5875:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5876:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5877:     }
                   5878:     if ($tdomain ne '') {
                   5879:         if (defined($pr{$trole.':d'})) {
                   5880:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5881:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5882:         }
                   5883:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5884:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5885:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5886:         }
                   5887:     }
                   5888: }
                   5889: 
                   5890: sub set_userprivs {
1.1064    raeburn  5891:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5892:     my $author=0;
                   5893:     my $adv=0;
1.678     raeburn  5894:     my %grouproles = ();
                   5895:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5896:         my @groupkeys; 
1.1000    raeburn  5897:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5898:             push(@groupkeys,$role);
                   5899:         }
                   5900:         if (ref($groups_roles) eq 'HASH') {
                   5901:             foreach my $key (keys(%{$groups_roles})) {
                   5902:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5903:                     push(@groupkeys,$key);
                   5904:                 }
                   5905:             }
                   5906:         }
                   5907:         if (@groupkeys > 0) {
                   5908:             foreach my $role (@groupkeys) {
                   5909:                 my ($trole,$area,$sec,$extendedarea);
                   5910:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5911:                     $trole = $1;
                   5912:                     $area = $2;
                   5913:                     $sec = $3;
                   5914:                     $extendedarea = $area.$sec;
                   5915:                     if (exists($$allgroups{$area})) {
                   5916:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5917:                             my $spec = $trole.'.'.$extendedarea;
                   5918:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5919:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5920:                         }
1.678     raeburn  5921:                     }
                   5922:                 }
                   5923:             }
                   5924:         }
                   5925:     }
1.800     albertel 5926:     foreach my $group (keys(%grouproles)) {
                   5927:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5928:     }
1.800     albertel 5929:     foreach my $role (keys(%{$allroles})) {
                   5930:         my %thesepriv;
1.941     raeburn  5931:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5932:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5933:             if ($item ne '') {
                   5934:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5935:                 if ($restrictions eq '') {
                   5936:                     $thesepriv{$privilege}='F';
                   5937:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5938:                     $thesepriv{$privilege}.=$restrictions;
                   5939:                 }
                   5940:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5941:             }
                   5942:         }
                   5943:         my $thesestr='';
1.1104    raeburn  5944:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5945: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5946: 	}
                   5947:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5948:     }
                   5949:     return ($author,$adv);
                   5950: }
                   5951: 
1.994     raeburn  5952: sub role_status {
1.1104    raeburn  5953:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5954:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  5955:         my ($one,$two) = split(m{\./},$rolekey,2);
                   5956:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  5957:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  5958:             $$where = '/'.$two;
1.994     raeburn  5959:             $$trolecode=$$role.'.'.$$where;
                   5960:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5961:             $$tstatus='is';
1.1104    raeburn  5962:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5963:                 $$tstatus='future';
1.1034    raeburn  5964:                 if ($$tstart<$now) {
                   5965:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5966:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5967:                             my (%allroles,%allgroups,$group_privs,
                   5968:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5969:                             my %userroles = (
                   5970:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5971:                             );
1.1064    raeburn  5972:                             @rolecodes = ('cm'); 
1.1002    raeburn  5973:                             my $spec=$$role.'.'.$$where;
                   5974:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5975:                             if ($$role =~ /^cr\//) {
                   5976:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5977:                                 push(@rolecodes,'cr');
1.1002    raeburn  5978:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5979:                                 push(@rolecodes,$$role);
1.1002    raeburn  5980:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5981:                                                     $env{'user.name'});
1.1064    raeburn  5982:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5983:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5984:                                 $group_privs = &unescape($group_privs);
                   5985:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5986:                                 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  5987:                                 &get_groups_roles($tdomain,$trest,
                   5988:                                                   \%course_roles,\@rolecodes,
                   5989:                                                   \%groups_roles);
1.1002    raeburn  5990:                             } else {
1.1064    raeburn  5991:                                 push(@rolecodes,$$role);
1.1002    raeburn  5992:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5993:                             }
1.1064    raeburn  5994:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5995:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5996:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5997:                         }
                   5998:                     }
1.1034    raeburn  5999:                     $$tstatus = 'is';
1.1002    raeburn  6000:                 }
1.994     raeburn  6001:             }
                   6002:             if ($$tend) {
1.1104    raeburn  6003:                 if ($$tend<$update) {
1.994     raeburn  6004:                     $$tstatus='expired';
                   6005:                 } elsif ($$tend<$now) {
                   6006:                     $$tstatus='will_not';
                   6007:                 }
                   6008:             }
                   6009:         }
                   6010:     }
                   6011: }
                   6012: 
1.1104    raeburn  6013: sub get_groups_roles {
                   6014:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6015:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6016:                   (ref($rolecodes) eq 'ARRAY') && 
                   6017:                   (ref($groups_roles) eq 'HASH')); 
                   6018:     if (keys(%{$cdom_courseroles}) > 0) {
                   6019:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6020:         if ($cdom ne '' && $cnum ne '') {
                   6021:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6022:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6023:                     my $crsrole = $1;
                   6024:                     my $crssec = $2;
                   6025:                     if ($crsrole =~ /^cr/) {
                   6026:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6027:                             push(@{$rolecodes},'cr');
                   6028:                         }
                   6029:                     } else {
                   6030:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6031:                             push(@{$rolecodes},$crsrole);
                   6032:                         }
                   6033:                     }
                   6034:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6035:                     if ($crssec ne '') {
                   6036:                         $rolekey .= "/$crssec";
                   6037:                     }
                   6038:                     $rolekey .= './';
                   6039:                     $groups_roles->{$rolekey} = $rolecodes;
                   6040:                 }
                   6041:             }
                   6042:         }
                   6043:     }
                   6044:     return;
                   6045: }
                   6046: 
                   6047: sub delete_env_groupprivs {
                   6048:     my ($where,$courseroles,$possroles) = @_;
                   6049:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6050:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6051:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6052:         %{$courseroles->{$udom}} =
                   6053:             &get_my_roles('','','userroles',['active'],
                   6054:                           $possroles,[$udom],1);
                   6055:     }
                   6056:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6057:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6058:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6059:             my $area = '/'.$cdom.'/'.$cnum;
                   6060:             my $privkey = "user.priv.$crsrole.$area";
                   6061:             if ($crssec ne '') {
                   6062:                 $privkey .= '/'.$crssec;
                   6063:             }
                   6064:             $privkey .= ".$area/$group";
                   6065:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6066:         }
                   6067:     }
                   6068:     return;
                   6069: }
                   6070: 
1.994     raeburn  6071: sub check_adhoc_privs {
1.1329    raeburn  6072:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6073:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329    raeburn  6074:     if ($sec) {
                   6075:         $cckey .= '/'.$sec;
                   6076:     } 
1.1185    raeburn  6077:     my $setprivs;
1.994     raeburn  6078:     if ($env{$cckey}) {
                   6079:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6080:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6081:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329    raeburn  6082:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6083:             $setprivs = 1;
1.994     raeburn  6084:         }
                   6085:     } else {
1.1330    raeburn  6086:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6087:         $setprivs = 1;
1.994     raeburn  6088:     }
1.1185    raeburn  6089:     return $setprivs;
1.994     raeburn  6090: }
                   6091: 
                   6092: sub set_adhoc_privileges {
1.1326    raeburn  6093: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329    raeburn  6094:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6095:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329    raeburn  6096:     if ($sec ne '') {
                   6097:         $area .= '/'.$sec;
                   6098:     }
1.994     raeburn  6099:     my $spec = $role.'.'.$area;
                   6100:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  6101:                                   $env{'user.name'},1);
1.1326    raeburn  6102:     my %rolehash = ();
1.1332    raeburn  6103:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6104:         my $rolename = $1;
1.1326    raeburn  6105:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332    raeburn  6106:         my %domdef = &get_domain_defaults($dcdom);
                   6107:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6108:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6109:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6110:             }
                   6111:         }
1.1326    raeburn  6112:     } else {
                   6113:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6114:     }
                   6115:     my ($author,$adv)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6116:     &appenv(\%userroles,[$role,'cm']);
                   6117:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  6118:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6119:         &appenv( {'request.role'        => $spec,
                   6120:                   'request.role.domain' => $dcdom,
1.1332    raeburn  6121:                   'request.course.sec'  => $sec,
1.1088    raeburn  6122:                  }
                   6123:                );
                   6124:         my $tadv=0;
                   6125:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6126:         &appenv({'request.role.adv'    => $tadv});
                   6127:     }
1.994     raeburn  6128: }
                   6129: 
1.12      www      6130: # --------------------------------------------------------------- get interface
                   6131: 
                   6132: sub get {
1.131     albertel 6133:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6134:    my $items='';
1.800     albertel 6135:    foreach my $item (@$storearr) {
                   6136:        $items.=&escape($item).'&';
1.191     harris41 6137:    }
1.12      www      6138:    $items=~s/\&$//;
1.620     albertel 6139:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6140:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6141:    my $uhome=&homeserver($uname,$udomain);
                   6142: 
1.133     albertel 6143:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6144:    my @pairs=split(/\&/,$rep);
1.273     albertel 6145:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6146:      return @pairs;
                   6147:    }
1.15      www      6148:    my %returnhash=();
1.42      www      6149:    my $i=0;
1.800     albertel 6150:    foreach my $item (@$storearr) {
                   6151:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6152:       $i++;
1.191     harris41 6153:    }
1.15      www      6154:    return %returnhash;
1.27      www      6155: }
                   6156: 
                   6157: # --------------------------------------------------------------- del interface
                   6158: 
                   6159: sub del {
1.133     albertel 6160:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6161:    my $items='';
1.800     albertel 6162:    foreach my $item (@$storearr) {
                   6163:        $items.=&escape($item).'&';
1.191     harris41 6164:    }
1.984     neumanie 6165: 
1.27      www      6166:    $items=~s/\&$//;
1.620     albertel 6167:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6168:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6169:    my $uhome=&homeserver($uname,$udomain);
                   6170:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6171: }
                   6172: 
                   6173: # -------------------------------------------------------------- dump interface
                   6174: 
1.1180    droeschl 6175: sub unserialize {
                   6176:     my ($rep, $escapedkeys) = @_;
                   6177: 
                   6178:     return {} if $rep =~ /^error/;
                   6179: 
                   6180:     my %returnhash=();
1.1252    raeburn  6181: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 6182: 	    my ($key, $value) = split(/=/, $item, 2);
                   6183: 	    $key = unescape($key) unless $escapedkeys;
                   6184: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  6185: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 6186: 	}
                   6187:     #return %returnhash;
                   6188:     return \%returnhash;
                   6189: }        
                   6190: 
                   6191: # see Lond::dump_with_regexp
                   6192: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6193: sub dump {
1.1180    droeschl 6194:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6195:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6196:     if (!$uname) { $uname=$env{'user.name'}; }
                   6197:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6198: 
1.1266    raeburn  6199:     if ($regexp) {
                   6200:         $regexp=&escape($regexp);
                   6201:     } else {
                   6202:         $regexp='.';
                   6203:     }
1.1180    droeschl 6204:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   6205:         # user is hosted on this machine
1.1266    raeburn  6206:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  6207:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 6208:         return %{unserialize($reply, $escapedkeys)};
                   6209:     }
1.1166    raeburn  6210:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6211:     my @pairs=split(/\&/,$rep);
                   6212:     my %returnhash=();
1.1098    foxr     6213:     if (!($rep =~ /^error/ )) {
                   6214: 	foreach my $item (@pairs) {
                   6215: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 6216:         $key = unescape($key) unless $escapedkeys;
                   6217:         #$key = &unescape($key);
1.1098    foxr     6218: 	    next if ($key =~ /^error: 2 /);
                   6219: 	    $returnhash{$key}=&thaw_unescape($value);
                   6220: 	}
1.755     albertel 6221:     }
                   6222:     return %returnhash;
1.407     www      6223: }
                   6224: 
1.1098    foxr     6225: 
1.717     albertel 6226: # --------------------------------------------------------- dumpstore interface
                   6227: 
                   6228: sub dumpstore {
                   6229:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 6230:    # same as dump but keys must be escaped. They may contain colon separated
                   6231:    # lists of values that may themself contain colons (e.g. symbs).
                   6232:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6233: }
                   6234: 
1.407     www      6235: # -------------------------------------------------------------- keys interface
                   6236: 
                   6237: sub getkeys {
                   6238:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6239:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6240:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6241:    my $uhome=&homeserver($uname,$udomain);
                   6242:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6243:    my @keyarray=();
1.800     albertel 6244:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6245:       next if ($key =~ /^error: 2 /);
1.800     albertel 6246:       push(@keyarray,&unescape($key));
1.407     www      6247:    }
                   6248:    return @keyarray;
1.318     matthew  6249: }
                   6250: 
1.319     matthew  6251: # --------------------------------------------------------------- currentdump
                   6252: sub currentdump {
1.328     matthew  6253:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6254:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6255:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6256:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6257:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 6258:    my $rep;
                   6259: 
                   6260:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6261:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   6262:                    $courseid)));
                   6263:    } else {
                   6264:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6265:    }
                   6266: 
1.318     matthew  6267:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6268:    #
1.318     matthew  6269:    my %returnhash=();
1.319     matthew  6270:    #
                   6271:    if ($rep eq "unknown_cmd") { 
                   6272:        # an old lond will not know currentdump
                   6273:        # Do a dump and make it look like a currentdump
1.822     albertel 6274:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6275:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6276:        my %hash = @tmp;
                   6277:        @tmp=();
1.424     matthew  6278:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6279:    } else {
                   6280:        my @pairs=split(/\&/,$rep);
1.800     albertel 6281:        foreach my $pair (@pairs) {
                   6282:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6283:            my ($symb,$param) = split(/:/,$key);
                   6284:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6285:                                                         &thaw_unescape($value);
1.319     matthew  6286:        }
1.191     harris41 6287:    }
1.12      www      6288:    return %returnhash;
1.424     matthew  6289: }
                   6290: 
                   6291: sub convert_dump_to_currentdump{
                   6292:     my %hash = %{shift()};
                   6293:     my %returnhash;
                   6294:     # Code ripped from lond, essentially.  The only difference
                   6295:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6296:     # we might run in to problems with parameter names =~ /^v\./
                   6297:     while (my ($key,$value) = each(%hash)) {
                   6298:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6299: 	$symb  = &unescape($symb);
                   6300: 	$param = &unescape($param);
1.424     matthew  6301:         next if ($v eq 'version' || $symb eq 'keys');
                   6302:         next if (exists($returnhash{$symb}) &&
                   6303:                  exists($returnhash{$symb}->{$param}) &&
                   6304:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6305:         $returnhash{$symb}->{$param}=$value;
                   6306:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6307:     }
                   6308:     #
                   6309:     # Remove all of the keys in the hashes which keep track of
                   6310:     # the version of the parameter.
                   6311:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6312:         # use a foreach because we are going to delete from the hash.
                   6313:         foreach my $key (keys(%$param_hash)) {
                   6314:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6315:         }
                   6316:     }
                   6317:     return \%returnhash;
1.12      www      6318: }
                   6319: 
1.627     albertel 6320: # ------------------------------------------------------ critical inc interface
                   6321: 
                   6322: sub cinc {
                   6323:     return &inc(@_,'critical');
                   6324: }
                   6325: 
1.449     matthew  6326: # --------------------------------------------------------------- inc interface
                   6327: 
                   6328: sub inc {
1.627     albertel 6329:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6330:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6331:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6332:     my $uhome=&homeserver($uname,$udomain);
                   6333:     my $items='';
                   6334:     if (! ref($store)) {
                   6335:         # got a single value, so use that instead
                   6336:         $items = &escape($store).'=&';
                   6337:     } elsif (ref($store) eq 'SCALAR') {
                   6338:         $items = &escape($$store).'=&';        
                   6339:     } elsif (ref($store) eq 'ARRAY') {
                   6340:         $items = join('=&',map {&escape($_);} @{$store});
                   6341:     } elsif (ref($store) eq 'HASH') {
                   6342:         while (my($key,$value) = each(%{$store})) {
                   6343:             $items.= &escape($key).'='.&escape($value).'&';
                   6344:         }
                   6345:     }
                   6346:     $items=~s/\&$//;
1.627     albertel 6347:     if ($critical) {
                   6348: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6349:     } else {
                   6350: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6351:     }
1.449     matthew  6352: }
                   6353: 
1.12      www      6354: # --------------------------------------------------------------- put interface
                   6355: 
                   6356: sub put {
1.134     albertel 6357:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6358:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6359:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6360:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6361:    my $items='';
1.800     albertel 6362:    foreach my $item (keys(%$storehash)) {
                   6363:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6364:    }
1.12      www      6365:    $items=~s/\&$//;
1.134     albertel 6366:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6367: }
                   6368: 
1.631     albertel 6369: # ------------------------------------------------------------ newput interface
                   6370: 
                   6371: sub newput {
                   6372:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6373:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6374:    if (!$uname) { $uname=$env{'user.name'}; }
                   6375:    my $uhome=&homeserver($uname,$udomain);
                   6376:    my $items='';
                   6377:    foreach my $key (keys(%$storehash)) {
                   6378:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6379:    }
                   6380:    $items=~s/\&$//;
                   6381:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6382: }
                   6383: 
                   6384: # ---------------------------------------------------------  putstore interface
                   6385: 
1.524     raeburn  6386: sub putstore {
1.1269    raeburn  6387:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6388:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6389:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6390:    my $uhome=&homeserver($uname,$udomain);
                   6391:    my $items='';
1.715     albertel 6392:    foreach my $key (keys(%$storehash)) {
                   6393:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6394:    }
1.715     albertel 6395:    $items=~s/\&$//;
1.716     albertel 6396:    my $esc_symb=&escape($symb);
                   6397:    my $esc_v=&escape($version);
1.715     albertel 6398:    my $reply =
1.716     albertel 6399:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6400: 	      $uhome);
1.1269    raeburn  6401:    if (($tolog) && ($reply eq 'ok')) {
                   6402:        my $namevalue='';
                   6403:        foreach my $key (keys(%{$storehash})) {
                   6404:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6405:        }
                   6406:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6407:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6408:                      '&version='.$esc_v.
                   6409:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6410:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6411:    }
1.715     albertel 6412:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6413:        # gfall back to way things use to be done
1.715     albertel 6414:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6415: 			    $uname);
1.524     raeburn  6416:    }
1.715     albertel 6417:    return $reply;
                   6418: }
                   6419: 
                   6420: sub old_putstore {
1.716     albertel 6421:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6422:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6423:     if (!$uname) { $uname=$env{'user.name'}; }
                   6424:     my $uhome=&homeserver($uname,$udomain);
                   6425:     my %newstorehash;
1.800     albertel 6426:     foreach my $item (keys(%$storehash)) {
                   6427: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6428: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6429:     }
                   6430:     my $items='';
                   6431:     my %allitems = ();
1.800     albertel 6432:     foreach my $item (keys(%newstorehash)) {
                   6433: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6434: 	    my $key = $1.':keys:'.$2;
                   6435: 	    $allitems{$key} .= $3.':';
                   6436: 	}
1.800     albertel 6437: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6438:     }
1.800     albertel 6439:     foreach my $item (keys(%allitems)) {
                   6440: 	$allitems{$item} =~ s/\:$//;
                   6441: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6442:     }
                   6443:     $items=~s/\&$//;
                   6444:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6445: }
                   6446: 
1.47      www      6447: # ------------------------------------------------------ critical put interface
                   6448: 
                   6449: sub cput {
1.134     albertel 6450:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6451:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6452:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6453:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6454:    my $items='';
1.800     albertel 6455:    foreach my $item (keys(%$storehash)) {
                   6456:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6457:    }
1.47      www      6458:    $items=~s/\&$//;
1.134     albertel 6459:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6460: }
                   6461: 
                   6462: # -------------------------------------------------------------- eget interface
                   6463: 
                   6464: sub eget {
1.133     albertel 6465:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6466:    my $items='';
1.800     albertel 6467:    foreach my $item (@$storearr) {
                   6468:        $items.=&escape($item).'&';
1.191     harris41 6469:    }
1.12      www      6470:    $items=~s/\&$//;
1.620     albertel 6471:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6472:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6473:    my $uhome=&homeserver($uname,$udomain);
                   6474:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6475:    my @pairs=split(/\&/,$rep);
                   6476:    my %returnhash=();
1.42      www      6477:    my $i=0;
1.800     albertel 6478:    foreach my $item (@$storearr) {
                   6479:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6480:       $i++;
1.191     harris41 6481:    }
1.12      www      6482:    return %returnhash;
                   6483: }
                   6484: 
1.667     albertel 6485: # ------------------------------------------------------------ tmpput interface
                   6486: sub tmpput {
1.802     raeburn  6487:     my ($storehash,$server,$context)=@_;
1.667     albertel 6488:     my $items='';
1.800     albertel 6489:     foreach my $item (keys(%$storehash)) {
                   6490: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6491:     }
                   6492:     $items=~s/\&$//;
1.802     raeburn  6493:     if (defined($context)) {
                   6494:         $items .= ':'.&escape($context);
                   6495:     }
1.667     albertel 6496:     return &reply("tmpput:$items",$server);
                   6497: }
                   6498: 
                   6499: # ------------------------------------------------------------ tmpget interface
                   6500: sub tmpget {
1.688     albertel 6501:     my ($token,$server)=@_;
                   6502:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6503:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6504:     my %returnhash;
1.1328    raeburn  6505:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   6506:         return %returnhash;
                   6507:     }
1.667     albertel 6508:     foreach my $item (split(/\&/,$rep)) {
                   6509: 	my ($key,$value)=split(/=/,$item);
                   6510: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6511:     }
                   6512:     return %returnhash;
                   6513: }
                   6514: 
1.1113    raeburn  6515: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6516: sub tmpdel {
                   6517:     my ($token,$server)=@_;
                   6518:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6519:     return &reply("tmpdel:$token",$server);
                   6520: }
                   6521: 
1.1198    raeburn  6522: # ------------------------------------------------------------ get_timebased_id 
                   6523: 
                   6524: sub get_timebased_id {
                   6525:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6526:         $maxtries) = @_;
                   6527:     my ($newid,$error,$dellock);
                   6528:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   6529:         return ('','ok','invalid call to get suffix');
                   6530:     }
                   6531: 
                   6532: # set defaults for any optional args for which values were not supplied
                   6533:     if ($who eq '') {
                   6534:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6535:     }
                   6536:     if (!$locktries) {
                   6537:         $locktries = 3;
                   6538:     }
                   6539:     if (!$maxtries) {
                   6540:         $maxtries = 10;
                   6541:     }
                   6542:     
                   6543:     if (($cdom eq '') || ($cnum eq '')) {
                   6544:         if ($env{'request.course.id'}) {
                   6545:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6546:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6547:         }
                   6548:         if (($cdom eq '') || ($cnum eq '')) {
                   6549:             return ('','ok','call to get suffix not in course context');
                   6550:         }
                   6551:     }
                   6552: 
                   6553: # construct locking item
                   6554:     my $lockhash = {
                   6555:                       $prefix."\0".'locked_'.$keyid => $who,
                   6556:                    };
                   6557:     my $tries = 0;
                   6558: 
                   6559: # attempt to get lock on nohist_$namespace file
                   6560:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6561:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6562:         $tries ++;
                   6563:         sleep 1;
                   6564:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6565:     }
                   6566: 
                   6567: # attempt to get unique identifier, based on current timestamp
                   6568:     if ($gotlock eq 'ok') {
                   6569:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6570:         my $id = time;
                   6571:         $newid = $id;
1.1268    raeburn  6572:         if ($idtype eq 'addcode') {
                   6573:             $newid .= &sixnum_code();
                   6574:         }
1.1198    raeburn  6575:         my $idtries = 0;
                   6576:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6577:             if ($idtype eq 'concat') {
                   6578:                 $newid = $id.$idtries;
1.1268    raeburn  6579:             } elsif ($idtype eq 'addcode') {
                   6580:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  6581:             } else {
                   6582:                 $newid ++;
                   6583:             }
                   6584:             $idtries ++;
                   6585:         }
                   6586:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6587:             my %new_item =  (
                   6588:                               $prefix."\0".$newid => $who,
                   6589:                             );
                   6590:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6591:                                                  $cdom,$cnum);
                   6592:             if ($putresult ne 'ok') {
                   6593:                 undef($newid);
                   6594:                 $error = 'error saving new item: '.$putresult;
                   6595:             }
                   6596:         } else {
1.1268    raeburn  6597:              undef($newid);
1.1198    raeburn  6598:              $error = ('error: no unique suffix available for the new item ');
                   6599:         }
                   6600: #  remove lock
                   6601:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6602:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6603:     } else {
                   6604:         $error = "error: could not obtain lockfile\n";
                   6605:         $dellock = 'ok';
1.1276    raeburn  6606:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6607:             $dellock = 'nolock';
                   6608:         }
1.1198    raeburn  6609:     }
                   6610:     return ($newid,$dellock,$error);
                   6611: }
                   6612: 
1.1268    raeburn  6613: sub sixnum_code {
                   6614:     my $code;
                   6615:     for (0..6) {
                   6616:         $code .= int( rand(9) );
                   6617:     }
                   6618:     return $code;
                   6619: }
                   6620: 
1.765     albertel 6621: # -------------------------------------------------- portfolio access checking
                   6622: 
                   6623: sub portfolio_access {
1.1270    raeburn  6624:     my ($requrl,$clientip) = @_;
1.765     albertel 6625:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  6626:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6627:     if ($result) {
                   6628:         my %setters;
                   6629:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6630:             my ($startblock,$endblock) =
                   6631:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6632:             if ($startblock && $endblock) {
                   6633:                 return 'B';
                   6634:             }
                   6635:         } else {
                   6636:             my ($startblock,$endblock) =
                   6637:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6638:             if ($startblock && $endblock) {
                   6639:                 return 'B';
                   6640:             }
                   6641:         }
                   6642:     }
1.765     albertel 6643:     if ($result eq 'ok') {
1.766     albertel 6644:        return 'F';
1.765     albertel 6645:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6646:        return 'A';
1.765     albertel 6647:     }
1.766     albertel 6648:     return '';
1.765     albertel 6649: }
                   6650: 
                   6651: sub get_portfolio_access {
1.1270    raeburn  6652:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 6653: 
                   6654:     if (!ref($access_hash)) {
                   6655: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6656: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6657: 						   $file_name);
                   6658: 	$access_hash = $access_controls{$file_name};
                   6659:     }
                   6660: 
1.1270    raeburn  6661:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 6662:     my $now = time;
                   6663:     if (ref($access_hash) eq 'HASH') {
                   6664:         foreach my $key (keys(%{$access_hash})) {
                   6665:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6666:             if ($start > $now) {
                   6667:                 next;
                   6668:             }
                   6669:             if ($end && $end<$now) {
                   6670:                 next;
                   6671:             }
                   6672:             if ($scope eq 'public') {
                   6673:                 $public = $key;
                   6674:                 last;
                   6675:             } elsif ($scope eq 'guest') {
                   6676:                 $guest = $key;
                   6677:             } elsif ($scope eq 'domains') {
                   6678:                 push(@domains,$key);
                   6679:             } elsif ($scope eq 'users') {
                   6680:                 push(@users,$key);
                   6681:             } elsif ($scope eq 'course') {
                   6682:                 push(@courses,$key);
                   6683:             } elsif ($scope eq 'group') {
                   6684:                 push(@groups,$key);
1.1270    raeburn  6685:             } elsif ($scope eq 'ip') {
                   6686:                 push(@ips,$key);
1.765     albertel 6687:             }
                   6688:         }
                   6689:         if ($public) {
                   6690:             return 'ok';
1.1270    raeburn  6691:         } elsif (@ips > 0) {
                   6692:             my $allowed;
                   6693:             foreach my $ipkey (@ips) {
                   6694:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   6695:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   6696:                         $allowed = 1;
                   6697:                         last; 
                   6698:                     }
                   6699:                 }
                   6700:             }
                   6701:             if ($allowed) {
                   6702:                 return 'ok';
                   6703:             }
1.765     albertel 6704:         }
                   6705:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6706:             if ($guest) {
                   6707:                 return $guest;
                   6708:             }
                   6709:         } else {
                   6710:             if (@domains > 0) {
                   6711:                 foreach my $domkey (@domains) {
                   6712:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6713:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6714:                             return 'ok';
                   6715:                         }
                   6716:                     }
                   6717:                 }
                   6718:             }
                   6719:             if (@users > 0) {
                   6720:                 foreach my $userkey (@users) {
1.865     raeburn  6721:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6722:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6723:                             if (ref($item) eq 'HASH') {
                   6724:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6725:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6726:                                     return 'ok';
                   6727:                                 }
                   6728:                             }
                   6729:                         }
                   6730:                     } 
1.765     albertel 6731:                 }
                   6732:             }
                   6733:             my %roleshash;
                   6734:             my @courses_and_groups = @courses;
                   6735:             push(@courses_and_groups,@groups); 
                   6736:             if (@courses_and_groups > 0) {
                   6737:                 my (%allgroups,%allroles); 
                   6738:                 my ($start,$end,$role,$sec,$group);
                   6739:                 foreach my $envkey (%env) {
1.1060    raeburn  6740:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6741:                         my $cid = $2.'_'.$3; 
                   6742:                         if ($1 eq 'gr') {
                   6743:                             $group = $4;
                   6744:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6745:                         } else {
                   6746:                             if ($4 eq '') {
                   6747:                                 $sec = 'none';
                   6748:                             } else {
                   6749:                                 $sec = $4;
                   6750:                             }
                   6751:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6752:                         }
1.811     albertel 6753:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6754:                         my $cid = $2.'_'.$3;
                   6755:                         if ($4 eq '') {
                   6756:                             $sec = 'none';
                   6757:                         } else {
                   6758:                             $sec = $4;
                   6759:                         }
                   6760:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6761:                     }
                   6762:                 }
                   6763:                 if (keys(%allroles) == 0) {
                   6764:                     return;
                   6765:                 }
                   6766:                 foreach my $key (@courses_and_groups) {
                   6767:                     my %content = %{$$access_hash{$key}};
                   6768:                     my $cnum = $content{'number'};
                   6769:                     my $cdom = $content{'domain'};
                   6770:                     my $cid = $cdom.'_'.$cnum;
                   6771:                     if (!exists($allroles{$cid})) {
                   6772:                         next;
                   6773:                     }    
                   6774:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6775:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6776:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6777:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6778:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6779:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6780:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6781:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6782:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6783:                                         if (grep/^all$/,@sections) {
                   6784:                                             return 'ok';
                   6785:                                         } else {
                   6786:                                             if (grep/^$sec$/,@sections) {
                   6787:                                                 return 'ok';
                   6788:                                             }
                   6789:                                         }
                   6790:                                     }
                   6791:                                 }
                   6792:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6793:                                     if (grep/^none$/,@groups) {
                   6794:                                         return 'ok';
                   6795:                                     }
                   6796:                                 } else {
                   6797:                                     if (grep/^all$/,@groups) {
                   6798:                                         return 'ok';
                   6799:                                     } 
                   6800:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6801:                                         if (grep/^$group$/,@groups) {
                   6802:                                             return 'ok';
                   6803:                                         }
                   6804:                                     }
                   6805:                                 } 
                   6806:                             }
                   6807:                         }
                   6808:                     }
                   6809:                 }
                   6810:             }
                   6811:             if ($guest) {
                   6812:                 return $guest;
                   6813:             }
                   6814:         }
                   6815:     }
                   6816:     return;
                   6817: }
                   6818: 
                   6819: sub course_group_datechecker {
                   6820:     my ($dates,$now,$status) = @_;
                   6821:     my ($start,$end) = split(/\./,$dates);
                   6822:     if (!$start && !$end) {
                   6823:         return 'ok';
                   6824:     }
                   6825:     if (grep/^active$/,@{$status}) {
                   6826:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6827:             return 'ok';
                   6828:         }
                   6829:     }
                   6830:     if (grep/^previous$/,@{$status}) {
                   6831:         if ($end > $now ) {
                   6832:             return 'ok';
                   6833:         }
                   6834:     }
                   6835:     if (grep/^future$/,@{$status}) {
                   6836:         if ($start > $now) {
                   6837:             return 'ok';
                   6838:         }
                   6839:     }
                   6840:     return; 
                   6841: }
                   6842: 
                   6843: sub parse_portfolio_url {
                   6844:     my ($url) = @_;
                   6845: 
                   6846:     my ($type,$udom,$unum,$group,$file_name);
                   6847:     
1.823     albertel 6848:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6849: 	$type = 1;
                   6850:         $udom = $1;
                   6851:         $unum = $2;
                   6852:         $file_name = $3;
1.823     albertel 6853:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6854: 	$type = 2;
                   6855:         $udom = $1;
                   6856:         $unum = $2;
                   6857:         $group = $3;
                   6858:         $file_name = $3.'/'.$4;
                   6859:     }
                   6860:     if (wantarray) {
                   6861: 	return ($type,$udom,$unum,$file_name,$group);
                   6862:     }
                   6863:     return $type;
                   6864: }
                   6865: 
                   6866: sub is_portfolio_url {
                   6867:     my ($url) = @_;
                   6868:     return scalar(&parse_portfolio_url($url));
                   6869: }
                   6870: 
1.798     raeburn  6871: sub is_portfolio_file {
                   6872:     my ($file) = @_;
1.820     raeburn  6873:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6874:         return 1;
                   6875:     }
                   6876:     return;
                   6877: }
                   6878: 
1.976     raeburn  6879: sub usertools_access {
1.1084    raeburn  6880:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6881:     my ($access,%tools);
                   6882:     if ($context eq '') {
                   6883:         $context = 'tools';
                   6884:     }
                   6885:     if ($context eq 'requestcourses') {
                   6886:         %tools = (
                   6887:                       official   => 1,
                   6888:                       unofficial => 1,
1.1006    raeburn  6889:                       community  => 1,
1.1246    raeburn  6890:                       textbook   => 1,
1.1305    raeburn  6891:                       placement  => 1,
1.985     raeburn  6892:                  );
1.1183    raeburn  6893:     } elsif ($context eq 'requestauthor') {
                   6894:         %tools = (
                   6895:                       requestauthor => 1,
                   6896:                  );
1.985     raeburn  6897:     } else {
                   6898:         %tools = (
                   6899:                       aboutme   => 1,
                   6900:                       blog      => 1,
1.1177    raeburn  6901:                       webdav    => 1,
1.985     raeburn  6902:                       portfolio => 1,
                   6903:                  );
                   6904:     }
1.976     raeburn  6905:     return if (!defined($tools{$tool}));
                   6906: 
1.1242    raeburn  6907:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6908:         $udom = $env{'user.domain'};
                   6909:         $uname = $env{'user.name'};
                   6910:     }
                   6911: 
1.978     raeburn  6912:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6913:         if ($action ne 'reload') {
1.985     raeburn  6914:             if ($context eq 'requestcourses') {
                   6915:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  6916:             } elsif ($context eq 'requestauthor') {
                   6917:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6918:             } else {
                   6919:                 return $env{'environment.availabletools.'.$tool};
                   6920:             }
                   6921:         }
1.976     raeburn  6922:     }
                   6923: 
1.1183    raeburn  6924:     my ($toolstatus,$inststatus,$envkey);
                   6925:     if ($context eq 'requestauthor') {
                   6926:         $envkey = $context; 
                   6927:     } else {
                   6928:         $envkey = $context.'.'.$tool;
                   6929:     }
1.976     raeburn  6930: 
1.985     raeburn  6931:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6932:          ($action ne 'reload')) {
1.1183    raeburn  6933:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6934:         $inststatus = $env{'environment.inststatus'};
                   6935:     } else {
1.1084    raeburn  6936:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  6937:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6938:             $inststatus = $userenvref->{'inststatus'};
                   6939:         } else {
1.1183    raeburn  6940:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6941:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6942:             $inststatus = $userenv{'inststatus'};
                   6943:         }
1.976     raeburn  6944:     }
                   6945: 
                   6946:     if ($toolstatus ne '') {
                   6947:         if ($toolstatus) {
                   6948:             $access = 1;
                   6949:         } else {
                   6950:             $access = 0;
                   6951:         }
                   6952:         return $access;
                   6953:     }
                   6954: 
1.1084    raeburn  6955:     my ($is_adv,%domdef);
                   6956:     if (ref($is_advref) eq 'HASH') {
                   6957:         $is_adv = $is_advref->{'is_adv'};
                   6958:     } else {
                   6959:         $is_adv = &is_advanced_user($udom,$uname);
                   6960:     }
                   6961:     if (ref($domdefref) eq 'HASH') {
                   6962:         %domdef = %{$domdefref};
                   6963:     } else {
                   6964:         %domdef = &get_domain_defaults($udom);
                   6965:     }
1.976     raeburn  6966:     if (ref($domdef{$tool}) eq 'HASH') {
                   6967:         if ($is_adv) {
                   6968:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6969:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6970:                     $access = 1;
                   6971:                 } else {
                   6972:                     $access = 0;
                   6973:                 }
                   6974:                 return $access;
                   6975:             }
                   6976:         }
                   6977:         if ($inststatus ne '') {
                   6978:             my ($hasaccess,$hasnoaccess);
                   6979:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6980:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6981:                     if ($domdef{$tool}{$affiliation}) {
                   6982:                         $hasaccess = 1;
                   6983:                     } else {
                   6984:                         $hasnoaccess = 1;
                   6985:                     }
                   6986:                 }
                   6987:             }
                   6988:             if ($hasaccess || $hasnoaccess) {
                   6989:                 if ($hasaccess) {
                   6990:                     $access = 1;
                   6991:                 } elsif ($hasnoaccess) {
                   6992:                     $access = 0; 
                   6993:                 }
                   6994:                 return $access;
                   6995:             }
                   6996:         } else {
                   6997:             if ($domdef{$tool}{'default'} ne '') {
                   6998:                 if ($domdef{$tool}{'default'}) {
                   6999:                     $access = 1;
                   7000:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7001:                     $access = 0;
                   7002:                 }
                   7003:                 return $access;
                   7004:             }
                   7005:         }
                   7006:     } else {
1.1177    raeburn  7007:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7008:             $access = 1;
                   7009:         } else {
                   7010:             $access = 0;
                   7011:         }
1.976     raeburn  7012:         return $access;
                   7013:     }
                   7014: }
                   7015: 
1.1050    raeburn  7016: sub is_course_owner {
                   7017:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7018:     if (($udom eq '') || ($uname eq '')) {
                   7019:         $udom = $env{'user.domain'};
                   7020:         $uname = $env{'user.name'};
                   7021:     }
                   7022:     unless (($udom eq '') || ($uname eq '')) {
                   7023:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7024:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7025:                 return 1;
                   7026:             } else {
                   7027:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7028:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7029:                     return 1;
                   7030:                 }
                   7031:             }
                   7032:         }
                   7033:     }
                   7034:     return;
                   7035: }
                   7036: 
1.976     raeburn  7037: sub is_advanced_user {
                   7038:     my ($udom,$uname) = @_;
1.1085    raeburn  7039:     if ($udom ne '' && $uname ne '') {
                   7040:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7041:             if (wantarray) {
                   7042:                 return ($env{'user.adv'},$env{'user.author'});
                   7043:             } else {
                   7044:                 return $env{'user.adv'};
                   7045:             }
1.1085    raeburn  7046:         }
                   7047:     }
1.976     raeburn  7048:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7049:     my %allroles;
1.1128    raeburn  7050:     my ($is_adv,$is_author);
1.976     raeburn  7051:     foreach my $role (keys(%roleshash)) {
                   7052:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7053:         my $area = '/'.$tdomain.'/'.$trest;
                   7054:         if ($sec ne '') {
                   7055:             $area .= '/'.$sec;
                   7056:         }
                   7057:         if (($area ne '') && ($trole ne '')) {
                   7058:             my $spec=$trole.'.'.$area;
                   7059:             if ($trole =~ /^cr\//) {
                   7060:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7061:             } elsif ($trole ne 'gr') {
                   7062:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7063:             }
1.1128    raeburn  7064:             if ($trole eq 'au') {
                   7065:                 $is_author = 1;
                   7066:             }
1.976     raeburn  7067:         }
                   7068:     }
                   7069:     foreach my $role (keys(%allroles)) {
                   7070:         last if ($is_adv);
                   7071:         foreach my $item (split(/:/,$allroles{$role})) {
                   7072:             if ($item ne '') {
                   7073:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7074:                 if ($privilege eq 'adv') {
                   7075:                     $is_adv = 1;
                   7076:                     last;
                   7077:                 }
                   7078:             }
                   7079:         }
                   7080:     }
1.1128    raeburn  7081:     if (wantarray) {
                   7082:         return ($is_adv,$is_author);
                   7083:     }
1.976     raeburn  7084:     return $is_adv;
                   7085: }
1.798     raeburn  7086: 
1.1035    raeburn  7087: sub check_can_request {
1.1036    raeburn  7088:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7089:     my $canreq = 0;
                   7090:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7091:     my @options = ('approval','validate','autolimit');
                   7092:     my $optregex = join('|',@options);
                   7093:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7094:         foreach my $type (@{$types}) {
                   7095:             if (&usertools_access($env{'user.name'},
                   7096:                                   $env{'user.domain'},
                   7097:                                   $type,undef,'requestcourses')) {
                   7098:                 $canreq ++;
1.1036    raeburn  7099:                 if (ref($request_domains) eq 'HASH') {
                   7100:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7101:                 }
1.1035    raeburn  7102:                 if ($dom eq $env{'user.domain'}) {
                   7103:                     $can_request->{$type} = 1;
                   7104:                 }
                   7105:             }
                   7106:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7107:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7108:                 if (@curr > 0) {
1.1036    raeburn  7109:                     foreach my $item (@curr) {
                   7110:                         if (ref($request_domains) eq 'HASH') {
                   7111:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7112:                             if ($otherdom ne '') {
                   7113:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7114:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7115:                                         push(@{$request_domains->{$type}},$otherdom);
                   7116:                                     }
                   7117:                                 } else {
                   7118:                                     push(@{$request_domains->{$type}},$otherdom);
                   7119:                                 }
                   7120:                             }
                   7121:                         }
                   7122:                     }
                   7123:                     unless($dom eq $env{'user.domain'}) {
                   7124:                         $canreq ++;
1.1035    raeburn  7125:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7126:                             $can_request->{$type} = 1;
                   7127:                         }
                   7128:                     }
                   7129:                 }
                   7130:             }
                   7131:         }
                   7132:     }
                   7133:     return $canreq;
                   7134: }
                   7135: 
1.341     www      7136: # ---------------------------------------------- Custom access rule evaluation
                   7137: 
                   7138: sub customaccess {
                   7139:     my ($priv,$uri)=@_;
1.807     albertel 7140:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7141:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7142:     $udom = &LONCAPA::clean_domain($udom);
                   7143:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7144:     my $access=0;
1.800     albertel 7145:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7146: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7147: 	if ($type eq 'user') {
                   7148: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7149: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7150: 		if ($tdom) {
                   7151: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7152: 		}
1.896     albertel 7153: 		if ($tuname) {
                   7154: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7155: 		}
                   7156: 		$access=($effect eq 'allow');
                   7157: 		last;
                   7158: 	    }
                   7159: 	} else {
                   7160: 	    if ($role) {
                   7161: 		if ($role ne $urole) { next; }
                   7162: 	    }
                   7163: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7164: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7165: 		if ($tdom) {
                   7166: 		    if ($tdom ne $udom) { next; }
                   7167: 		}
                   7168: 		if ($tcrs) {
                   7169: 		    if ($tcrs ne $ucrs) { next; }
                   7170: 		}
                   7171: 		if ($tsec) {
                   7172: 		    if ($tsec ne $usec) { next; }
                   7173: 		}
                   7174: 		$access=($effect eq 'allow');
                   7175: 		last;
                   7176: 	    }
                   7177: 	    if ($realm eq '' && $role eq '') {
                   7178: 		$access=($effect eq 'allow');
                   7179: 	    }
1.402     bowersj2 7180: 	}
1.341     www      7181:     }
                   7182:     return $access;
                   7183: }
                   7184: 
1.103     harris41 7185: # ------------------------------------------------- Check for a user privilege
1.12      www      7186: 
                   7187: sub allowed {
1.1281    raeburn  7188:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7189:     my $ver_orguri=$uri;
1.439     www      7190:     $uri=&deversion($uri);
1.152     www      7191:     my $orguri=$uri;
1.52      www      7192:     $uri=&declutter($uri);
1.809     raeburn  7193: 
1.810     raeburn  7194:     if ($priv eq 'evb') {
                   7195: # Evade communication block restrictions for specified role in a course
                   7196:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7197:             return $1;
                   7198:         } else {
                   7199:             return;
                   7200:         }
                   7201:     }
                   7202: 
1.620     albertel 7203:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7204: # Free bre access to adm and meta resources
1.775     albertel 7205:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 7206: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7207: 	&& ($priv eq 'bre')) {
1.14      www      7208: 	return 'F';
1.159     www      7209:     }
                   7210: 
1.545     banghart 7211: # Free bre access to user's own portfolio contents
1.714     raeburn  7212:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7213:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7214: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7215:         my %setters;
                   7216:         my ($startblock,$endblock) = 
                   7217:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7218:         if ($startblock && $endblock) {
                   7219:             return 'B';
                   7220:         } else {
                   7221:             return 'F';
                   7222:         }
1.545     banghart 7223:     }
                   7224: 
1.762     raeburn  7225: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7226:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7227:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7228:         if (exists($env{'request.course.id'})) {
                   7229:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7230:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7231:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7232:                 my $courseprivid=$env{'request.course.id'};
                   7233:                 $courseprivid=~s/\_/\//;
                   7234:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7235:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7236:                     return $1; 
1.762     raeburn  7237:                 } else {
                   7238:                     if ($env{'request.course.sec'}) {
                   7239:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7240:                     }
                   7241:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7242:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7243:                         return $2;
                   7244:                     }
1.714     raeburn  7245:                 }
                   7246:             }
                   7247:         }
                   7248:     }
                   7249: 
1.159     www      7250: # Free bre to public access
                   7251: 
                   7252:     if ($priv eq 'bre') {
1.238     www      7253:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7254: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7255:            return 'F'; 
                   7256:         }
1.238     www      7257:         if ($copyright eq 'priv') {
                   7258:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7259: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7260: 		return '';
                   7261:             }
                   7262:         }
                   7263:         if ($copyright eq 'domain') {
                   7264:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7265: 	    unless (($env{'user.domain'} eq $1) ||
                   7266:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7267: 		return '';
                   7268:             }
1.262     matthew  7269:         }
1.620     albertel 7270:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7271:             # Library role, so allow browsing of resources in this domain.
                   7272:             return 'F';
1.238     www      7273:         }
1.341     www      7274:         if ($copyright eq 'custom') {
                   7275: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7276:         }
1.14      www      7277:     }
1.264     matthew  7278:     # Domain coordinator is trying to create a course
1.620     albertel 7279:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7280:         # uri is the requested domain in this case.
                   7281:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7282:         # a role of dc for the domain in question.
1.620     albertel 7283:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7284:     }
1.29      www      7285: 
1.52      www      7286:     my $thisallowed='';
                   7287:     my $statecond=0;
                   7288:     my $courseprivid='';
                   7289: 
1.1039    raeburn  7290:     my $ownaccess;
1.1043    raeburn  7291:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7292:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7293:         if ($uri eq '') {
                   7294:             $ownaccess = 1;
                   7295:         } else {
                   7296:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7297:                 my $udom = $env{'user.domain'};
                   7298:                 my $uname = $env{'user.name'};
                   7299:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7300:                     $ownaccess = 1;
1.1040    raeburn  7301:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7302:                     unless ($uri =~ m{\.\./}) {
                   7303:                         $ownaccess = 1;
                   7304:                     }
                   7305:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7306:                     my $now = time;
                   7307:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7308:                         my $adom = $1;
                   7309:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7310:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7311:                                 my ($start,$end) = split('.',$env{$key});
                   7312:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7313:                                     $ownaccess = 1;
                   7314:                                     last;
                   7315:                                 }
                   7316:                             }
                   7317:                         }
                   7318:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7319:                         my $adom = $1;
                   7320:                         my $aname = $2;
1.1042    raeburn  7321:                         foreach my $role ('ca','aa') { 
                   7322:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7323:                                 my ($start,$end) =
                   7324:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7325:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7326:                                     $ownaccess = 1;
                   7327:                                     last;
                   7328:                                 }
1.1039    raeburn  7329:                             }
                   7330:                         }
                   7331:                     }
                   7332:                 }
                   7333:             }
                   7334:         }
                   7335:     }
                   7336: 
1.52      www      7337: # Course
                   7338: 
1.620     albertel 7339:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7340:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7341:             $thisallowed.=$1;
                   7342:         }
1.52      www      7343:     }
1.29      www      7344: 
1.52      www      7345: # Domain
                   7346: 
1.620     albertel 7347:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7348:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7349:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7350:             $thisallowed.=$1;
                   7351:         }
1.12      www      7352:     }
1.52      www      7353: 
1.1141    raeburn  7354: # User who is not author or co-author might still be able to edit
                   7355: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7356:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7357:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7358:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7359:             $thisallowed.=$1;
                   7360:         }
                   7361:     }
                   7362: 
1.52      www      7363: # Course: uri itself is a course
1.66      www      7364:     my $courseuri=$uri;
                   7365:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7366:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7367: 
1.620     albertel 7368:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7369:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7370:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7371:             $thisallowed.=$1;
                   7372:         }
1.12      www      7373:     }
1.29      www      7374: 
1.665     albertel 7375: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7376: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7377:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7378: 	$thisallowed='';
1.671     raeburn  7379:         my ($match)=&is_on_map($uri);
                   7380:         if ($match) {
                   7381:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7382:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  7383:                 my $value = $1;
                   7384:                 if ($noblockcheck) {
                   7385:                     $thisallowed.=$value;
1.1162    raeburn  7386:                 } else {
1.1281    raeburn  7387:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7388:                     if (@blockers > 0) {
                   7389:                         $thisallowed = 'B';
                   7390:                     } else {
                   7391:                         $thisallowed.=$value;
                   7392:                     }
1.1162    raeburn  7393:                 }
1.671     raeburn  7394:             }
                   7395:         } else {
1.705     albertel 7396:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7397:             if ($refuri) {
                   7398:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7399:                     $thisallowed='F';
1.671     raeburn  7400:                 } else {
                   7401:                     $refuri=&declutter($refuri);
                   7402:                     my ($match) = &is_on_map($refuri);
                   7403:                     if ($match) {
1.1281    raeburn  7404:                         if ($noblockcheck) {
                   7405:                             $thisallowed='F';
1.1162    raeburn  7406:                         } else {
1.1281    raeburn  7407:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7408:                             if (@blockers > 0) {
                   7409:                                 $thisallowed = 'B';
                   7410:                             } else {
                   7411:                                 $thisallowed='F';
                   7412:                             }
1.1162    raeburn  7413:                         }
1.671     raeburn  7414:                     }
1.669     raeburn  7415:                 }
1.671     raeburn  7416:             }
                   7417:         }
1.314     www      7418:     }
1.492     albertel 7419: 
1.766     albertel 7420:     if ($priv eq 'bre'
                   7421: 	&& $thisallowed ne 'F' 
                   7422: 	&& $thisallowed ne '2'
                   7423: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  7424: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7425:     }
1.1250    raeburn  7426: 
1.52      www      7427: # Full access at system, domain or course-wide level? Exit.
1.29      www      7428:     if ($thisallowed=~/F/) {
                   7429: 	return 'F';
                   7430:     }
                   7431: 
1.52      www      7432: # If this is generating or modifying users, exit with special codes
1.29      www      7433: 
1.643     www      7434:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7435: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7436: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7437: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7438: 	    unless ($auname) { return $thisallowed; }
                   7439: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7440: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7441: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7442: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7443: 	}
1.52      www      7444: 	return $thisallowed;
                   7445:     }
                   7446: #
1.103     harris41 7447: # Gathered so far: system, domain and course wide privileges
1.52      www      7448: #
                   7449: # Course: See if uri or referer is an individual resource that is part of 
                   7450: # the course
                   7451: 
1.620     albertel 7452:     if ($env{'request.course.id'}) {
1.232     www      7453: 
1.620     albertel 7454:        $courseprivid=$env{'request.course.id'};
                   7455:        if ($env{'request.course.sec'}) {
                   7456:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7457:        }
                   7458:        $courseprivid=~s/\_/\//;
                   7459:        my $checkreferer=1;
1.232     www      7460:        my ($match,$cond)=&is_on_map($uri);
                   7461:        if ($match) {
                   7462:            $statecond=$cond;
1.620     albertel 7463:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7464:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7465:                my $value = $1;
                   7466:                if ($priv eq 'bre') {
1.1281    raeburn  7467:                    if ($noblockcheck) {
                   7468:                        $thisallowed.=$value;
1.1162    raeburn  7469:                    } else {
1.1281    raeburn  7470:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7471:                        if (@blockers > 0) {
                   7472:                            $thisallowed = 'B';
                   7473:                        } else {
                   7474:                            $thisallowed.=$value;
                   7475:                        }
1.1162    raeburn  7476:                    }
                   7477:                } else {
                   7478:                    $thisallowed.=$value;
                   7479:                }
1.52      www      7480:                $checkreferer=0;
                   7481:            }
1.29      www      7482:        }
1.83      www      7483:        
1.148     www      7484:        if ($checkreferer) {
1.620     albertel 7485: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7486:             unless ($refuri) {
1.800     albertel 7487:                 foreach my $key (keys(%env)) {
                   7488: 		    if ($key=~/^httpref\..*\*/) {
                   7489: 			my $pattern=$key;
1.156     www      7490:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7491:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7492:                         $pattern=~s/\//\\\//g;
1.152     www      7493:                         if ($orguri=~/$pattern/) {
1.800     albertel 7494: 			    $refuri=$env{$key};
1.148     www      7495:                         }
                   7496:                     }
1.191     harris41 7497:                 }
1.148     www      7498:             }
1.232     www      7499: 
1.148     www      7500:          if ($refuri) { 
1.152     www      7501: 	  $refuri=&declutter($refuri);
1.232     www      7502:           my ($match,$cond)=&is_on_map($refuri);
                   7503:             if ($match) {
                   7504:               my $refstatecond=$cond;
1.620     albertel 7505:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7506:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7507:                   my $value = $1;
                   7508:                   if ($priv eq 'bre') {
1.1281    raeburn  7509:                       if ($noblockcheck) {
                   7510:                           $thisallowed.=$value;
1.1162    raeburn  7511:                       } else {
1.1281    raeburn  7512:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7513:                           if (@blockers > 0) {
                   7514:                               $thisallowed = 'B';
                   7515:                           } else {
                   7516:                               $thisallowed.=$value;
                   7517:                           }
1.1162    raeburn  7518:                       }
                   7519:                   } else {
                   7520:                       $thisallowed.=$value;
                   7521:                   }
1.53      www      7522:                   $uri=$refuri;
                   7523:                   $statecond=$refstatecond;
1.52      www      7524:               }
                   7525:           }
1.148     www      7526:         }
1.29      www      7527:        }
1.52      www      7528:    }
1.29      www      7529: 
1.52      www      7530: #
1.103     harris41 7531: # Gathered now: all privileges that could apply, and condition number
1.52      www      7532: # 
                   7533: #
                   7534: # Full or no access?
                   7535: #
1.29      www      7536: 
1.52      www      7537:     if ($thisallowed=~/F/) {
                   7538: 	return 'F';
                   7539:     }
1.29      www      7540: 
1.52      www      7541:     unless ($thisallowed) {
                   7542:         return '';
                   7543:     }
1.29      www      7544: 
1.52      www      7545: # Restrictions exist, deal with them
                   7546: #
                   7547: #   C:according to course preferences
                   7548: #   R:according to resource settings
                   7549: #   L:unless locked
                   7550: #   X:according to user session state
                   7551: #
                   7552: 
                   7553: # Possibly locked functionality, check all courses
1.54      www      7554: # Locks might take effect only after 10 minutes cache expiration for other
                   7555: # courses, and 2 minutes for current course
1.52      www      7556: 
                   7557:     my $envkey;
                   7558:     if ($thisallowed=~/L/) {
1.1000    raeburn  7559:         foreach $envkey (keys(%env)) {
1.54      www      7560:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7561:                my $courseid=$2;
                   7562:                my $roleid=$1.'.'.$2;
1.92      www      7563:                $courseid=~s/^\///;
1.54      www      7564:                my $expiretime=600;
1.620     albertel 7565:                if ($env{'request.role'} eq $roleid) {
1.54      www      7566: 		  $expiretime=120;
                   7567:                }
                   7568: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7569:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7570:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7571: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7572:                }
1.620     albertel 7573:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7574:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7575: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7576:                        &log($env{'user.domain'},$env{'user.name'},
                   7577:                             $env{'user.home'},
1.57      www      7578:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7579:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7580:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7581: 		       return '';
                   7582:                    }
                   7583:                }
1.620     albertel 7584:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7585:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7586: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7587:                        &log($env{'user.domain'},$env{'user.name'},
                   7588:                             $env{'user.home'},
1.57      www      7589:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7590:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7591:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7592: 		       return '';
                   7593:                    }
                   7594:                }
                   7595: 	   }
1.29      www      7596:        }
1.52      www      7597:     }
                   7598:    
                   7599: #
                   7600: # Rest of the restrictions depend on selected course
                   7601: #
                   7602: 
1.620     albertel 7603:     unless ($env{'request.course.id'}) {
1.766     albertel 7604: 	if ($thisallowed eq 'A') {
                   7605: 	    return 'A';
1.814     raeburn  7606:         } elsif ($thisallowed eq 'B') {
                   7607:             return 'B';
1.766     albertel 7608: 	} else {
                   7609: 	    return '1';
                   7610: 	}
1.52      www      7611:     }
1.29      www      7612: 
1.52      www      7613: #
                   7614: # Now user is definitely in a course
                   7615: #
1.53      www      7616: 
                   7617: 
                   7618: # Course preferences
                   7619: 
                   7620:    if ($thisallowed=~/C/) {
1.620     albertel 7621:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7622:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7623:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7624: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  7625: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 7626: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7627: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7628: 			$env{'request.course.id'});
                   7629: 	   }
1.237     www      7630:            return '';
                   7631:        }
                   7632: 
1.620     albertel 7633:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7634: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  7635: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 7636: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7637: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7638: 			$env{'request.course.id'});
                   7639: 	   }
1.54      www      7640:            return '';
                   7641:        }
1.53      www      7642:    }
                   7643: 
                   7644: # Resource preferences
                   7645: 
                   7646:    if ($thisallowed=~/R/) {
1.620     albertel 7647:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7648:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7649: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7650: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7651: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7652: 	   }
                   7653: 	   return '';
1.54      www      7654:        }
1.53      www      7655:    }
1.30      www      7656: 
1.246     www      7657: # Restricted by state or randomout?
1.30      www      7658: 
1.52      www      7659:    if ($thisallowed=~/X/) {
1.620     albertel 7660:       if ($env{'acc.randomout'}) {
1.579     albertel 7661: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7662:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7663:             return ''; 
                   7664:          }
1.247     www      7665:       }
                   7666:       if (&condval($statecond)) {
1.52      www      7667: 	 return '2';
                   7668:       } else {
                   7669:          return '';
                   7670:       }
                   7671:    }
1.30      www      7672: 
1.766     albertel 7673:     if ($thisallowed eq 'A') {
                   7674: 	return 'A';
1.814     raeburn  7675:     } elsif ($thisallowed eq 'B') {
                   7676:         return 'B';
1.766     albertel 7677:     }
1.52      www      7678:    return 'F';
1.232     www      7679: }
1.1162    raeburn  7680: 
1.1192    raeburn  7681: # ------------------------------------------- Check construction space access
                   7682: 
                   7683: sub constructaccess {
                   7684:     my ($url,$setpriv)=@_;
                   7685: 
                   7686: # We do not allow editing of previous versions of files
                   7687:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7688: 
                   7689: # Get username and domain from URL
                   7690:     my ($ownername,$ownerdomain,$ownerhome);
                   7691: 
                   7692:     ($ownerdomain,$ownername) =
1.1325    raeburn  7693:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192    raeburn  7694: 
                   7695: # The URL does not really point to any authorspace, forget it
                   7696:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7697: 
                   7698: # Now we need to see if the user has access to the authorspace of
                   7699: # $ownername at $ownerdomain
                   7700: 
                   7701:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7702: # Real author for this?
                   7703:        $ownerhome = $env{'user.home'};
                   7704:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7705:           return ($ownername,$ownerdomain,$ownerhome);
                   7706:        }
                   7707:     } else {
                   7708: # Co-author for this?
                   7709:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7710:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7711:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7712:             return ($ownername,$ownerdomain,$ownerhome);
                   7713:         }
1.1312    raeburn  7714:         if ($env{'request.course.id'}) {
                   7715:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
                   7716:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
                   7717:                 if (&allowed('mdc',$env{'request.course.id'})) {
                   7718:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   7719:                     return ($ownername,$ownerdomain,$ownerhome);
                   7720:                 }
                   7721:             }
                   7722:         }
1.1192    raeburn  7723:     }
                   7724: 
                   7725: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7726: # we might as well leave
                   7727:    unless ($setpriv) { return ''; }
                   7728: 
                   7729: # Backdoor access?
                   7730:     my $allowed=&allowed('eco',$ownerdomain);
                   7731: # Nope
                   7732:     unless ($allowed) { return ''; }
                   7733: # Looks like we may have access, but could be locked by the owner of the construction space
                   7734:     if ($allowed eq 'U') {
                   7735:         my %blocked=&get('environment',['domcoord.author'],
                   7736:                          $ownerdomain,$ownername);
                   7737: # Is blocked by owner
                   7738:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7739:     }
                   7740:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7741: # Grant temporary access
                   7742:         my $then=$env{'user.login.time'};
1.1209    raeburn  7743:         my $update=$env{'user.update.time'};
1.1192    raeburn  7744:         if (!$update) { $update = $then; }
                   7745:         my $refresh=$env{'user.refresh.time'};
                   7746:         if (!$refresh) { $refresh = $update; }
                   7747:         my $now = time;
                   7748:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7749:                            $now,'ca','constructaccess');
                   7750:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7751:         return($ownername,$ownerdomain,$ownerhome);
                   7752:     }
                   7753: # No business here
                   7754:     return '';
                   7755: }
                   7756: 
1.1282    raeburn  7757: # ----------------------------------------------------------- Content Blocking
                   7758: 
                   7759: {
                   7760: # Caches for faster Course Contents display where content blocking
                   7761: # is in operation (i.e., interval param set) for timed quiz.
                   7762: #
                   7763: # User for whom data are being temporarily cached.
                   7764: my $cacheduser='';
                   7765: # Cached blockers for this user (a hash of blocking items). 
                   7766: my %cachedblockers=();
                   7767: # When the data were last cached.
                   7768: my $cachedlast='';
                   7769: 
                   7770: sub load_all_blockers {
                   7771:     my ($uname,$udom,$blocks)=@_;
                   7772:     if (($uname ne '') && ($udom ne '')) { 
                   7773:         if (($cacheduser eq $uname.':'.$udom) &&
                   7774:             (abs($cachedlast-time)<5)) {
                   7775:             return;
                   7776:         }
                   7777:     }
                   7778:     $cachedlast=time;
                   7779:     $cacheduser=$uname.':'.$udom;
                   7780:     %cachedblockers = &get_commblock_resources($blocks);
                   7781: }
                   7782: 
1.1162    raeburn  7783: sub get_comm_blocks {
                   7784:     my ($cdom,$cnum) = @_;
                   7785:     if ($cdom eq '' || $cnum eq '') {
                   7786:         return unless ($env{'request.course.id'});
                   7787:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7788:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7789:     }
                   7790:     my %commblocks;
                   7791:     my $hashid=$cdom.'_'.$cnum;
                   7792:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7793:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7794:         %commblocks = %{$blocksref};
                   7795:     } else {
                   7796:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7797:         my $cachetime = 600;
                   7798:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7799:     }
                   7800:     return %commblocks;
                   7801: }
                   7802: 
1.1282    raeburn  7803: sub get_commblock_resources {
                   7804:     my ($blocks) = @_;
                   7805:     my %blockers = ();
                   7806:     return %blockers unless ($env{'request.course.id'});
                   7807:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  7808:     my %commblocks;
                   7809:     if (ref($blocks) eq 'HASH') {
                   7810:         %commblocks = %{$blocks};
                   7811:     } else {
                   7812:         %commblocks = &get_comm_blocks();
                   7813:     }
1.1282    raeburn  7814:     return %blockers unless (keys(%commblocks) > 0); 
                   7815:     my $navmap = Apache::lonnavmaps::navmap->new();
                   7816:     return %blockers unless (ref($navmap));
1.1162    raeburn  7817:     my $now = time;
                   7818:     foreach my $block (keys(%commblocks)) {
                   7819:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7820:             my ($start,$end) = ($1,$2);
                   7821:             if ($start <= $now && $end >= $now) {
                   7822:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7823:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7824:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  7825:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7826:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  7827:                             }
                   7828:                         }
                   7829:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  7830:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7831:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  7832:                             }
                   7833:                         }
                   7834:                     }
                   7835:                 }
                   7836:             }
                   7837:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7838:             my $item = $1;
1.1163    raeburn  7839:             my @to_test;
1.1162    raeburn  7840:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7841:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282    raeburn  7842:                     my @interval;
                   7843:                     my $type = 'map';
                   7844:                     if ($item eq 'course') {
                   7845:                         $type = 'course';
                   7846:                         @interval=&EXT("resource.0.interval");
                   7847:                     } else {
                   7848:                         if ($item =~ /___\d+___/) {
                   7849:                             $type = 'resource';
                   7850:                             @interval=&EXT("resource.0.interval",$item);
                   7851:                             if (ref($navmap)) {                        
                   7852:                                 my $res = $navmap->getBySymb($item); 
                   7853:                                 push(@to_test,$res);
                   7854:                             }
1.1162    raeburn  7855:                         } else {
1.1282    raeburn  7856:                             my $mapsymb = &symbread($item,1);
                   7857:                             if ($mapsymb) {
                   7858:                                 if (ref($navmap)) {
                   7859:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   7860:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   7861:                                     foreach my $res (@to_test) {
                   7862:                                         my $symb = $res->symb();
                   7863:                                         next if ($symb eq $mapsymb);
                   7864:                                         if ($symb ne '') {
                   7865:                                             @interval=&EXT("resource.0.interval",$symb);
                   7866:                                             if ($interval[1] eq 'map') {
                   7867:                                                 last;
1.1162    raeburn  7868:                                             }
                   7869:                                         }
                   7870:                                     }
                   7871:                                 }
                   7872:                             }
                   7873:                         }
1.1282    raeburn  7874:                     }
1.1310    raeburn  7875:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  7876:                         my $timelimit = $1; 
1.1282    raeburn  7877:                         my $first_access;
                   7878:                         if ($type eq 'resource') {
                   7879:                             $first_access=&get_first_access($interval[1],$item);
                   7880:                         } elsif ($type eq 'map') {
                   7881:                             $first_access=&get_first_access($interval[1],undef,$item);
                   7882:                         } else {
                   7883:                             $first_access=&get_first_access($interval[1]);
                   7884:                         }
                   7885:                         if ($first_access) {
1.1292    raeburn  7886:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  7887:                             if ($timesup > $now) {
                   7888:                                 my $activeblock;
                   7889:                                 foreach my $res (@to_test) {
1.1283    raeburn  7890:                                     if ($res->answerable()) {
1.1282    raeburn  7891:                                         $activeblock = 1;
                   7892:                                         last;
                   7893:                                     }
                   7894:                                 }
                   7895:                                 if ($activeblock) {
                   7896:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7897:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7898:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   7899:                                          }
                   7900:                                     }
                   7901:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7902:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7903:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  7904:                                         }
1.1162    raeburn  7905:                                     }
                   7906:                                 }
                   7907:                             }
                   7908:                         }
                   7909:                     }
                   7910:                 }
                   7911:             }
                   7912:         }
                   7913:     }
1.1282    raeburn  7914:     return %blockers;
1.1162    raeburn  7915: }
                   7916: 
1.1282    raeburn  7917: sub has_comm_blocking {
                   7918:     my ($priv,$symb,$uri,$blocks) = @_;
                   7919:     my @blockers;
                   7920:     return unless ($env{'request.course.id'});
                   7921:     return unless ($priv eq 'bre');
                   7922:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7923:     return if ($env{'request.state'} eq 'construct');
                   7924:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   7925:     return unless (keys(%cachedblockers) > 0);
                   7926:     my (%possibles,@symbs);
                   7927:     if (!$symb) {
                   7928:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  7929:     }
1.1282    raeburn  7930:     if ($symb) {
                   7931:         @symbs = ($symb);
                   7932:     } elsif (keys(%possibles)) { 
                   7933:         @symbs = keys(%possibles);
                   7934:     }
                   7935:     my $noblock;
                   7936:     foreach my $symb (@symbs) {
                   7937:         last if ($noblock);
                   7938:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   7939:         foreach my $block (keys(%cachedblockers)) {
                   7940:             if ($block =~ /^firstaccess____(.+)$/) {
                   7941:                 my $item = $1;
                   7942:                 if (($item eq $map) || ($item eq $symb)) {
                   7943:                     $noblock = 1;
                   7944:                     last;
                   7945:                 }
                   7946:             }
                   7947:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   7948:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   7949:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   7950:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   7951:                             push(@blockers,$block);
                   7952:                         }
                   7953:                     }
                   7954:                 }
1.1162    raeburn  7955:             }
1.1282    raeburn  7956:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   7957:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   7958:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   7959:                         push(@blockers,$block);
                   7960:                     }
                   7961:                 }
1.1162    raeburn  7962:             }
                   7963:         }
                   7964:     }
1.1282    raeburn  7965:     return if ($noblock);
                   7966:     return @blockers;
                   7967: }
1.1162    raeburn  7968: }
                   7969: 
1.1282    raeburn  7970: # -------------------------------- Deversion and split uri into path an filename   
                   7971: 
1.1133    foxr     7972: #
1.1282    raeburn  7973: #   Removes the version from a URI and
1.1133    foxr     7974: #   splits it in to its filename and path to the filename.
                   7975: #   Seems like File::Basename could have done this more clearly.
                   7976: #   Parameters:
                   7977: #      $uri   - input URI
                   7978: #   Returns:
                   7979: #     Two element list consisting of 
                   7980: #     $pathname  - the URI up to and excluding the trailing /
                   7981: #     $filename  - The part of the URI following the last /
                   7982: #  NOTE:
                   7983: #    Another realization of this is simply:
                   7984: #    use File::Basename;
                   7985: #    ...
                   7986: #    $uri = shift;
                   7987: #    $filename = basename($uri);
                   7988: #    $path     = dirname($uri);
                   7989: #    return ($filename, $path);
                   7990: #
                   7991: #     The implementation below is probably faster however.
                   7992: #
1.710     albertel 7993: sub split_uri_for_cond {
                   7994:     my $uri=&deversion(&declutter(shift));
                   7995:     my @uriparts=split(/\//,$uri);
                   7996:     my $filename=pop(@uriparts);
                   7997:     my $pathname=join('/',@uriparts);
                   7998:     return ($pathname,$filename);
                   7999: }
1.232     www      8000: # --------------------------------------------------- Is a resource on the map?
                   8001: 
                   8002: sub is_on_map {
1.710     albertel 8003:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8004:     #Trying to find the conditional for the file
1.620     albertel 8005:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8006: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8007:     if ($match) {
1.289     bowersj2 8008: 	return (1,$1);
                   8009:     } else {
1.434     www      8010: 	return (0,0);
1.289     bowersj2 8011:     }
1.12      www      8012: }
                   8013: 
1.427     www      8014: # --------------------------------------------------------- Get symb from alias
                   8015: 
                   8016: sub get_symb_from_alias {
                   8017:     my $symb=shift;
                   8018:     my ($map,$resid,$url)=&decode_symb($symb);
                   8019: # Already is a symb
                   8020:     if ($url) { return $symb; }
                   8021: # Must be an alias
                   8022:     my $aliassymb='';
                   8023:     my %bighash;
1.620     albertel 8024:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8025:                             &GDBM_READER(),0640)) {
                   8026:         my $rid=$bighash{'mapalias_'.$symb};
                   8027: 	if ($rid) {
                   8028: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8029: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8030: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8031: 	}
                   8032:         untie %bighash;
                   8033:     }
                   8034:     return $aliassymb;
                   8035: }
                   8036: 
1.12      www      8037: # ----------------------------------------------------------------- Define Role
                   8038: 
                   8039: sub definerole {
                   8040:   if (allowed('mcr','/')) {
1.1326    raeburn  8041:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8042:     foreach my $role (split(':',$sysrole)) {
                   8043: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8044:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8045:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8046: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8047:                return "refused:s:$crole&$cqual"; 
                   8048:             }
                   8049:         }
1.191     harris41 8050:     }
1.800     albertel 8051:     foreach my $role (split(':',$domrole)) {
                   8052: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8053:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8054:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8055: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8056:                return "refused:d:$crole&$cqual"; 
                   8057:             }
                   8058:         }
1.191     harris41 8059:     }
1.800     albertel 8060:     foreach my $role (split(':',$courole)) {
                   8061: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8062:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8063:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8064: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8065:                return "refused:c:$crole&$cqual"; 
                   8066:             }
                   8067:         }
1.191     harris41 8068:     }
1.1326    raeburn  8069:     my $uhome;
                   8070:     if (($uname ne '') && ($udom ne '')) {
                   8071:         $uhome = &homeserver($uname,$udom);
                   8072:         return $uhome if ($uhome eq 'no_host');
                   8073:     } else {
                   8074:         $uname = $env{'user.name'};
                   8075:         $udom = $env{'user.domain'};
                   8076:         $uhome = $env{'user.home'};
                   8077:     }
1.620     albertel 8078:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326    raeburn  8079:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8080:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326    raeburn  8081:     return reply($command,$uhome);
1.12      www      8082:   } else {
                   8083:     return 'refused';
                   8084:   }
1.105     harris41 8085: }
                   8086: 
                   8087: # ---------------- Make a metadata query against the network of library servers
                   8088: 
                   8089: sub metadata_query {
1.1237    raeburn  8090:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8091:     my %rhash;
1.845     albertel 8092:     my %libserv = &all_library();
1.244     matthew  8093:     my @server_list = (defined($server_array) ? @$server_array
                   8094:                                               : keys(%libserv) );
                   8095:     for my $server (@server_list) {
1.1237    raeburn  8096:         my $domains = ''; 
                   8097:         if (ref($domains_hash) eq 'HASH') {
                   8098:             $domains = $domains_hash->{$server}; 
                   8099:         }
1.118     harris41 8100: 	unless ($custom or $customshow) {
1.1237    raeburn  8101: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8102: 	    $rhash{$server}=$reply;
                   8103: 	}
                   8104: 	else {
                   8105: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  8106: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8107: 			     $server);
                   8108: 	    $rhash{$server}=$reply;
                   8109: 	}
1.112     harris41 8110:     }
1.118     harris41 8111:     return \%rhash;
1.240     www      8112: }
                   8113: 
                   8114: # ----------------------------------------- Send log queries and wait for reply
                   8115: 
                   8116: sub log_query {
                   8117:     my ($uname,$udom,$query,%filters)=@_;
                   8118:     my $uhome=&homeserver($uname,$udom);
                   8119:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8120:     my $uhost=&hostname($uhome);
1.800     albertel 8121:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8122:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8123:                        $uhome);
1.479     albertel 8124:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8125:     return get_query_reply($queryid);
                   8126: }
                   8127: 
1.818     raeburn  8128: # -------------------------- Update MySQL table for portfolio file
                   8129: 
                   8130: sub update_portfolio_table {
1.821     raeburn  8131:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8132:     if ($group ne '') {
                   8133:         $file_name =~s /^\Q$group\E//;
                   8134:     }
1.818     raeburn  8135:     my $homeserver = &homeserver($uname,$udom);
                   8136:     my $queryid=
1.821     raeburn  8137:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8138:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8139:     my $reply = &get_query_reply($queryid);
                   8140:     return $reply;
                   8141: }
                   8142: 
1.899     raeburn  8143: # -------------------------- Update MySQL allusers table
                   8144: 
                   8145: sub update_allusers_table {
                   8146:     my ($uname,$udom,$names) = @_;
                   8147:     my $homeserver = &homeserver($uname,$udom);
                   8148:     my $queryid=
                   8149:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8150:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8151:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8152:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8153:                'generation='.&escape($names->{'generation'}).'%%'.
                   8154:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8155:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8156:     return;
1.899     raeburn  8157: }
                   8158: 
1.508     raeburn  8159: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8160: 
                   8161: sub fetch_enrollment_query {
1.511     raeburn  8162:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317    raeburn  8163:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8164:     my $maxtries = 1;
1.508     raeburn  8165:     if ($context eq 'automated') {
                   8166:         $homeserver = $perlvar{'lonHostID'};
1.1317    raeburn  8167:         $sleep = 2;
                   8168:         $loopmax = 100;
1.547     raeburn  8169:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8170:     } else {
                   8171:         $homeserver = &homeserver($cnum,$dom);
                   8172:     }
1.838     albertel 8173:     my $host=&hostname($homeserver);
1.506     raeburn  8174:     my $cmd = '';
1.1000    raeburn  8175:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8176:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8177:     }
                   8178:     $cmd =~ s/%%$//;
                   8179:     $cmd = &escape($cmd);
                   8180:     my $query = 'fetchenrollment';
1.620     albertel 8181:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8182:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8183:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8184:         return 'error: '.$queryid;
                   8185:     }
1.1317    raeburn  8186:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8187:     my $tries = 1;
                   8188:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317    raeburn  8189:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8190:         $tries ++;
                   8191:     }
1.526     raeburn  8192:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8193:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8194:     } else {
1.901     albertel 8195:         my @responses = split(/:/,$reply);
1.1322    raeburn  8196:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8197:             foreach my $line (@responses) {
                   8198:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8199:                 $$replyref{$key} = $value;
                   8200:             }
                   8201:         } else {
1.1117    foxr     8202:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8203:             foreach my $line (@responses) {
                   8204:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8205:                 $$replyref{$key} = $value;
                   8206:                 if ($value > 0) {
1.800     albertel 8207:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8208:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8209:                         my $destname = $pathname.'/'.$filename;
                   8210:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8211:                         if ($xml_classlist =~ /^error/) {
                   8212:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8213:                         } else {
1.506     raeburn  8214:                             if ( open(FILE,">$destname") ) {
                   8215:                                 print FILE &unescape($xml_classlist);
                   8216:                                 close(FILE);
1.526     raeburn  8217:                             } else {
                   8218:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8219:                             }
                   8220:                         }
                   8221:                     }
                   8222:                 }
                   8223:             }
                   8224:         }
                   8225:         return 'ok';
                   8226:     }
                   8227:     return 'error';
                   8228: }
                   8229: 
1.242     www      8230: sub get_query_reply {
1.1317    raeburn  8231:     my ($queryid,$sleep,$loopmax) = @_;;
                   8232:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8233:         $sleep = 0.2;
                   8234:     }
                   8235:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8236:         $loopmax = 100;
                   8237:     }
1.1117    foxr     8238:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8239:     my $reply='';
1.1317    raeburn  8240:     for (1..$loopmax) {
                   8241: 	sleep($sleep);
1.240     www      8242:         if (-e $replyfile.'.end') {
1.448     albertel 8243: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 8244: 		$reply = join('',<$fh>);
                   8245: 		close($fh);
1.240     www      8246: 	   } else { return 'error: reply_file_error'; }
1.242     www      8247:            return &unescape($reply);
                   8248: 	}
1.240     www      8249:     }
1.242     www      8250:     return 'timeout:'.$queryid;
1.240     www      8251: }
                   8252: 
                   8253: sub courselog_query {
1.241     www      8254: #
                   8255: # possible filters:
                   8256: # url: url or symb
                   8257: # username
                   8258: # domain
                   8259: # action: view, submit, grade
                   8260: # start: timestamp
                   8261: # end: timestamp
                   8262: #
1.240     www      8263:     my (%filters)=@_;
1.620     albertel 8264:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8265:     if ($filters{'url'}) {
                   8266: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8267:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8268:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8269:     }
1.620     albertel 8270:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8271:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8272:     return &log_query($cname,$cdom,'courselog',%filters);
                   8273: }
                   8274: 
                   8275: sub userlog_query {
1.858     raeburn  8276: #
                   8277: # possible filters:
                   8278: # action: log check role
                   8279: # start: timestamp
                   8280: # end: timestamp
                   8281: #
1.240     www      8282:     my ($uname,$udom,%filters)=@_;
                   8283:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8284: }
                   8285: 
1.506     raeburn  8286: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8287: 
                   8288: sub auto_run {
1.508     raeburn  8289:     my ($cnum,$cdom) = @_;
1.876     raeburn  8290:     my $response = 0;
                   8291:     my $settings;
                   8292:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8293:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8294:         $settings = $domconfig{'autoenroll'};
                   8295:         if ($settings->{'run'} eq '1') {
                   8296:             $response = 1;
                   8297:         }
                   8298:     } else {
1.934     raeburn  8299:         my $homeserver;
                   8300:         if (&is_course($cdom,$cnum)) {
                   8301:             $homeserver = &homeserver($cnum,$cdom);
                   8302:         } else {
                   8303:             $homeserver = &domain($cdom,'primary');
                   8304:         }
                   8305:         if ($homeserver ne 'no_host') {
                   8306:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8307:         }
1.876     raeburn  8308:     }
1.506     raeburn  8309:     return $response;
                   8310: }
1.776     albertel 8311: 
1.506     raeburn  8312: sub auto_get_sections {
1.508     raeburn  8313:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8314:     my $homeserver;
                   8315:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8316:         $homeserver = &homeserver($cnum,$cdom);
                   8317:     }
                   8318:     if (!defined($homeserver)) { 
                   8319:         if ($cdom =~ /^$match_domain$/) {
                   8320:             $homeserver = &domain($cdom,'primary');
                   8321:         }
                   8322:     }
                   8323:     my @secs;
                   8324:     if (defined($homeserver)) {
                   8325:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8326:         unless ($response eq 'refused') {
                   8327:             @secs = split(/:/,$response);
                   8328:         }
1.506     raeburn  8329:     }
                   8330:     return @secs;
                   8331: }
1.776     albertel 8332: 
1.506     raeburn  8333: sub auto_new_course {
1.1099    raeburn  8334:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8335:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8336:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8337:     return $response;
                   8338: }
1.776     albertel 8339: 
1.506     raeburn  8340: sub auto_validate_courseID {
1.508     raeburn  8341:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8342:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8343:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8344:     return $response;
                   8345: }
1.776     albertel 8346: 
1.1007    raeburn  8347: sub auto_validate_instcode {
1.1020    raeburn  8348:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8349:     my ($homeserver,$response);
                   8350:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8351:         $homeserver = &homeserver($cnum,$cdom);
                   8352:     }
                   8353:     if (!defined($homeserver)) {
                   8354:         if ($cdom =~ /^$match_domain$/) {
                   8355:             $homeserver = &domain($cdom,'primary');
                   8356:         }
                   8357:     }
1.1065    raeburn  8358:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8359:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  8360:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8361:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8362: }
                   8363: 
1.506     raeburn  8364: sub auto_create_password {
1.873     raeburn  8365:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8366:     my ($homeserver,$response);
1.506     raeburn  8367:     my $create_passwd = 0;
                   8368:     my $authchk = '';
1.873     raeburn  8369:     if ($udom =~ /^$match_domain$/) {
                   8370:         $homeserver = &domain($udom,'primary');
                   8371:     }
                   8372:     if ($homeserver eq '') {
                   8373:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8374:             $homeserver = &homeserver($cnum,$cdom);
                   8375:         }
                   8376:     }
                   8377:     if ($homeserver eq '') {
                   8378:         $authchk = 'nodomain';
1.506     raeburn  8379:     } else {
1.873     raeburn  8380:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8381:         if ($response eq 'refused') {
                   8382:             $authchk = 'refused';
                   8383:         } else {
1.901     albertel 8384:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8385:         }
1.506     raeburn  8386:     }
                   8387:     return ($authparam,$create_passwd,$authchk);
                   8388: }
                   8389: 
1.706     raeburn  8390: sub auto_photo_permission {
                   8391:     my ($cnum,$cdom,$students) = @_;
                   8392:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8393:     my ($outcome,$perm_reqd,$conditions) = 
                   8394: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8395:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8396: 	return (undef,undef);
                   8397:     }
1.706     raeburn  8398:     return ($outcome,$perm_reqd,$conditions);
                   8399: }
                   8400: 
                   8401: sub auto_checkphotos {
                   8402:     my ($uname,$udom,$pid) = @_;
                   8403:     my $homeserver = &homeserver($uname,$udom);
                   8404:     my ($result,$resulttype);
                   8405:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8406: 				   &escape($uname).':'.&escape($pid),
                   8407: 				   $homeserver));
1.709     albertel 8408:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8409: 	return (undef,undef);
                   8410:     }
1.706     raeburn  8411:     if ($outcome) {
                   8412:         ($result,$resulttype) = split(/:/,$outcome);
                   8413:     } 
                   8414:     return ($result,$resulttype);
                   8415: }
                   8416: 
                   8417: sub auto_photochoice {
                   8418:     my ($cnum,$cdom) = @_;
                   8419:     my $homeserver = &homeserver($cnum,$cdom);
                   8420:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8421: 						       &escape($cdom),
                   8422: 						       $homeserver)));
1.709     albertel 8423:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8424: 	return (undef,undef);
                   8425:     }
1.706     raeburn  8426:     return ($update,$comment);
                   8427: }
                   8428: 
                   8429: sub auto_photoupdate {
                   8430:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8431:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8432:     my $host=&hostname($homeserver);
1.706     raeburn  8433:     my $cmd = '';
                   8434:     my $maxtries = 1;
1.800     albertel 8435:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8436:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8437:     }
                   8438:     $cmd =~ s/%%$//;
                   8439:     $cmd = &escape($cmd);
                   8440:     my $query = 'institutionalphotos';
                   8441:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8442:     unless ($queryid=~/^\Q$host\E\_/) {
                   8443:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8444:         return 'error: '.$queryid;
                   8445:     }
                   8446:     my $reply = &get_query_reply($queryid);
                   8447:     my $tries = 1;
                   8448:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8449:         $reply = &get_query_reply($queryid);
                   8450:         $tries ++;
                   8451:     }
                   8452:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8453:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8454:     } else {
                   8455:         my @responses = split(/:/,$reply);
                   8456:         my $outcome = shift(@responses); 
                   8457:         foreach my $item (@responses) {
                   8458:             my ($key,$value) = split(/=/,$item);
                   8459:             $$photo{$key} = $value;
                   8460:         }
                   8461:         return $outcome;
                   8462:     }
                   8463:     return 'error';
                   8464: }
                   8465: 
1.521     raeburn  8466: sub auto_instcode_format {
1.793     albertel 8467:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8468: 	$cat_order) = @_;
1.521     raeburn  8469:     my $courses = '';
1.772     raeburn  8470:     my @homeservers;
1.521     raeburn  8471:     if ($caller eq 'global') {
1.841     albertel 8472: 	my %servers = &get_servers($codedom,'library');
                   8473: 	foreach my $tryserver (keys(%servers)) {
                   8474: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8475: 		push(@homeservers,$tryserver);
                   8476: 	    }
1.584     raeburn  8477:         }
1.1022    raeburn  8478:     } elsif ($caller eq 'requests') {
                   8479:         if ($codedom =~ /^$match_domain$/) {
                   8480:             my $chome = &domain($codedom,'primary');
                   8481:             unless ($chome eq 'no_host') {
                   8482:                 push(@homeservers,$chome);
                   8483:             }
                   8484:         }
1.521     raeburn  8485:     } else {
1.772     raeburn  8486:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8487:     }
1.793     albertel 8488:     foreach my $code (keys(%{$instcodes})) {
                   8489:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8490:     }
                   8491:     chop($courses);
1.772     raeburn  8492:     my $ok_response = 0;
                   8493:     my $response;
                   8494:     while (@homeservers > 0 && $ok_response == 0) {
                   8495:         my $server = shift(@homeservers); 
                   8496:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8497:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8498:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8499: 		split(/:/,$response);
1.772     raeburn  8500:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8501:             push(@{$codetitles},&str2array($codetitles_str));
                   8502:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8503:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8504:             $ok_response = 1;
                   8505:         }
                   8506:     }
                   8507:     if ($ok_response) {
1.521     raeburn  8508:         return 'ok';
1.772     raeburn  8509:     } else {
                   8510:         return $response;
1.521     raeburn  8511:     }
                   8512: }
                   8513: 
1.792     raeburn  8514: sub auto_instcode_defaults {
                   8515:     my ($domain,$returnhash,$code_order) = @_;
                   8516:     my @homeservers;
1.841     albertel 8517: 
                   8518:     my %servers = &get_servers($domain,'library');
                   8519:     foreach my $tryserver (keys(%servers)) {
                   8520: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8521: 	    push(@homeservers,$tryserver);
                   8522: 	}
1.792     raeburn  8523:     }
1.841     albertel 8524: 
1.792     raeburn  8525:     my $response;
1.841     albertel 8526:     foreach my $server (@homeservers) {
1.792     raeburn  8527:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8528:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8529: 	
                   8530: 	foreach my $pair (split(/\&/,$response)) {
                   8531: 	    my ($name,$value)=split(/\=/,$pair);
                   8532: 	    if ($name eq 'code_order') {
                   8533: 		@{$code_order} = split(/\&/,&unescape($value));
                   8534: 	    } else {
                   8535: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8536: 	    }
                   8537: 	}
                   8538: 	return 'ok';
1.792     raeburn  8539:     }
1.841     albertel 8540: 
                   8541:     return $response;
1.1003    raeburn  8542: }
                   8543: 
                   8544: sub auto_possible_instcodes {
1.1007    raeburn  8545:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8546:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8547:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8548:         return;
                   8549:     }
1.1003    raeburn  8550:     my (@homeservers,$uhome);
                   8551:     if (defined(&domain($domain,'primary'))) {
                   8552:         $uhome=&domain($domain,'primary');
                   8553:         push(@homeservers,&domain($domain,'primary'));
                   8554:     } else {
                   8555:         my %servers = &get_servers($domain,'library');
                   8556:         foreach my $tryserver (keys(%servers)) {
                   8557:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8558:                 push(@homeservers,$tryserver);
                   8559:             }
                   8560:         }
                   8561:     }
                   8562:     my $response;
                   8563:     foreach my $server (@homeservers) {
                   8564:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8565:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8566:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8567:             split(':',$response);
                   8568:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8569:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8570:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8571:             my ($name,$value)=split('=',$item);
                   8572:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8573:         }
                   8574:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8575:             my ($name,$value)=split('=',$item);
                   8576:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8577:         }
                   8578:         return 'ok';
                   8579:     }
                   8580:     return $response;
                   8581: }
1.792     raeburn  8582: 
1.1010    raeburn  8583: sub auto_courserequest_checks {
                   8584:     my ($dom) = @_;
1.1020    raeburn  8585:     my ($homeserver,%validations);
                   8586:     if ($dom =~ /^$match_domain$/) {
                   8587:         $homeserver = &domain($dom,'primary');
                   8588:     }
                   8589:     unless ($homeserver eq 'no_host') {
                   8590:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8591:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8592:             my @items = split(/&/,$response);
                   8593:             foreach my $item (@items) {
                   8594:                 my ($key,$value) = split('=',$item);
                   8595:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8596:             }
                   8597:         }
                   8598:     }
1.1010    raeburn  8599:     return %validations; 
                   8600: }
                   8601: 
1.1020    raeburn  8602: sub auto_courserequest_validation {
1.1255    raeburn  8603:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8604:     my ($homeserver,$response);
                   8605:     if ($dom =~ /^$match_domain$/) {
                   8606:         $homeserver = &domain($dom,'primary');
                   8607:     }
1.1255    raeburn  8608:     unless ($homeserver eq 'no_host') {
                   8609:         my $customdata;
                   8610:         if (ref($custominfo) eq 'HASH') {
                   8611:             $customdata = &freeze_escape($custominfo);
                   8612:         }
1.1020    raeburn  8613:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8614:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  8615:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8616:                                     $customdata,$homeserver));
1.1020    raeburn  8617:     }
                   8618:     return $response;
                   8619: }
                   8620: 
1.777     albertel 8621: sub auto_validate_class_sec {
1.918     raeburn  8622:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8623:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8624:     my $ownerlist;
                   8625:     if (ref($owners) eq 'ARRAY') {
                   8626:         $ownerlist = join(',',@{$owners});
                   8627:     } else {
                   8628:         $ownerlist = $owners;
                   8629:     }
1.773     raeburn  8630:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8631:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8632:     return $response;
                   8633: }
                   8634: 
1.1248    raeburn  8635: sub auto_crsreq_update {
                   8636:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  8637:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  8638:     my ($homeserver,%crsreqresponse);
                   8639:     if ($cdom =~ /^$match_domain$/) {
                   8640:         $homeserver = &domain($cdom,'primary');
                   8641:     }
                   8642:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8643:         my $info;
                   8644:         if (ref($inbound) eq 'HASH') {
                   8645:             $info = &freeze_escape($inbound);
                   8646:         }
                   8647:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8648:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8649:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  8650:                             &escape($title).':'.&escape($code).':'.
                   8651:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   8652:                             $homeserver);
1.1248    raeburn  8653:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8654:             my @items = split(/&/,$response);
                   8655:             foreach my $item (@items) {
                   8656:                 my ($key,$value) = split('=',$item);
                   8657:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8658:             }
                   8659:         }
                   8660:     }
                   8661:     return \%crsreqresponse;
                   8662: }
                   8663: 
1.1305    raeburn  8664: sub auto_export_grades {
1.1309    raeburn  8665:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   8666:     my ($homeserver,%exportresponse);
                   8667:     if ($cdom =~ /^$match_domain$/) {
                   8668:         $homeserver = &domain($cdom,'primary');
                   8669:     }
                   8670:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8671:         my $info;
                   8672:         if (ref($inforef) eq 'HASH') {
                   8673:             $info = &freeze_escape($inforef);
                   8674:         }
                   8675:         if (ref($gradesref) eq 'HASH') {
                   8676:             my $grades = &freeze_escape($gradesref);
                   8677:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   8678:                                 $info.':'.$grades,$homeserver);
                   8679:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   8680:                 my @items = split(/&/,$response);
                   8681:                 foreach my $item (@items) {
                   8682:                     my ($key,$value) = split('=',$item);
                   8683:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   8684:                 }
                   8685:             }
                   8686:         }
                   8687:     }
                   8688:     return \%exportresponse;
1.1305    raeburn  8689: }
                   8690: 
1.1287    raeburn  8691: sub check_instcode_cloning {
                   8692:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   8693:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8694:         return;
                   8695:     }
                   8696:     my $canclone;
                   8697:     if (@{$code_order} > 0) {
                   8698:         my $instcoderegexp ='^';
                   8699:         my @clonecodes = split(/\&/,$cloner);
                   8700:         foreach my $item (@{$code_order}) {
                   8701:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   8702:                 foreach my $pair (@clonecodes) {
                   8703:                     my ($key,$val) = split(/\=/,$pair,2);
                   8704:                     $val = &unescape($val);
                   8705:                     if ($key eq $item) {
                   8706:                         $instcoderegexp .= '('.$val.')';
                   8707:                         last;
                   8708:                     }
                   8709:                 }
                   8710:             } else {
                   8711:                 $instcoderegexp .= $codedefaults->{$item};
                   8712:             }
                   8713:         }
                   8714:         $instcoderegexp .= '$';
                   8715:         my (@from,@to);
                   8716:         eval {
                   8717:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8718:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8719:         };
                   8720:         if ((@from > 0) && (@to > 0)) {
                   8721:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8722:             if (!@diffs) {
                   8723:                 $canclone = 1;
                   8724:             }
                   8725:         }
                   8726:     }
                   8727:     return $canclone;
                   8728: }
                   8729: 
                   8730: sub default_instcode_cloning {
                   8731:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   8732:     my (%codedefaults,@code_order,$canclone);
                   8733:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   8734:         %codedefaults = %{$codedefaultsref};
                   8735:         @code_order = @{$codeorderref};
                   8736:     } elsif ($clonedom) {
                   8737:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   8738:     }
                   8739:     if (($domdefclone) && (@code_order)) {
                   8740:         my @clonecodes = split(/\+/,$domdefclone);
                   8741:         my $instcoderegexp ='^';
                   8742:         foreach my $item (@code_order) {
                   8743:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   8744:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   8745:             } else {
                   8746:                 $instcoderegexp .= $codedefaults{$item};
                   8747:             }
                   8748:         }
                   8749:         $instcoderegexp .= '$';
                   8750:         my (@from,@to);
                   8751:         eval {
                   8752:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8753:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8754:         };
                   8755:         if ((@from > 0) && (@to > 0)) {
                   8756:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8757:             if (!@diffs) {
                   8758:                 $canclone = 1;
                   8759:             }
                   8760:         }
                   8761:     }
                   8762:     return $canclone;
                   8763: }
                   8764: 
1.679     raeburn  8765: # ------------------------------------------------------- Course Group routines
                   8766: 
                   8767: sub get_coursegroups {
1.809     raeburn  8768:     my ($cdom,$cnum,$group,$namespace) = @_;
                   8769:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  8770: }
                   8771: 
1.679     raeburn  8772: sub modify_coursegroup {
                   8773:     my ($cdom,$cnum,$groupsettings) = @_;
                   8774:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   8775: }
                   8776: 
1.809     raeburn  8777: sub toggle_coursegroup_status {
                   8778:     my ($cdom,$cnum,$group,$action) = @_;
                   8779:     my ($from_namespace,$to_namespace);
                   8780:     if ($action eq 'delete') {
                   8781:         $from_namespace = 'coursegroups';
                   8782:         $to_namespace = 'deleted_groups';
                   8783:     } else {
                   8784:         $from_namespace = 'deleted_groups';
                   8785:         $to_namespace = 'coursegroups';
                   8786:     }
                   8787:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  8788:     if (my $tmp = &error(%curr_group)) {
                   8789:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   8790:         return ('read error',$tmp);
                   8791:     } else {
                   8792:         my %savedsettings = %curr_group; 
1.809     raeburn  8793:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  8794:         my $deloutcome;
                   8795:         if ($result eq 'ok') {
1.809     raeburn  8796:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  8797:         } else {
                   8798:             return ('write error',$result);
                   8799:         }
                   8800:         if ($deloutcome eq 'ok') {
                   8801:             return 'ok';
                   8802:         } else {
                   8803:             return ('delete error',$deloutcome);
                   8804:         }
                   8805:     }
                   8806: }
                   8807: 
1.679     raeburn  8808: sub modify_group_roles {
1.957     raeburn  8809:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  8810:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   8811:     my $role = 'gr/'.&escape($userprivs);
                   8812:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  8813:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  8814:     if ($result eq 'ok') {
                   8815:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   8816:     }
1.679     raeburn  8817:     return $result;
                   8818: }
                   8819: 
                   8820: sub modify_coursegroup_membership {
                   8821:     my ($cdom,$cnum,$membership) = @_;
                   8822:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   8823:     return $result;
                   8824: }
                   8825: 
1.682     raeburn  8826: sub get_active_groups {
                   8827:     my ($udom,$uname,$cdom,$cnum) = @_;
                   8828:     my $now = time;
                   8829:     my %groups = ();
                   8830:     foreach my $key (keys(%env)) {
1.811     albertel 8831:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  8832:             my ($start,$end) = split(/\./,$env{$key});
                   8833:             if (($end!=0) && ($end<$now)) { next; }
                   8834:             if (($start!=0) && ($start>$now)) { next; }
                   8835:             if ($1 eq $cdom && $2 eq $cnum) {
                   8836:                 $groups{$3} = $env{$key} ;
                   8837:             }
                   8838:         }
                   8839:     }
                   8840:     return %groups;
                   8841: }
                   8842: 
1.683     raeburn  8843: sub get_group_membership {
                   8844:     my ($cdom,$cnum,$group) = @_;
                   8845:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   8846: }
                   8847: 
                   8848: sub get_users_groups {
                   8849:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  8850:     my @usersgroups;
1.683     raeburn  8851:     my $cachetime=1800;
                   8852: 
                   8853:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  8854:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   8855:     if (defined($cached)) {
1.734     albertel 8856:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  8857:     } else {  
                   8858:         $grouplist = '';
1.816     raeburn  8859:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  8860:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  8861:         my $access_end = $env{'course.'.$courseid.
                   8862:                               '.default_enrollment_end_date'};
                   8863:         my $now = time;
                   8864:         foreach my $key (keys(%roleshash)) {
                   8865:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   8866:                 my $group = $1;
                   8867:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   8868:                     my $start = $2;
                   8869:                     my $end = $1;
                   8870:                     if ($start == -1) { next; } # deleted from group
                   8871:                     if (($start!=0) && ($start>$now)) { next; }
                   8872:                     if (($end!=0) && ($end<$now)) {
                   8873:                         if ($access_end && $access_end < $now) {
                   8874:                             if ($access_end - $end < 86400) {
                   8875:                                 push(@usersgroups,$group);
1.733     raeburn  8876:                             }
                   8877:                         }
1.817     raeburn  8878:                         next;
1.733     raeburn  8879:                     }
1.817     raeburn  8880:                     push(@usersgroups,$group);
1.683     raeburn  8881:                 }
                   8882:             }
                   8883:         }
1.817     raeburn  8884:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8885:         $grouplist = join(':',@usersgroups);
                   8886:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8887:     }
1.733     raeburn  8888:     return @usersgroups;
1.683     raeburn  8889: }
                   8890: 
                   8891: sub devalidate_getgroups_cache {
                   8892:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8893:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8894: 
1.683     raeburn  8895:     my $hashid="$udom:$uname:$courseid";
                   8896:     &devalidate_cache_new('getgroups',$hashid);
                   8897: }
                   8898: 
1.12      www      8899: # ------------------------------------------------------------------ Plain Text
                   8900: 
                   8901: sub plaintext {
1.988     raeburn  8902:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8903:     if ($short =~ m{^cr/}) {
1.758     albertel 8904: 	return (split('/',$short))[-1];
                   8905:     }
1.742     raeburn  8906:     if (!defined($cid)) {
                   8907:         $cid = $env{'request.course.id'};
                   8908:     }
                   8909:     my %rolenames = (
1.1008    raeburn  8910:                       Course    => 'std',
                   8911:                       Community => 'alt1',
1.1305    raeburn  8912:                       Placement => 'std',
1.742     raeburn  8913:                     );
1.1037    raeburn  8914:     if ($cid ne '') {
                   8915:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8916:             unless ($forcedefault) {
                   8917:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8918:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8919:                 return &Apache::lonlocal::mt($roletext);
                   8920:             }
                   8921:         }
                   8922:     }
                   8923:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8924:         (defined($rolenames{$type})) && 
                   8925:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8926:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8927:     } elsif ($cid ne '') {
                   8928:         my $crstype = $env{'course.'.$cid.'.type'};
                   8929:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8930:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8931:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8932:         }
1.742     raeburn  8933:     }
1.1037    raeburn  8934:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8935: }
                   8936: 
                   8937: # ----------------------------------------------------------------- Assign Role
                   8938: 
                   8939: sub assignrole {
1.957     raeburn  8940:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8941:         $context)=@_;
1.21      www      8942:     my $mrole;
                   8943:     if ($role =~ /^cr\//) {
1.393     www      8944:         my $cwosec=$url;
1.811     albertel 8945:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8946: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8947:            my $refused = 1;
                   8948:            if ($context eq 'requestcourses') {
                   8949:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8950:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8951:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8952:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8953:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8954:                            if ($crsenv{'internal.courseowner'} eq
                   8955:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8956:                                $refused = '';
                   8957:                            }
                   8958:                        }
                   8959:                    }
                   8960:                }
                   8961:            }
                   8962:            if ($refused) {
                   8963:                &logthis('Refused custom assignrole: '.
                   8964:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8965:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8966:                return 'refused';
                   8967:            }
1.104     www      8968:         }
1.21      www      8969:         $mrole='cr';
1.678     raeburn  8970:     } elsif ($role =~ /^gr\//) {
                   8971:         my $cwogrp=$url;
1.811     albertel 8972:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8973:         unless (&allowed('mdg',$cwogrp)) {
                   8974:             &logthis('Refused group assignrole: '.
                   8975:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   8976:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   8977:             return 'refused';
                   8978:         }
                   8979:         $mrole='gr';
1.21      www      8980:     } else {
1.82      www      8981:         my $cwosec=$url;
1.811     albertel 8982:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  8983:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   8984:             my $refused;
                   8985:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   8986:                 if (!(&allowed('c'.$role,$url))) {
                   8987:                     $refused = 1;
                   8988:                 }
                   8989:             } else {
                   8990:                 $refused = 1;
                   8991:             }
1.947     raeburn  8992:             if ($refused) {
1.1045    raeburn  8993:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8994:                 if (!$selfenroll && $context eq 'course') {
                   8995:                     my %crsenv;
                   8996:                     if ($role eq 'cc' || $role eq 'co') {
                   8997:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8998:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   8999:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9000:                                 if ($crsenv{'internal.courseowner'} eq 
                   9001:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9002:                                     $refused = '';
                   9003:                                 }
                   9004:                             }
                   9005:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9006:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9007:                                 if ($crsenv{'internal.courseowner'} eq 
                   9008:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9009:                                     $refused = '';
                   9010:                                 }
                   9011:                             }
                   9012:                         }
                   9013:                     }
                   9014:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  9015:                     $refused = '';
1.1017    raeburn  9016:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9017:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9018:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9019:                         my $wrongcc;
                   9020:                         if ($cnum =~ /^$match_community$/) {
                   9021:                             $wrongcc = 1 if ($role eq 'cc');
                   9022:                         } else {
                   9023:                             $wrongcc = 1 if ($role eq 'co');
                   9024:                         }
                   9025:                         unless ($wrongcc) {
                   9026:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9027:                             if ($crsenv{'internal.courseowner'} eq 
                   9028:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9029:                                 $refused = '';
                   9030:                             }
1.1017    raeburn  9031:                         }
                   9032:                     }
1.1183    raeburn  9033:                 } elsif ($context eq 'requestauthor') {
                   9034:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   9035:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9036:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9037:                             $refused = '';
                   9038:                         } else {
                   9039:                             my %domdefaults = &get_domain_defaults($udom);
                   9040:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9041:                                 my $checkbystatus;
                   9042:                                 if ($env{'user.adv'}) { 
                   9043:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9044:                                     if ($disposition eq 'automatic') {
                   9045:                                         $refused = '';
                   9046:                                     } elsif ($disposition eq '') {
                   9047:                                         $checkbystatus = 1;
                   9048:                                     } 
                   9049:                                 } else {
                   9050:                                     $checkbystatus = 1;
                   9051:                                 }
                   9052:                                 if ($checkbystatus) {
                   9053:                                     if ($env{'environment.inststatus'}) {
                   9054:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9055:                                         foreach my $type (@inststatuses) {
                   9056:                                             if (($type ne '') &&
                   9057:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9058:                                                 $refused = '';
                   9059:                                             }
                   9060:                                         }
                   9061:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9062:                                         $refused = '';
                   9063:                                     }
                   9064:                                 }
                   9065:                             }
                   9066:                         }
                   9067:                     }
1.1017    raeburn  9068:                 }
                   9069:                 if ($refused) {
1.947     raeburn  9070:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9071:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9072: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9073:                     return 'refused';
                   9074:                 }
1.932     raeburn  9075:             }
1.1131    raeburn  9076:         } elsif ($role eq 'au') {
                   9077:             if ($url ne '/'.$udom.'/') {
                   9078:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9079:                          ' to assign author role for '.$uname.':'.$udom.
                   9080:                          ' in domain: '.$url.' refused (wrong domain).');
                   9081:                 return 'refused';
                   9082:             }
1.104     www      9083:         }
1.21      www      9084:         $mrole=$role;
                   9085:     }
1.620     albertel 9086:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9087:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9088:     if ($end) { $command.='_'.$end; }
1.21      www      9089:     if ($start) {
                   9090: 	if ($end) { 
1.81      www      9091:            $command.='_'.$start; 
1.21      www      9092:         } else {
1.81      www      9093:            $command.='_0_'.$start;
1.21      www      9094:         }
                   9095:     }
1.739     raeburn  9096:     my $origstart = $start;
                   9097:     my $origend = $end;
1.957     raeburn  9098:     my $delflag;
1.357     www      9099: # actually delete
                   9100:     if ($deleteflag) {
1.373     www      9101: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9102: # modify command to delete the role
1.620     albertel 9103:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9104:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9105: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9106: # set start and finish to negative values for userrolelog
                   9107:            $start=-1;
                   9108:            $end=-1;
1.957     raeburn  9109:            $delflag = 1;
1.357     www      9110:         }
                   9111:     }
                   9112: # send command
1.349     www      9113:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9114: # log new user role if status is ok
1.349     www      9115:     if ($answer eq 'ok') {
1.663     raeburn  9116: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  9117:         if (($role eq 'cc') || ($role eq 'in') ||
                   9118:             ($role eq 'ep') || ($role eq 'ad') ||
                   9119:             ($role eq 'ta') || ($role eq 'st') ||
                   9120:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9121:             ($role eq 'co')) {
1.1200    raeburn  9122: # for course roles, perform group memberships changes triggered by role change.
                   9123:             unless ($role =~ /^gr/) {
                   9124:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9125:                                                  $origstart,$selfenroll,$context);
                   9126:             }
1.1184    raeburn  9127:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9128:                            $selfenroll,$context);
                   9129:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1327    raeburn  9130:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh')) {
1.1184    raeburn  9131:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9132:                            $context);
                   9133:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9134:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9135:                              $context); 
                   9136:         }
1.1053    raeburn  9137:         if ($role eq 'cc') {
                   9138:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9139:         }
1.349     www      9140:     }
                   9141:     return $answer;
1.169     harris41 9142: }
                   9143: 
1.1053    raeburn  9144: sub autoupdate_coowners {
                   9145:     my ($url,$end,$start,$uname,$udom) = @_;
                   9146:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9147:     if (($cdom ne '') && ($cnum ne '')) {
                   9148:         my $now = time;
                   9149:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9150:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9151:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9152:             my $instcode = $coursehash{'internal.coursecode'};
                   9153:             if ($instcode ne '') {
1.1056    raeburn  9154:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9155:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9156:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9157:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9158:                         if ($result eq 'valid') {
                   9159:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9160:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9161:                                     push(@newcoowners,$coowner);
                   9162:                                 }
                   9163:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9164:                                     push(@newcoowners,$uname.':'.$udom);
                   9165:                                 }
                   9166:                                 @newcoowners = sort(@newcoowners);
                   9167:                             } else {
                   9168:                                 push(@newcoowners,$uname.':'.$udom);
                   9169:                             }
                   9170:                         } else {
                   9171:                             if ($coursehash{'internal.co-owners'}) {
                   9172:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9173:                                     unless ($coowner eq $uname.':'.$udom) {
                   9174:                                         push(@newcoowners,$coowner);
                   9175:                                     }
                   9176:                                 }
                   9177:                                 unless (@newcoowners > 0) {
                   9178:                                     $delcoowners = 1;
                   9179:                                     $coowners = '';
                   9180:                                 }
                   9181:                             }
                   9182:                         }
                   9183:                         if (@newcoowners || $delcoowners) {
                   9184:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9185:                                             $delcoowners,@newcoowners);
                   9186:                         }
                   9187:                     }
                   9188:                 }
                   9189:             }
                   9190:         }
                   9191:     }
                   9192: }
                   9193: 
                   9194: sub store_coowners {
                   9195:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9196:     my $cid = $cdom.'_'.$cnum;
                   9197:     my ($coowners,$delresult,$putresult);
                   9198:     if (@newcoowners) {
                   9199:         $coowners = join(',',@newcoowners);
                   9200:         my %coownershash = (
                   9201:                             'internal.co-owners' => $coowners,
                   9202:                            );
                   9203:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9204:         if ($putresult eq 'ok') {
                   9205:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9206:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9207:             }
                   9208:         }
                   9209:     }
                   9210:     if ($delcoowners) {
                   9211:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9212:         if ($delresult eq 'ok') {
                   9213:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9214:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9215:             }
                   9216:         }
                   9217:     }
                   9218:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9219:         my %crsinfo =
                   9220:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9221:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9222:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9223:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9224:         }
                   9225:     }
                   9226: }
                   9227: 
1.169     harris41 9228: # -------------------------------------------------- Modify user authentication
1.197     www      9229: # Overrides without validation
                   9230: 
1.169     harris41 9231: sub modifyuserauth {
                   9232:     my ($udom,$uname,$umode,$upass)=@_;
                   9233:     my $uhome=&homeserver($uname,$udom);
1.197     www      9234:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   9235:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9236:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9237:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9238:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9239: 		     &escape($upass),$uhome);
1.620     albertel 9240:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9241:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9242:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9243:     &log($udom,,$uname,$uhome,
1.620     albertel 9244:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9245:                                      $env{'user.name'}.', '.$umode.
1.197     www      9246:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9247:     unless ($reply eq 'ok') {
1.197     www      9248:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9249: 	return 'error: '.$reply;
                   9250:     }   
1.170     harris41 9251:     return 'ok';
1.80      www      9252: }
                   9253: 
1.81      www      9254: # --------------------------------------------------------------- Modify a user
1.80      www      9255: 
1.81      www      9256: sub modifyuser {
1.206     matthew  9257:     my ($udom,    $uname, $uid,
                   9258:         $umode,   $upass, $first,
                   9259:         $middle,  $last,  $gene,
1.1058    raeburn  9260:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9261:     $udom= &LONCAPA::clean_domain($udom);
                   9262:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9263:     my $showcandelete = 'none';
                   9264:     if (ref($candelete) eq 'ARRAY') {
                   9265:         if (@{$candelete} > 0) {
                   9266:             $showcandelete = join(', ',@{$candelete});
                   9267:         }
                   9268:     }
1.81      www      9269:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9270:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9271: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9272:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9273:                                      ' desiredhome not specified'). 
1.620     albertel 9274:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9275:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9276:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9277:     my $newuser;
                   9278:     if ($uhome eq 'no_host') {
                   9279:         $newuser = 1;
                   9280:     }
1.80      www      9281: # ----------------------------------------------------------------- Create User
1.406     albertel 9282:     if (($uhome eq 'no_host') && 
                   9283: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      9284:         my $unhome='';
1.844     albertel 9285:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9286:             $unhome = $desiredhome;
1.620     albertel 9287: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9288: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9289:         } else { # load balancing routine for determining $unhome
1.81      www      9290:             my $loadm=10000000;
1.841     albertel 9291: 	    my %servers = &get_servers($udom,'library');
                   9292: 	    foreach my $tryserver (keys(%servers)) {
                   9293: 		my $answer=reply('load',$tryserver);
                   9294: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9295: 		    $loadm=$answer;
                   9296: 		    $unhome=$tryserver;
                   9297: 		}
1.80      www      9298: 	    }
                   9299:         }
                   9300:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9301: 	    return 'error: unable to find a home server for '.$uname.
                   9302:                    ' in domain '.$udom;
1.80      www      9303:         }
                   9304:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9305:                          &escape($upass),$unhome);
                   9306: 	unless ($reply eq 'ok') {
                   9307:             return 'error: '.$reply;
                   9308:         }   
1.230     stredwic 9309:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9310:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9311: 	    return 'error: unable verify users home machine.';
1.80      www      9312:         }
1.209     matthew  9313:     }   # End of creation of new user
1.80      www      9314: # ---------------------------------------------------------------------- Add ID
                   9315:     if ($uid) {
                   9316:        $uid=~tr/A-Z/a-z/;
                   9317:        my %uidhash=&idrget($udom,$uname);
1.196     www      9318:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9319:          && (!$forceid)) {
1.80      www      9320: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9321: 	      return 'error: user id "'.$uid.'" does not match '.
                   9322:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9323:           }
                   9324:        } else {
1.1300    raeburn  9325: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      9326:        }
                   9327:     }
                   9328: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9329:     my @tmp=&get('environment',
1.899     raeburn  9330: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9331:                     'permanentemail','inststatus'],
1.134     albertel 9332: 		   $udom,$uname);
1.1075    raeburn  9333:     my (%names,%oldnames);
1.313     matthew  9334:     if ($tmp[0] =~ m/^error:.*/) { 
                   9335:         %names=(); 
                   9336:     } else {
                   9337:         %names = @tmp;
1.1075    raeburn  9338:         %oldnames = %names;
1.313     matthew  9339:     }
1.388     www      9340: #
1.1058    raeburn  9341: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9342: # of users did not contain them), do not overwrite existing values
                   9343: # unless field is in $candelete array ref.  
                   9344: #
                   9345: 
                   9346:     my @fields = ('firstname','middlename','lastname','generation',
                   9347:                   'permanentemail','id');
                   9348:     my %newvalues;
                   9349:     if (ref($candelete) eq 'ARRAY') {
                   9350:         foreach my $field (@fields) {
                   9351:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9352:                 if ($field eq 'firstname') {
                   9353:                     $names{$field} = $first;
                   9354:                 } elsif ($field eq 'middlename') {
                   9355:                     $names{$field} = $middle;
                   9356:                 } elsif ($field eq 'lastname') {
                   9357:                     $names{$field} = $last;
                   9358:                 } elsif ($field eq 'generation') { 
                   9359:                     $names{$field} = $gene;
                   9360:                 } elsif ($field eq 'permanentemail') {
                   9361:                     $names{$field} = $email;
                   9362:                 } elsif ($field eq 'id') {
                   9363:                     $names{$field}  = $uid;
                   9364:                 }
                   9365:             }
                   9366:         }
                   9367:     }
1.388     www      9368:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9369:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9370:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9371:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9372:     if ($email) {
                   9373:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9374:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9375:     }
1.899     raeburn  9376:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9377:     if (defined($inststatus)) {
                   9378:         $names{'inststatus'} = '';
                   9379:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9380:         if (ref($usertypes) eq 'HASH') {
                   9381:             my @okstatuses; 
                   9382:             foreach my $item (split(/:/,$inststatus)) {
                   9383:                 if (defined($usertypes->{$item})) {
                   9384:                     push(@okstatuses,$item);  
                   9385:                 }
                   9386:             }
                   9387:             if (@okstatuses) {
                   9388:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9389:             }
                   9390:         }
                   9391:     }
1.1075    raeburn  9392:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9393:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9394:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9395:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9396:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9397:     } else {
                   9398:         $logmsg .= ' during self creation';
                   9399:     }
1.1075    raeburn  9400:     my $changed;
                   9401:     if ($newuser) {
                   9402:         $changed = 1;
                   9403:     } else {
                   9404:         foreach my $field (@fields) {
                   9405:             if ($names{$field} ne $oldnames{$field}) {
                   9406:                 $changed = 1;
                   9407:                 last;
                   9408:             }
                   9409:         }
                   9410:     }
                   9411:     unless ($changed) {
                   9412:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9413:         &logthis($logmsg);
                   9414:         return 'ok';
                   9415:     }
                   9416:     my $reply = &put('environment', \%names, $udom,$uname);
                   9417:     if ($reply ne 'ok') { 
                   9418:         return 'error: '.$reply;
                   9419:     }
1.1087    raeburn  9420:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9421:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9422:     }
1.1075    raeburn  9423:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9424:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9425:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9426:     &logthis($logmsg);
1.134     albertel 9427:     return 'ok';
1.80      www      9428: }
                   9429: 
1.81      www      9430: # -------------------------------------------------------------- Modify student
1.80      www      9431: 
1.81      www      9432: sub modifystudent {
                   9433:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9434:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314    raeburn  9435:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9436:     if (!$cid) {
1.620     albertel 9437: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9438: 	    return 'not_in_class';
                   9439: 	}
1.80      www      9440:     }
                   9441: # --------------------------------------------------------------- Make the user
1.81      www      9442:     my $reply=&modifyuser
1.209     matthew  9443: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9444:          $desiredhome,$email,$inststatus);
1.80      www      9445:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9446:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  9447:     # student's environment
1.297     matthew  9448:     $uid = undef if (!$forceid);
1.455     albertel 9449:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  9450:                                         $gene,$usec,$end,$start,$type,$locktype,
1.1314    raeburn  9451:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9452:     return $reply;
                   9453: }
                   9454: 
                   9455: sub modify_student_enrollment {
1.1216    raeburn  9456:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314    raeburn  9457:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9458:     my ($cdom,$cnum,$chome);
                   9459:     if (!$cid) {
1.620     albertel 9460: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9461: 	    return 'not_in_class';
                   9462: 	}
1.620     albertel 9463: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9464: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9465:     } else {
                   9466: 	($cdom,$cnum)=split(/_/,$cid);
                   9467:     }
1.620     albertel 9468:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9469:     if (!$chome) {
1.457     raeburn  9470: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9471:     }
1.455     albertel 9472:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9473:     # Make sure the user exists
1.81      www      9474:     my $uhome=&homeserver($uname,$udom);
                   9475:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9476: 	return 'error: no such user';
                   9477:     }
1.297     matthew  9478:     # Get student data if we were not given enough information
                   9479:     if (!defined($first)  || $first  eq '' || 
                   9480:         !defined($last)   || $last   eq '' || 
                   9481:         !defined($uid)    || $uid    eq '' || 
                   9482:         !defined($middle) || $middle eq '' || 
                   9483:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9484:         # They did not supply us with enough data to enroll the student, so
                   9485:         # we need to pick up more information.
1.297     matthew  9486:         my %tmp = &get('environment',
1.294     matthew  9487:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9488:                        ,$udom,$uname);
                   9489: 
1.800     albertel 9490:         #foreach my $key (keys(%tmp)) {
                   9491:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9492:         #}
1.294     matthew  9493:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9494:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9495:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9496:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9497:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9498:     }
1.556     albertel 9499:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9500:     my $user = "$uname:$udom";
                   9501:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9502:     my $reply=cput('classlist',
1.1148    raeburn  9503: 		   {$user => 
1.1314    raeburn  9504: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 9505: 		   $cdom,$cnum);
1.1148    raeburn  9506:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9507:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9508:     } else { 
1.81      www      9509: 	return 'error: '.$reply;
                   9510:     }
1.297     matthew  9511:     # Add student role to user
1.83      www      9512:     my $uurl='/'.$cid;
1.81      www      9513:     $uurl=~s/\_/\//g;
                   9514:     if ($usec) {
                   9515: 	$uurl.='/'.$usec;
                   9516:     }
1.1148    raeburn  9517:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9518:                              $selfenroll,$context);
                   9519:     if ($result ne 'ok') {
                   9520:         if ($old_entry{$user} ne '') {
                   9521:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9522:         } else {
                   9523:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9524:         }
                   9525:     }
                   9526:     return $result; 
1.21      www      9527: }
                   9528: 
1.556     albertel 9529: sub format_name {
                   9530:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9531:     my $name;
                   9532:     if ($first ne 'lastname') {
                   9533: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9534:     } else {
                   9535: 	if ($lastname=~/\S/) {
                   9536: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9537: 	    $name=~s/\s+,/,/;
                   9538: 	} else {
                   9539: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9540: 	}
                   9541:     }
                   9542:     $name=~s/^\s+//;
                   9543:     $name=~s/\s+$//;
                   9544:     $name=~s/\s+/ /g;
                   9545:     return $name;
                   9546: }
                   9547: 
1.84      www      9548: # ------------------------------------------------- Write to course preferences
                   9549: 
                   9550: sub writecoursepref {
                   9551:     my ($courseid,%prefs)=@_;
                   9552:     $courseid=~s/^\///;
                   9553:     $courseid=~s/\_/\//g;
                   9554:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9555:     my $chome=homeserver($cnum,$cdomain);
                   9556:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9557: 	return 'error: no such course';
                   9558:     }
                   9559:     my $cstring='';
1.800     albertel 9560:     foreach my $pref (keys(%prefs)) {
                   9561: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9562:     }
1.84      www      9563:     $cstring=~s/\&$//;
                   9564:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9565: }
                   9566: 
                   9567: # ---------------------------------------------------------- Make/modify course
                   9568: 
                   9569: sub createcourse {
1.741     raeburn  9570:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  9571:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      9572:     $url=&declutter($url);
                   9573:     my $cid='';
1.1028    raeburn  9574:     if ($context eq 'requestcourses') {
                   9575:         my $can_create = 0;
                   9576:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9577:         if ($udom eq $ownerdom) {
                   9578:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   9579:                                   $context)) {
                   9580:                 $can_create = 1;
                   9581:             }
                   9582:         } else {
                   9583:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9584:                                            $category);
                   9585:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   9586:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   9587:                 if (@curr > 0) {
                   9588:                     my @options = qw(approval validate autolimit);
                   9589:                     my $optregex = join('|',@options);
                   9590:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   9591:                         $can_create = 1;
                   9592:                     }
                   9593:                 }
                   9594:             }
                   9595:         }
                   9596:         if ($can_create) {
                   9597:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   9598:                 unless (&allowed('ccc',$udom)) {
                   9599:                     return 'refused'; 
                   9600:                 }
1.1017    raeburn  9601:             }
                   9602:         } else {
                   9603:             return 'refused';
                   9604:         }
1.1028    raeburn  9605:     } elsif (!&allowed('ccc',$udom)) {
                   9606:         return 'refused';
1.84      www      9607:     }
1.1011    raeburn  9608: # --------------------------------------------------------------- Get Unique ID
                   9609:     my $uname;
                   9610:     if ($cnum =~ /^$match_courseid$/) {
                   9611:         my $chome=&homeserver($cnum,$udom,'true');
                   9612:         if (($chome eq '') || ($chome eq 'no_host')) {
                   9613:             $uname = $cnum;
                   9614:         } else {
1.1038    raeburn  9615:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9616:         }
                   9617:     } else {
1.1038    raeburn  9618:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9619:     }
                   9620:     return $uname if ($uname =~ /^error/);
                   9621: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  9622:     if (!defined($course_server)) {
                   9623:         if (defined(&domain($udom,'primary'))) {
                   9624:             $course_server = &domain($udom,'primary');
                   9625:         } else {
                   9626:             $course_server = $env{'user.home'}; 
                   9627:         }
                   9628:     }
                   9629:     my %host_servers =
                   9630:         &Apache::lonnet::get_servers($udom,'library');
                   9631:     unless ($host_servers{$course_server}) {
                   9632:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  9633:     }
1.84      www      9634: # ------------------------------------------------------------- Make the course
                   9635:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  9636:                       $course_server);
1.84      www      9637:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  9638:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      9639:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9640: 	return 'error: no such course';
                   9641:     }
1.271     www      9642: # ----------------------------------------------------------------- Course made
1.516     raeburn  9643: # log existence
1.1029    raeburn  9644:     my $now = time;
1.918     raeburn  9645:     my $newcourse = {
                   9646:                     $udom.'_'.$uname => {
1.921     raeburn  9647:                                      description => $description,
                   9648:                                      inst_code   => $inst_code,
                   9649:                                      owner       => $course_owner,
                   9650:                                      type        => $crstype,
1.1029    raeburn  9651:                                      creator     => $env{'user.name'}.':'.
                   9652:                                                     $env{'user.domain'},
                   9653:                                      created     => $now,
                   9654:                                      context     => $context,
1.918     raeburn  9655:                                                 },
                   9656:                     };
1.921     raeburn  9657:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      9658: # set toplevel url
1.271     www      9659:     my $topurl=$url;
                   9660:     unless ($nonstandard) {
                   9661: # ------------------------------------------ For standard courses, make top url
                   9662:         my $mapurl=&clutter($url);
1.278     www      9663:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 9664:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      9665: <map>
                   9666: <resource id="1" type="start"></resource>
                   9667: <resource id="2" src="$mapurl"></resource>
                   9668: <resource id="3" type="finish"></resource>
                   9669: <link index="1" from="1" to="2"></link>
                   9670: <link index="2" from="2" to="3"></link>
                   9671: </map>
                   9672: ENDINITMAP
                   9673:         $topurl=&declutter(
1.638     albertel 9674:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      9675:                           );
                   9676:     }
                   9677: # ----------------------------------------------------------- Write preferences
1.84      www      9678:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  9679:                      ('description'              => $description,
                   9680:                       'url'                      => $topurl,
                   9681:                       'internal.creator'         => $env{'user.name'}.':'.
                   9682:                                                     $env{'user.domain'},
                   9683:                       'internal.created'         => $now,
                   9684:                       'internal.creationcontext' => $context)
                   9685:                     );
1.84      www      9686:     return '/'.$udom.'/'.$uname;
                   9687: }
                   9688: 
1.1011    raeburn  9689: # ------------------------------------------------------------------- Create ID
                   9690: sub generate_coursenum {
1.1038    raeburn  9691:     my ($udom,$crstype) = @_;
1.1011    raeburn  9692:     my $domdesc = &domain($udom);
                   9693:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  9694:     my $first;
                   9695:     if ($crstype eq 'Community') {
                   9696:         $first = '0';
                   9697:     } else {
                   9698:         $first = int(1+rand(9)); 
                   9699:     } 
                   9700:     my $uname=$first.
1.1011    raeburn  9701:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9702:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9703:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9704: # ----------------------------------------------- Make sure that does not exist
                   9705:     my $uhome=&homeserver($uname,$udom,'true');
                   9706:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  9707:         if ($crstype eq 'Community') {
                   9708:             $first = '0';
                   9709:         } else {
                   9710:             $first = int(1+rand(9));
                   9711:         }
                   9712:         $uname=$first.
1.1011    raeburn  9713:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9714:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9715:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9716:         $uhome=&homeserver($uname,$udom,'true');
                   9717:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   9718:             return 'error: unable to generate unique course-ID';
                   9719:         }
                   9720:     }
                   9721:     return $uname;
                   9722: }
                   9723: 
1.813     albertel 9724: sub is_course {
1.1167    droeschl 9725:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   9726:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   9727: 
                   9728:     return unless $cdom and $cnum;
                   9729: 
                   9730:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   9731:         '.');
                   9732: 
1.1219    raeburn  9733:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 9734:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 9735: }
                   9736: 
1.1015    raeburn  9737: sub store_userdata {
                   9738:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  9739:     my $result;
1.1016    raeburn  9740:     if ($datakey ne '') {
1.1013    raeburn  9741:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  9742:             if ($udom eq '' || $uname eq '') {
                   9743:                 $udom = $env{'user.domain'};
                   9744:                 $uname = $env{'user.name'};
                   9745:             }
                   9746:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  9747:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   9748:                 $result = 'error: no_host';
                   9749:             } else {
                   9750:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   9751:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   9752: 
                   9753:                 my $namevalue='';
                   9754:                 foreach my $key (keys(%{$storehash})) {
                   9755:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   9756:                 }
                   9757:                 $namevalue=~s/\&$//;
1.1224    raeburn  9758:                 unless ($namespace eq 'courserequests') {
                   9759:                     $datakey = &escape($datakey);
                   9760:                 }
1.1105    raeburn  9761:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   9762:                                   $namevalue,$uhome);
1.1013    raeburn  9763:             }
                   9764:         } else {
                   9765:             $result = 'error: data to store was not a hash reference'; 
                   9766:         }
                   9767:     } else {
                   9768:         $result= 'error: invalid requestkey'; 
                   9769:     }
                   9770:     return $result;
                   9771: }
                   9772: 
1.21      www      9773: # ---------------------------------------------------------- Assign Custom Role
                   9774: 
                   9775: sub assigncustomrole {
1.957     raeburn  9776:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9777:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  9778:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      9779: }
                   9780: 
                   9781: # ----------------------------------------------------------------- Revoke Role
                   9782: 
                   9783: sub revokerole {
1.957     raeburn  9784:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9785:     my $now=time;
1.965     raeburn  9786:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      9787: }
                   9788: 
                   9789: # ---------------------------------------------------------- Revoke Custom Role
                   9790: 
                   9791: sub revokecustomrole {
1.957     raeburn  9792:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9793:     my $now=time;
1.357     www      9794:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  9795:            $deleteflag,$selfenroll,$context);
1.17      www      9796: }
                   9797: 
1.533     banghart 9798: # ------------------------------------------------------------ Disk usage
1.535     albertel 9799: sub diskusage {
1.955     raeburn  9800:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   9801:     $directorypath =~ s/\/$//;
                   9802:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   9803:                        .&escape($getpropath).':'.&escape($uname).':'
                   9804:                        .&escape($udom),homeserver($uname,$udom));
                   9805:     if ($listing eq 'unknown_cmd') {
                   9806:         if ($getpropath) {
                   9807:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   9808:         }
                   9809:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   9810:     }
1.514     albertel 9811:     return $listing;
1.512     banghart 9812: }
                   9813: 
1.566     banghart 9814: sub is_locked {
1.1096    raeburn  9815:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 9816:     my @check;
                   9817:     my $is_locked;
1.1093    raeburn  9818:     push (@check,$file_name);
1.613     albertel 9819:     my %locked = &get('file_permissions',\@check,
1.620     albertel 9820: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 9821:     my ($tmp)=keys(%locked);
                   9822:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  9823:     
1.566     banghart 9824:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  9825:         $is_locked = 'false';
                   9826:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  9827:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  9828:                $is_locked = 'true';
1.1096    raeburn  9829:                if (ref($which) eq 'ARRAY') {
                   9830:                    push(@{$which},$entry);
                   9831:                } else {
                   9832:                    last;
                   9833:                }
1.745     raeburn  9834:            }
                   9835:        }
1.566     banghart 9836:     } else {
                   9837:         $is_locked = 'false';
                   9838:     }
1.1093    raeburn  9839:     return $is_locked;
1.566     banghart 9840: }
                   9841: 
1.759     albertel 9842: sub declutter_portfile {
                   9843:     my ($file) = @_;
1.833     albertel 9844:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 9845:     return $file;
                   9846: }
                   9847: 
1.559     banghart 9848: # ------------------------------------------------------------- Mark as Read Only
                   9849: 
                   9850: sub mark_as_readonly {
                   9851:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 9852:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9853:     my ($tmp)=keys(%current_permissions);
                   9854:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 9855:     foreach my $file (@{$files}) {
1.759     albertel 9856: 	$file = &declutter_portfile($file);
1.561     banghart 9857:         push(@{$current_permissions{$file}},$what);
1.559     banghart 9858:     }
1.613     albertel 9859:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9860:     return;
                   9861: }
                   9862: 
1.572     banghart 9863: # ------------------------------------------------------------Save Selected Files
                   9864: 
                   9865: sub save_selected_files {
                   9866:     my ($user, $path, @files) = @_;
                   9867:     my $filename = $user."savedfiles";
1.573     banghart 9868:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 9869:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 9870:     foreach my $file (@files) {
1.620     albertel 9871:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 9872:     }
                   9873:     foreach my $file (@other_files) {
1.574     banghart 9874:         print (OUT $file."\n");
1.572     banghart 9875:     }
1.574     banghart 9876:     close (OUT);
1.572     banghart 9877:     return 'ok';
                   9878: }
                   9879: 
1.574     banghart 9880: sub clear_selected_files {
                   9881:     my ($user) = @_;
                   9882:     my $filename = $user."savedfiles";
1.1117    foxr     9883:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 9884:     print (OUT undef);
                   9885:     close (OUT);
                   9886:     return ("ok");    
                   9887: }
                   9888: 
1.572     banghart 9889: sub files_in_path {
                   9890:     my ($user, $path) = @_;
                   9891:     my $filename = $user."savedfiles";
                   9892:     my %return_files;
1.1117    foxr     9893:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 9894:     while (my $line_in = <IN>) {
1.574     banghart 9895:         chomp ($line_in);
                   9896:         my @paths_and_file = split (m!/!, $line_in);
                   9897:         my $file_part = pop (@paths_and_file);
                   9898:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9899:         $path_part.='/';
                   9900:         my $path_and_file = $path_part.$file_part;
                   9901:         if ($path_part eq $path) {
                   9902:             $return_files{$file_part}= 'selected';
                   9903:         }
                   9904:     }
1.574     banghart 9905:     close (IN);
                   9906:     return (\%return_files);
1.572     banghart 9907: }
                   9908: 
                   9909: # called in portfolio select mode, to show files selected NOT in current directory
                   9910: sub files_not_in_path {
                   9911:     my ($user, $path) = @_;
                   9912:     my $filename = $user."savedfiles";
                   9913:     my @return_files;
                   9914:     my $path_part;
1.1117    foxr     9915:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 9916:     while (my $line = <IN>) {
1.572     banghart 9917:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9918:         my @paths_and_file = split(m|/|, $line);
                   9919:         my $file_part = pop(@paths_and_file);
                   9920:         chomp($file_part);
                   9921:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9922:         $path_part .= '/';
                   9923:         my $path_and_file = $path_part.$file_part;
                   9924:         if ($path_part ne $path) {
1.800     albertel 9925:             push(@return_files, ($path_and_file));
1.572     banghart 9926:         }
                   9927:     }
1.800     albertel 9928:     close(OUT);
1.574     banghart 9929:     return (@return_files);
1.572     banghart 9930: }
                   9931: 
1.1273    raeburn  9932: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   9933:  
                   9934: sub portfiles_versioning {
                   9935:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   9936:     my $portfolio_root = '/userfiles/portfolio';
                   9937:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   9938:     foreach my $file (@{$portfiles}) {
                   9939:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   9940:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   9941:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   9942:         my $getpropath = 1;
                   9943:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   9944:                                              $stu_name,$getpropath);
                   9945:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   9946:         my $new_answer = 
                   9947:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   9948:         if ($new_answer ne 'problem getting file') {
                   9949:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   9950:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   9951:                               [$symb,$env{'request.course.id'},'graded']);
                   9952:         }
                   9953:     }
                   9954: }
                   9955: 
                   9956: sub get_next_version {
                   9957:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   9958:     my $version;
                   9959:     if (ref($dir_list) eq 'ARRAY') {
                   9960:         foreach my $row (@{$dir_list}) {
                   9961:             my ($file) = split(/\&/,$row,2);
                   9962:             my ($file_name,$file_version,$file_ext) =
                   9963:                 &file_name_version_ext($file);
                   9964:             if (($file_name eq $answer_name) &&
                   9965:                 ($file_ext eq $answer_ext)) {
                   9966:                      # gets here if filename and extension match,
                   9967:                      # regardless of version
                   9968:                 if ($file_version ne '') {
                   9969:                     # a versioned file is found  so save it for later
                   9970:                     if ($file_version > $version) {
                   9971:                         $version = $file_version;
                   9972:                     }
                   9973:                 }
                   9974:             }
                   9975:         }
                   9976:     }
                   9977:     $version ++;
                   9978:     return($version);
                   9979: }
                   9980: 
                   9981: sub version_selected_portfile {
                   9982:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   9983:     my ($answer_name,$answer_ver,$answer_ext) =
                   9984:         &file_name_version_ext($file_name);
                   9985:     my $new_answer;
                   9986:     $env{'form.copy'} =
                   9987:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   9988:     if($env{'form.copy'} eq '-1') {
                   9989:         $new_answer = 'problem getting file';
                   9990:     } else {
                   9991:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   9992:         my $copy_result = 
                   9993:             &finishuserfileupload($stu_name,$domain,'copy',
                   9994:                                   '/portfolio'.$directory.$new_answer);
                   9995:     }
                   9996:     undef($env{'form.copy'});
                   9997:     return ($new_answer);
                   9998: }
                   9999: 
                   10000: sub file_name_version_ext {
                   10001:     my ($file)=@_;
                   10002:     my @file_parts = split(/\./, $file);
                   10003:     my ($name,$version,$ext);
                   10004:     if (@file_parts > 1) {
                   10005:         $ext=pop(@file_parts);
                   10006:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   10007:             $version=pop(@file_parts);
                   10008:         }
                   10009:         $name=join('.',@file_parts);
                   10010:     } else {
                   10011:         $name=join('.',@file_parts);
                   10012:     }
                   10013:     return($name,$version,$ext);
                   10014: }
                   10015: 
1.745     raeburn  10016: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10017: 
1.745     raeburn  10018: sub get_portfile_permissions {
                   10019:     my ($domain,$user) = @_;
1.613     albertel 10020:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10021:     my ($tmp)=keys(%current_permissions);
                   10022:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10023:     return \%current_permissions;
                   10024: }
                   10025: 
                   10026: #---------------------------------------------Get portfolio file access controls
                   10027: 
1.749     raeburn  10028: sub get_access_controls {
1.745     raeburn  10029:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10030:     my %access;
                   10031:     my $real_file = $file;
                   10032:     $file =~ s/\.meta$//;
1.745     raeburn  10033:     if (defined($file)) {
1.749     raeburn  10034:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10035:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10036:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10037:             }
                   10038:         }
1.745     raeburn  10039:     } else {
1.749     raeburn  10040:         foreach my $key (keys(%{$current_permissions})) {
                   10041:             if ($key =~ /\0accesscontrol$/) {
                   10042:                 if (defined($group)) {
                   10043:                     if ($key !~ m-^\Q$group\E/-) {
                   10044:                         next;
                   10045:                     }
                   10046:                 }
                   10047:                 my ($fullpath) = split(/\0/,$key);
                   10048:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10049:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10050:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10051:                     }
                   10052:                 }
                   10053:             }
                   10054:         }
                   10055:     }
                   10056:     return %access;
                   10057: }
                   10058: 
                   10059: sub modify_access_controls {
                   10060:     my ($file_name,$changes,$domain,$user)=@_;
                   10061:     my ($outcome,$deloutcome);
                   10062:     my %store_permissions;
                   10063:     my %new_values;
                   10064:     my %new_control;
                   10065:     my %translation;
                   10066:     my @deletions = ();
                   10067:     my $now = time;
                   10068:     if (exists($$changes{'activate'})) {
                   10069:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10070:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10071:             my $numnew = scalar(@newitems);
                   10072:             for (my $i=0; $i<$numnew; $i++) {
                   10073:                 my $newkey = $newitems[$i];
                   10074:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10075:                 if ($newkey =~ /^\d+:/) { 
                   10076:                     $newkey =~ s/^(\d+)/$newid/;
                   10077:                     $translation{$1} = $newid;
                   10078:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10079:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10080:                     $translation{$1} = $newid;
                   10081:                 }
1.749     raeburn  10082:                 $new_values{$file_name."\0".$newkey} = 
                   10083:                                           $$changes{'activate'}{$newitems[$i]};
                   10084:                 $new_control{$newkey} = $now;
                   10085:             }
                   10086:         }
                   10087:     }
                   10088:     my %todelete;
                   10089:     my %changed_items;
                   10090:     foreach my $action ('delete','update') {
                   10091:         if (exists($$changes{$action})) {
                   10092:             if (ref($$changes{$action}) eq 'HASH') {
                   10093:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10094:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10095:                     if ($action eq 'delete') { 
                   10096:                         $todelete{$itemnum} = 1;
                   10097:                     } else {
                   10098:                         $changed_items{$itemnum} = $key;
                   10099:                     }
                   10100:                 }
1.745     raeburn  10101:             }
                   10102:         }
1.749     raeburn  10103:     }
                   10104:     # get lock on access controls for file.
                   10105:     my $lockhash = {
                   10106:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10107:                                                        ':'.$env{'user.domain'},
                   10108:                    }; 
                   10109:     my $tries = 0;
                   10110:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10111:    
1.1288    damieng  10112:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10113:         $tries ++;
1.1289    damieng  10114:         sleep(0.1);
1.749     raeburn  10115:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10116:     }
                   10117:     if ($gotlock eq 'ok') {
                   10118:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10119:         my ($tmp)=keys(%curr_permissions);
                   10120:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10121:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10122:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10123:             if (ref($curr_controls) eq 'HASH') {
                   10124:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10125:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10126:                     if (defined($todelete{$itemnum})) {
                   10127:                         push(@deletions,$file_name."\0".$control_item);
                   10128:                     } else {
                   10129:                         if (defined($changed_items{$itemnum})) {
                   10130:                             $new_control{$changed_items{$itemnum}} = $now;
                   10131:                             push(@deletions,$file_name."\0".$control_item);
                   10132:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10133:                         } else {
                   10134:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10135:                         }
                   10136:                     }
1.745     raeburn  10137:                 }
                   10138:             }
                   10139:         }
1.970     raeburn  10140:         my ($group);
                   10141:         if (&is_course($domain,$user)) {
                   10142:             ($group,my $file) = split(/\//,$file_name,2);
                   10143:         }
1.749     raeburn  10144:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10145:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10146:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10147:         #  remove lock
                   10148:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10149:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10150:         my $sqlresult =
1.970     raeburn  10151:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10152:                                     $group);
1.749     raeburn  10153:     } else {
                   10154:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10155:     }
1.749     raeburn  10156:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10157: }
                   10158: 
1.827     raeburn  10159: sub make_public_indefinitely {
1.1271    raeburn  10160:     my (@requrl) = @_;
                   10161:     return &automated_portfile_access('public',\@requrl);
                   10162: }
                   10163: 
                   10164: sub automated_portfile_access {
                   10165:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  10166:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   10167:         return 'invalid';
                   10168:     }
1.1271    raeburn  10169:     my %urls;
                   10170:     if (ref($addsref) eq 'ARRAY') {
                   10171:         foreach my $requrl (@{$addsref}) {
                   10172:             if (&is_portfolio_url($requrl)) {
                   10173:                 unless (exists($urls{$requrl})) {
                   10174:                     $urls{$requrl} = 'add';
                   10175:                 }
                   10176:             }
                   10177:         }
                   10178:     }
                   10179:     if (ref($delsref) eq 'ARRAY') {
                   10180:         foreach my $requrl (@{$delsref}) { 
                   10181:             if (&is_portfolio_url($requrl)) {
                   10182:                 unless (exists($urls{$requrl})) {
                   10183:                     $urls{$requrl} = 'delete'; 
                   10184:                 }
                   10185:             }
                   10186:         }
                   10187:     }
                   10188:     unless (keys(%urls)) {
                   10189:         return 'invalid';
                   10190:     }
                   10191:     my $ip;
                   10192:     if ($accesstype eq 'ip') {
                   10193:         if (ref($info) eq 'HASH') {
                   10194:             if ($info->{'ip'} ne '') {
                   10195:                 $ip = $info->{'ip'};
                   10196:             }
                   10197:         }
                   10198:         if ($ip eq '') {
                   10199:             return 'invalid';
                   10200:         }
                   10201:     }
                   10202:     my $errors;
1.827     raeburn  10203:     my $now = time;
1.1271    raeburn  10204:     my %current_perms;
                   10205:     foreach my $requrl (sort(keys(%urls))) {
                   10206:         my $action;
                   10207:         if ($urls{$requrl} eq 'add') {
                   10208:             $action = 'activate';
                   10209:         } else {
                   10210:             $action = 'none';
                   10211:         }
                   10212:         my $aclnum = 0;
1.827     raeburn  10213:         my (undef,$udom,$unum,$file_name,$group) =
                   10214:             &parse_portfolio_url($requrl);
1.1271    raeburn  10215:         unless (exists($current_perms{$unum.':'.$udom})) {
                   10216:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   10217:         }
                   10218:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  10219:                                                    $group,$file_name);
                   10220:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10221:             my ($num,$scope,$end,$start) = 
                   10222:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  10223:             if ($scope eq $accesstype) {
                   10224:                 if (($start <= $now) && ($end == 0)) {
                   10225:                     if ($accesstype eq 'ip') {
                   10226:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   10227:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   10228:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   10229:                                     if ($urls{$requrl} eq 'add') {
                   10230:                                         $action = 'none';
                   10231:                                         last;
                   10232:                                     } else {
                   10233:                                         $action = 'delete';
                   10234:                                         $aclnum = $num;
                   10235:                                         last;
                   10236:                                     }
                   10237:                                 }
                   10238:                             }
                   10239:                         }
                   10240:                     } elsif ($accesstype eq 'public') {
                   10241:                         if ($urls{$requrl} eq 'add') {
                   10242:                             $action = 'none';
                   10243:                             last;
                   10244:                         } else {
                   10245:                             $action = 'delete';
                   10246:                             $aclnum = $num;
                   10247:                             last;
                   10248:                         }
                   10249:                     }
                   10250:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  10251:                     $action = 'update';
                   10252:                     $aclnum = $num;
1.1271    raeburn  10253:                     last;
1.827     raeburn  10254:                 }
                   10255:             }
                   10256:         }
                   10257:         if ($action eq 'none') {
1.1271    raeburn  10258:             next;
1.827     raeburn  10259:         } else {
                   10260:             my %changes;
                   10261:             my $newend = 0;
                   10262:             my $newstart = $now;
1.1271    raeburn  10263:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  10264:             $changes{$action}{$newkey} = {
1.1271    raeburn  10265:                 type => $accesstype,
1.827     raeburn  10266:                 time => {
                   10267:                     start => $newstart,
                   10268:                     end   => $newend,
                   10269:                 },
                   10270:             };
1.1271    raeburn  10271:             if ($accesstype eq 'ip') {
                   10272:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   10273:             }
1.827     raeburn  10274:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10275:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  10276:             unless ($outcome eq 'ok') {
                   10277:                 $errors .= $outcome.' ';
                   10278:             }
1.827     raeburn  10279:         }
1.1271    raeburn  10280:     }
                   10281:     if ($errors) {
                   10282:         $errors =~ s/\s$//;
                   10283:         return $errors;
1.827     raeburn  10284:     } else {
1.1271    raeburn  10285:         return 'ok';
1.827     raeburn  10286:     }
                   10287: }
                   10288: 
1.745     raeburn  10289: #------------------------------------------------------Get Marked as Read Only
                   10290: 
                   10291: sub get_marked_as_readonly {
                   10292:     my ($domain,$user,$what,$group) = @_;
                   10293:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10294:     my @readonly_files;
1.629     banghart 10295:     my $cmp1=$what;
                   10296:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10297:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10298:         if (defined($group)) {
                   10299:             if ($file_name !~ m-^\Q$group\E/-) {
                   10300:                 next;
                   10301:             }
                   10302:         }
1.561     banghart 10303:         if (ref($value) eq "ARRAY"){
                   10304:             foreach my $stored_what (@{$value}) {
1.629     banghart 10305:                 my $cmp2=$stored_what;
1.759     albertel 10306:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10307:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10308:                 }
1.629     banghart 10309:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10310:                     push(@readonly_files, $file_name);
1.745     raeburn  10311:                     last;
1.563     banghart 10312:                 } elsif (!defined($what)) {
                   10313:                     push(@readonly_files, $file_name);
1.745     raeburn  10314:                     last;
1.561     banghart 10315:                 }
                   10316:             }
1.745     raeburn  10317:         }
1.561     banghart 10318:     }
                   10319:     return @readonly_files;
                   10320: }
1.577     banghart 10321: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10322: 
1.577     banghart 10323: sub get_marked_as_readonly_hash {
1.745     raeburn  10324:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10325:     my %readonly_files;
1.745     raeburn  10326:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10327:         if (defined($group)) {
                   10328:             if ($file_name !~ m-^\Q$group\E/-) {
                   10329:                 next;
                   10330:             }
                   10331:         }
1.577     banghart 10332:         if (ref($value) eq "ARRAY"){
                   10333:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10334:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10335:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10336:                         if ($lock_descriptor eq 'graded') {
                   10337:                             $readonly_files{$file_name} = 'graded';
                   10338:                         } elsif ($lock_descriptor eq 'handback') {
                   10339:                             $readonly_files{$file_name} = 'handback';
                   10340:                         } else {
                   10341:                             if (!exists($readonly_files{$file_name})) {
                   10342:                                 $readonly_files{$file_name} = 'locked';
                   10343:                             }
                   10344:                         }
1.745     raeburn  10345:                     }
1.750     banghart 10346:                 } 
1.577     banghart 10347:             }
                   10348:         } 
                   10349:     }
                   10350:     return %readonly_files;
                   10351: }
1.559     banghart 10352: # ------------------------------------------------------------ Unmark as Read Only
                   10353: 
                   10354: sub unmark_as_readonly {
1.629     banghart 10355:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10356:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10357:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10358:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10359:     my $symb_crs = $what;
                   10360:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10361:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10362:     my ($tmp)=keys(%current_permissions);
                   10363:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10364:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10365:     foreach my $file (@readonly_files) {
1.759     albertel 10366: 	my $clean_file = &declutter_portfile($file);
                   10367: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10368: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10369:         my @new_locks;
                   10370:         my @del_keys;
                   10371:         if (ref($current_locks) eq "ARRAY"){
                   10372:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10373:                 my $compare=$locker;
1.749     raeburn  10374:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10375:                     $compare=join('',@{$locker});
1.746     raeburn  10376:                     if ($compare ne $symb_crs) {
                   10377:                         push(@new_locks, $locker);
                   10378:                     }
1.563     banghart 10379:                 }
                   10380:             }
1.650     albertel 10381:             if (scalar(@new_locks) > 0) {
1.563     banghart 10382:                 $current_permissions{$file} = \@new_locks;
                   10383:             } else {
                   10384:                 push(@del_keys, $file);
1.613     albertel 10385:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10386:                 delete($current_permissions{$file});
1.563     banghart 10387:             }
                   10388:         }
1.561     banghart 10389:     }
1.613     albertel 10390:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10391:     return;
                   10392: }
1.512     banghart 10393: 
1.17      www      10394: # ------------------------------------------------------------ Directory lister
                   10395: 
                   10396: sub dirlist {
1.955     raeburn  10397:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10398:     $uri=~s/^\///;
                   10399:     $uri=~s/\/$//;
1.253     stredwic 10400:     my ($udom, $uname);
1.955     raeburn  10401:     if ($getuserdir) {
1.253     stredwic 10402:         $udom = $userdomain;
                   10403:         $uname = $username;
1.955     raeburn  10404:     } else {
                   10405:         (undef,$udom,$uname)=split(/\//,$uri);
                   10406:         if(defined($userdomain)) {
                   10407:             $udom = $userdomain;
                   10408:         }
                   10409:         if(defined($username)) {
                   10410:             $uname = $username;
                   10411:         }
1.253     stredwic 10412:     }
1.955     raeburn  10413:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10414: 
1.955     raeburn  10415:     $dirRoot = $perlvar{'lonDocRoot'};
                   10416:     if (defined($getpropath)) {
                   10417:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10418:         $dirRoot =~ s/\/$//;
1.955     raeburn  10419:     } elsif (defined($getuserdir)) {
                   10420:         my $subdir=$uname.'__';
                   10421:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10422:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10423:                    ."/$udom/$subdir/$uname";
                   10424:     } elsif (defined($alternateRoot)) {
                   10425:         $dirRoot = $alternateRoot;
1.751     banghart 10426:     }
1.253     stredwic 10427: 
                   10428:     if($udom) {
                   10429:         if($uname) {
1.1135    raeburn  10430:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10431:             if ($uhome eq 'no_host') {
                   10432:                 return ([],'no_host');
                   10433:             }
1.955     raeburn  10434:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10435:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10436:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10437:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10438:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10439:             } else {
                   10440:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10441:             }
1.605     matthew  10442:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10443:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10444:                 @listing_results = split(/:/,$listing);
                   10445:             } else {
                   10446:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10447:             }
1.1135    raeburn  10448:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10449:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10450:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10451:                 return ([],$listing);
                   10452:             } else {
                   10453:                 return (\@listing_results);
1.1135    raeburn  10454:             }
1.955     raeburn  10455:         } elsif(!$alternateRoot) {
1.1136    raeburn  10456:             my (%allusers,%listerror);
1.841     albertel 10457: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10458:  	    foreach my $tryserver (keys(%servers)) {
                   10459:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10460:                                   &escape($udom),$tryserver);
                   10461:                 if ($listing eq 'unknown_cmd') {
                   10462: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10463: 				      $udom, $tryserver);
                   10464:                 } else {
                   10465:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10466:                 }
1.841     albertel 10467: 		if ($listing eq 'unknown_cmd') {
                   10468: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10469: 				      $udom, $tryserver);
                   10470: 		    @listing_results = split(/:/,$listing);
                   10471: 		} else {
                   10472: 		    @listing_results =
                   10473: 			map { &unescape($_); } split(/:/,$listing);
                   10474: 		}
1.1136    raeburn  10475:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10476:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10477:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10478:                     $listerror{$tryserver} = $listing;
                   10479:                 } else {
1.841     albertel 10480: 		    foreach my $line (@listing_results) {
                   10481: 			my ($entry) = split(/&/,$line,2);
                   10482: 			$allusers{$entry} = 1;
                   10483: 		    }
                   10484: 		}
1.253     stredwic 10485:             }
1.1136    raeburn  10486:             my @alluserslist=();
1.800     albertel 10487:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10488:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10489:             }
1.1318    droeschl 10490: 
                   10491:             if (!%listerror) {
                   10492:                 # no errors
                   10493:                 return (\@alluserslist);
                   10494:             } elsif (scalar(keys(%servers)) == 1) {
                   10495:                 # one library server, one error 
                   10496:                 my ($key) = keys(%listerror);
                   10497:                 return (\@alluserslist, $listerror{$key});
                   10498:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10499:                 # con_lost indicates that we might miss data from at least one
                   10500:                 # library server
                   10501:                 return (\@alluserslist, 'con_lost');
                   10502:             } else {
                   10503:                 # multiple library servers and no con_lost -> data should be
                   10504:                 # complete. 
                   10505:                 return (\@alluserslist);
                   10506:             }
                   10507: 
1.253     stredwic 10508:         } else {
1.1136    raeburn  10509:             return ([],'missing username');
1.253     stredwic 10510:         }
1.955     raeburn  10511:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10512:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10513:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10514:         return (\@all_domains);
1.955     raeburn  10515:     } else {
1.1136    raeburn  10516:         return ([],'missing domain');
1.275     stredwic 10517:     }
                   10518: }
                   10519: 
                   10520: # --------------------------------------------- GetFileTimestamp
                   10521: # This function utilizes dirlist and returns the date stamp for
                   10522: # when it was last modified.  It will also return an error of -1
                   10523: # if an error occurs
                   10524: 
                   10525: sub GetFileTimestamp {
1.955     raeburn  10526:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10527:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10528:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10529:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10530:                                     undef,$getuserdir);
                   10531:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10532:         return -1;
                   10533:     }
                   10534:     if (ref($fileref) eq 'ARRAY') {
                   10535:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10536:         # @stats contains first the filename, then the stat output
                   10537:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10538:     } else {
                   10539:         return -1;
1.253     stredwic 10540:     }
1.26      www      10541: }
                   10542: 
1.712     albertel 10543: sub stat_file {
                   10544:     my ($uri) = @_;
1.787     albertel 10545:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10546: 
1.955     raeburn  10547:     my ($udom,$uname,$file);
1.712     albertel 10548:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10549: 	($udom,$uname,$file) =
1.811     albertel 10550: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10551: 	$file = 'userfiles/'.$file;
                   10552:     }
                   10553:     if ($uri =~ m-^/res/-) {
                   10554: 	($udom,$uname) = 
1.807     albertel 10555: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10556: 	$file = $uri;
                   10557:     }
                   10558: 
                   10559:     if (!$udom || !$uname || !$file) {
                   10560: 	# unable to handle the uri
                   10561: 	return ();
                   10562:     }
1.956     raeburn  10563:     my $getpropath;
                   10564:     if ($file =~ /^userfiles\//) {
                   10565:         $getpropath = 1;
                   10566:     }
1.1136    raeburn  10567:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10568:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10569:         return ();
                   10570:     } else {
                   10571:         if (ref($listref) eq 'ARRAY') {
                   10572:             my @stats = split('&',$listref->[0]);
                   10573: 	    shift(@stats); #filename is first
                   10574: 	    return @stats;
                   10575:         }
1.712     albertel 10576:     }
                   10577:     return ();
                   10578: }
                   10579: 
1.1313    raeburn  10580: # --------------------------------------------------------- recursedirs
                   10581: # Recursive function to traverse either a specific user's Authoring Space
                   10582: # or corresponding Published Resource Space, and populate the hash ref:
                   10583: # $dirhashref with URLs of all directories, and if $filehashref hash
                   10584: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
                   10585: # or .rights files in resource space, and .meta, .save, .log, and .bak
                   10586: # files in Authoring Space.
                   10587: #
                   10588: # Inputs:
                   10589: #
                   10590: # $is_home - true if current server is home server for user's space
                   10591: # $context - either: priv, or res respectively for Authoring or Resource Space.
                   10592: # $docroot - Document root (i.e., /home/httpd/html
                   10593: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
                   10594: # $relpath - Current path (relative to top level).
                   10595: # $dirhashref - reference to hash to populate with URLs of directories (Required)
                   10596: # $filehashref - reference to hash to populate with URLs of files (Optional)
                   10597: #
                   10598: # Returns: nothing
                   10599: #
                   10600: # Side Effects: populates $dirhashref, and $filehashref (if provided).
                   10601: #
                   10602: # Currently used by interface/londocs.pm to create linked select boxes for
                   10603: # directory and filename to import a Course "Author" resource into a course, and
                   10604: # also to create linked select boxes for Authoring Space and Directory to choose
                   10605: # save location for creation of a new "standard" problem from the Course Editor.
                   10606: #
                   10607: 
                   10608: sub recursedirs {
                   10609:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
                   10610:     return unless (ref($dirhashref) eq 'HASH');
                   10611:     my $currpath = $docroot.$toppath;
                   10612:     if ($relpath) {
                   10613:         $currpath .= "/$relpath";
                   10614:     }
                   10615:     my $savefile;
                   10616:     if (ref($filehashref)) {
                   10617:         $savefile = 1;
                   10618:     }
                   10619:     if ($is_home) {
                   10620:         if (opendir(my $dirh,$currpath)) {
                   10621:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
                   10622:                 next if ($item eq '');
                   10623:                 if (-d "$currpath/$item") {
                   10624:                     my $newpath;
                   10625:                     if ($relpath) {
                   10626:                         $newpath = "$relpath/$item";
                   10627:                     } else {
                   10628:                         $newpath = $item;
                   10629:                     }
                   10630:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   10631:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   10632:                 } elsif ($savefile) {
                   10633:                     if ($context eq 'priv') {
                   10634:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   10635:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   10636:                         }
                   10637:                     } else {
                   10638:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
                   10639:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   10640:                         }
                   10641:                     }
                   10642:                 }
                   10643:             }
                   10644:             closedir($dirh);
                   10645:         }
                   10646:     } else {
                   10647:         my ($dirlistref,$listerror) =
                   10648:             &dirlist($toppath.$relpath);
                   10649:         my @dir_lines;
                   10650:         my $dirptr=16384;
                   10651:         if (ref($dirlistref) eq 'ARRAY') {
                   10652:             foreach my $dir_line (sort
                   10653:                               {
                   10654:                                   my ($afile)=split('&',$a,2);
                   10655:                                   my ($bfile)=split('&',$b,2);
                   10656:                                   return (lc($afile) cmp lc($bfile));
                   10657:                               } (@{$dirlistref})) {
                   10658:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
                   10659:                     split(/\&/,$dir_line,16);
                   10660:                 $item =~ s/\s+$//;
                   10661:                 next if (($item =~ /^\.\.?$/) || ($obs));
                   10662:                 if ($dirptr&$testdir) {
                   10663:                     my $newpath;
                   10664:                     if ($relpath) {
                   10665:                         $newpath = "$relpath/$item";
                   10666:                     } else {
                   10667:                         $relpath = '/';
                   10668:                         $newpath = $item;
                   10669:                     }
                   10670:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   10671:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   10672:                 } elsif ($savefile) {
                   10673:                     if ($context eq 'priv') {
                   10674:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   10675:                             $filehashref->{$relpath}{$item} = 1;
                   10676:                         }
                   10677:                     } else {
                   10678:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
                   10679:                             $filehashref->{$relpath}{$item} = 1;
                   10680:                         }
                   10681:                     }
                   10682:                 }
                   10683:             }
                   10684:         }
                   10685:     }
                   10686:     return;
                   10687: }
                   10688: 
1.26      www      10689: # -------------------------------------------------------- Value of a Condition
                   10690: 
1.713     albertel 10691: # gets the value of a specific preevaluated condition
                   10692: #    stored in the string  $env{user.state.<cid>}
                   10693: # or looks up a condition reference in the bighash and if if hasn't
                   10694: # already been evaluated recurses into docondval to get the value of
                   10695: # the condition, then memoizing it to 
                   10696: #   $env{user.state.<cid>.<condition>}
1.40      www      10697: sub directcondval {
                   10698:     my $number=shift;
1.620     albertel 10699:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 10700: 	&Apache::lonuserstate::evalstate();
                   10701:     }
1.713     albertel 10702:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   10703: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   10704:     } elsif ($number =~ /^_/) {
                   10705: 	my $sub_condition;
                   10706: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10707: 		&GDBM_READER(),0640)) {
                   10708: 	    $sub_condition=$bighash{'conditions'.$number};
                   10709: 	    untie(%bighash);
                   10710: 	}
                   10711: 	my $value = &docondval($sub_condition);
1.949     raeburn  10712: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 10713: 	return $value;
                   10714:     }
1.620     albertel 10715:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   10716:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      10717:     } else {
                   10718:        return 2;
                   10719:     }
                   10720: }
                   10721: 
1.713     albertel 10722: # get the collection of conditions for this resource
1.26      www      10723: sub condval {
                   10724:     my $condidx=shift;
1.54      www      10725:     my $allpathcond='';
1.713     albertel 10726:     foreach my $cond (split(/\|/,$condidx)) {
                   10727: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   10728: 	    $allpathcond.=
                   10729: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   10730: 	}
1.191     harris41 10731:     }
1.54      www      10732:     $allpathcond=~s/\|$//;
1.713     albertel 10733:     return &docondval($allpathcond);
                   10734: }
                   10735: 
                   10736: #evaluates an expression of conditions
                   10737: sub docondval {
                   10738:     my ($allpathcond) = @_;
                   10739:     my $result=0;
                   10740:     if ($env{'request.course.id'}
                   10741: 	&& defined($allpathcond)) {
                   10742: 	my $operand='|';
                   10743: 	my @stack;
                   10744: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   10745: 	    if ($chunk eq '(') {
                   10746: 		push @stack,($operand,$result);
                   10747: 	    } elsif ($chunk eq ')') {
                   10748: 		my $before=pop @stack;
                   10749: 		if (pop @stack eq '&') {
                   10750: 		    $result=$result>$before?$before:$result;
                   10751: 		} else {
                   10752: 		    $result=$result>$before?$result:$before;
                   10753: 		}
                   10754: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   10755: 		$operand=$chunk;
                   10756: 	    } else {
                   10757: 		my $new=directcondval($chunk);
                   10758: 		if ($operand eq '&') {
                   10759: 		    $result=$result>$new?$new:$result;
                   10760: 		} else {
                   10761: 		    $result=$result>$new?$result:$new;
                   10762: 		}
                   10763: 	    }
                   10764: 	}
1.26      www      10765:     }
                   10766:     return $result;
1.421     albertel 10767: }
                   10768: 
                   10769: # ---------------------------------------------------- Devalidate courseresdata
                   10770: 
                   10771: sub devalidatecourseresdata {
                   10772:     my ($coursenum,$coursedomain)=@_;
                   10773:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10774:     &devalidate_cache_new('courseres',$hashid);
1.28      www      10775: }
                   10776: 
1.763     www      10777: 
1.200     www      10778: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     10779: #
                   10780: #  Parameters:
                   10781: #      $coursenum    - Number of the course.
                   10782: #      $coursedomain - Domain at which the course was created.
                   10783: #  Returns:
                   10784: #     A hash of the course parameters along (I think) with timestamps
                   10785: #     and version info.
1.877     foxr     10786: 
1.624     albertel 10787: sub get_courseresdata {
                   10788:     my ($coursenum,$coursedomain)=@_;
1.200     www      10789:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   10790:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10791:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 10792:     my %dumpreply;
1.417     albertel 10793:     unless (defined($cached)) {
1.624     albertel 10794: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 10795: 	$result=\%dumpreply;
1.251     albertel 10796: 	my ($tmp) = keys(%dumpreply);
                   10797: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 10798: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 10799: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   10800: 	    return $tmp;
1.416     albertel 10801: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 10802: 	    $result=undef;
1.599     albertel 10803: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 10804: 	}
                   10805:     }
1.624     albertel 10806:     return $result;
                   10807: }
                   10808: 
1.633     albertel 10809: sub devalidateuserresdata {
                   10810:     my ($uname,$udom)=@_;
                   10811:     my $hashid="$udom:$uname";
                   10812:     &devalidate_cache_new('userres',$hashid);
                   10813: }
                   10814: 
1.624     albertel 10815: sub get_userresdata {
                   10816:     my ($uname,$udom)=@_;
                   10817:     #most student don\'t have any data set, check if there is some data
                   10818:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   10819: 
                   10820:     my $hashid="$udom:$uname";
                   10821:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   10822:     if (!defined($cached)) {
                   10823: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   10824: 	$result=\%resourcedata;
                   10825: 	&do_cache_new('userres',$hashid,$result,600);
                   10826:     }
                   10827:     my ($tmp)=keys(%$result);
                   10828:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   10829: 	return $result;
                   10830:     }
                   10831:     #error 2 occurs when the .db doesn't exist
                   10832:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  10833:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   10834: 	    &logthis("<font color=\"blue\">WARNING:".
                   10835: 		     " Trying to get resource data for ".
                   10836: 		     $uname." at ".$udom.": ".
                   10837: 		     $tmp."</font>");
                   10838:         }
1.624     albertel 10839:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 10840: 	#&EXT_cache_set($udom,$uname);
                   10841: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 10842: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 10843:     }
                   10844:     return $tmp;
                   10845: }
1.879     foxr     10846: #----------------------------------------------- resdata - return resource data
                   10847: #  Purpose:
                   10848: #    Return resource data for either users or for a course.
                   10849: #  Parameters:
                   10850: #     $name      - Course/user name.
                   10851: #     $domain    - Name of the domain the user/course is registered on.
1.1311    raeburn  10852: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  10853: #     $mapp      - decluttered URL of enclosing map  
                   10854: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   10855: #     $recurseup - Ref to array of map URLs, starting with map containing
                   10856: #                  $mapp up through hierarchy of nested maps to top level map.  
                   10857: #     $courseid  - CourseID (first part of param identifier).
                   10858: #     $modifier  - Middle part of param identifier.
                   10859: #     $what      - Last part of param identifier.
1.879     foxr     10860: #     @which     - Array of names of resources desired.
                   10861: #  Returns:
                   10862: #     The value of the first reasource in @which that is found in the
                   10863: #     resource hash.
                   10864: #  Exceptional Conditions:
                   10865: #     If the $type passed in is not valid (not the string 'course' or 
                   10866: #     'user', an undefined  reference is returned.
                   10867: #     If none of the resources are found, an undef is returned
1.624     albertel 10868: sub resdata {
1.1301    raeburn  10869:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   10870:         $modifier,$what,@which)=@_;
1.624     albertel 10871:     my $result;
                   10872:     if ($type eq 'course') {
                   10873: 	$result=&get_courseresdata($name,$domain);
                   10874:     } elsif ($type eq 'user') {
                   10875: 	$result=&get_userresdata($name,$domain);
                   10876:     }
                   10877:     if (!ref($result)) { return $result; }    
1.251     albertel 10878:     foreach my $item (@which) {
1.1301    raeburn  10879:         if ($item->[1] eq 'course') {
                   10880:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   10881:                 unless ($$recursed) {
1.1302    raeburn  10882:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  10883:                     $$recursed = 1;
                   10884:                 }
                   10885:                 foreach my $item (@${recurseup}) {
                   10886:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   10887:                     last if (defined($result->{$norecursechk}));
                   10888:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   10889:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   10890:                 }
                   10891:             }
                   10892:         }
                   10893:         if (defined($result->{$item->[0]})) {
1.927     albertel 10894: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 10895: 	}
1.250     albertel 10896:     }
1.291     albertel 10897:     return undef;
1.200     www      10898: }
                   10899: 
1.1298    raeburn  10900: sub get_domain_ltitools {
                   10901:     my ($cdom) = @_;
                   10902:     my %ltitools;
                   10903:     my ($result,$cached)=&is_cached_new('ltitools',$cdom);
                   10904:     if (defined($cached)) {
                   10905:         if (ref($result) eq 'HASH') {
                   10906:             %ltitools = %{$result};
                   10907:         }
                   10908:     } else {
                   10909:         my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
                   10910:         if (ref($domconfig{'ltitools'}) eq 'HASH') {
                   10911:             %ltitools = %{$domconfig{'ltitools'}};
                   10912:         }
                   10913:         my $cachetime = 24*60*60;
                   10914:         &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
                   10915:     }
                   10916:     return %ltitools;
                   10917: }
                   10918: 
1.1236    raeburn  10919: sub get_numsuppfiles {
                   10920:     my ($cnum,$cdom,$ignorecache)=@_;
                   10921:     my $hashid=$cnum.':'.$cdom;
                   10922:     my ($suppcount,$cached);
                   10923:     unless ($ignorecache) {
                   10924:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   10925:     }
                   10926:     unless (defined($cached)) {
                   10927:         my $chome=&homeserver($cnum,$cdom);
                   10928:         unless ($chome eq 'no_host') {
                   10929:             ($suppcount,my $errors) = (0,0);
                   10930:             my $suppmap = 'supplemental.sequence';
                   10931:             ($suppcount,$errors) = 
                   10932:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   10933:         }
                   10934:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   10935:     }
                   10936:     return $suppcount;
                   10937: }
                   10938: 
1.379     matthew  10939: #
                   10940: # EXT resource caching routines
                   10941: #
                   10942: 
1.1302    raeburn  10943: {
                   10944: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   10945: #
                   10946: # The course for which we cache
                   10947: my $cachedmapkey='';
                   10948: # The cached recursive maps for this course
                   10949: my %cachedmaps=();
                   10950: # When this was last done
                   10951: my $cachedmaptime='';
                   10952: 
1.379     matthew  10953: sub clear_EXT_cache_status {
1.383     albertel 10954:     &delenv('cache.EXT.');
1.379     matthew  10955: }
                   10956: 
                   10957: sub EXT_cache_status {
                   10958:     my ($target_domain,$target_user) = @_;
1.383     albertel 10959:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 10960:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  10961:         # We know already the user has no data
                   10962:         return 1;
                   10963:     } else {
                   10964:         return 0;
                   10965:     }
                   10966: }
                   10967: 
                   10968: sub EXT_cache_set {
                   10969:     my ($target_domain,$target_user) = @_;
1.383     albertel 10970:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  10971:     #&appenv({$cachename => time});
1.379     matthew  10972: }
                   10973: 
1.28      www      10974: # --------------------------------------------------------- Value of a Variable
1.58      www      10975: sub EXT {
1.715     albertel 10976: 
1.1228    raeburn  10977:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      10978:     unless ($varname) { return ''; }
1.218     albertel 10979:     #get real user name/domain, courseid and symb
                   10980:     my $courseid;
1.359     albertel 10981:     my $publicuser;
1.427     www      10982:     if ($symbparm) {
                   10983: 	$symbparm=&get_symb_from_alias($symbparm);
                   10984:     }
1.218     albertel 10985:     if (!($uname && $udom)) {
1.790     albertel 10986:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 10987:       if (!$symbparm) {	$symbparm=$cursymb; }
                   10988:     } else {
1.620     albertel 10989: 	$courseid=$env{'request.course.id'};
1.218     albertel 10990:     }
1.48      www      10991:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   10992:     my $rest;
1.320     albertel 10993:     if (defined($therest[0])) {
1.48      www      10994:        $rest=join('.',@therest);
                   10995:     } else {
                   10996:        $rest='';
                   10997:     }
1.320     albertel 10998: 
1.57      www      10999:     my $qualifierrest=$qualifier;
                   11000:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11001:     my $spacequalifierrest=$space;
                   11002:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11003:     if ($realm eq 'user') {
1.48      www      11004: # --------------------------------------------------------------- user.resource
                   11005: 	if ($space eq 'resource') {
1.651     albertel 11006: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11007: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11008: 		 &&
1.744     albertel 11009: 		 ($symbparm eq &symbread()) ) {	
                   11010: 		# if we are in the middle of processing the resource the
                   11011: 		# get the value we are planning on committing
                   11012:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11013:                     return $Apache::lonhomework::results{$qualifierrest};
                   11014:                 } else {
                   11015:                     return $Apache::lonhomework::history{$qualifierrest};
                   11016:                 }
1.335     albertel 11017: 	    } else {
1.359     albertel 11018: 		my %restored;
1.620     albertel 11019: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11020: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11021: 		} else {
                   11022: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11023: 		}
1.335     albertel 11024: 		return $restored{$qualifierrest};
                   11025: 	    }
1.48      www      11026: # ----------------------------------------------------------------- user.access
                   11027:         } elsif ($space eq 'access') {
1.218     albertel 11028: 	    # FIXME - not supporting calls for a specific user
1.48      www      11029:             return &allowed($qualifier,$rest);
                   11030: # ------------------------------------------ user.preferences, user.environment
                   11031:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11032: 	    if (($uname eq $env{'user.name'}) &&
                   11033: 		($udom eq $env{'user.domain'})) {
                   11034: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11035: 	    } else {
1.359     albertel 11036: 		my %returnhash;
                   11037: 		if (!$publicuser) {
                   11038: 		    %returnhash=&userenvironment($udom,$uname,
                   11039: 						 $qualifierrest);
                   11040: 		}
1.218     albertel 11041: 		return $returnhash{$qualifierrest};
                   11042: 	    }
1.48      www      11043: # ----------------------------------------------------------------- user.course
                   11044:         } elsif ($space eq 'course') {
1.218     albertel 11045: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11046:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11047: # ------------------------------------------------------------------- user.role
                   11048:         } elsif ($space eq 'role') {
1.218     albertel 11049: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11050:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11051:             if ($qualifier eq 'value') {
                   11052: 		return $role;
                   11053:             } elsif ($qualifier eq 'extent') {
                   11054:                 return $where;
                   11055:             }
                   11056: # ----------------------------------------------------------------- user.domain
                   11057:         } elsif ($space eq 'domain') {
1.218     albertel 11058:             return $udom;
1.48      www      11059: # ------------------------------------------------------------------- user.name
                   11060:         } elsif ($space eq 'name') {
1.218     albertel 11061:             return $uname;
1.48      www      11062: # ---------------------------------------------------- Any other user namespace
1.29      www      11063:         } else {
1.359     albertel 11064: 	    my %reply;
                   11065: 	    if (!$publicuser) {
                   11066: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11067: 	    }
                   11068: 	    return $reply{$qualifierrest};
1.48      www      11069:         }
1.236     www      11070:     } elsif ($realm eq 'query') {
                   11071: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11072:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11073: 						[$spacequalifierrest]);
1.620     albertel 11074: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11075:    } elsif ($realm eq 'request') {
1.48      www      11076: # ------------------------------------------------------------- request.browser
                   11077:         if ($space eq 'browser') {
1.1145    bisitz   11078:             return $env{'browser.'.$qualifier};
1.57      www      11079: # ------------------------------------------------------------ request.filename
                   11080:         } else {
1.620     albertel 11081:             return $env{'request.'.$spacequalifierrest};
1.29      www      11082:         }
1.28      www      11083:     } elsif ($realm eq 'course') {
1.48      www      11084: # ---------------------------------------------------------- course.description
1.620     albertel 11085:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11086:     } elsif ($realm eq 'resource') {
1.165     www      11087: 
1.620     albertel 11088: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11089: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11090: 	}
1.693     albertel 11091: 
1.1232    raeburn  11092:         if ($qualifier eq '') {
                   11093: 	    if ($space eq 'title') {
                   11094: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11095: 	        return &gettitle($symbparm);
                   11096: 	    }
1.693     albertel 11097: 	
1.1232    raeburn  11098: 	    if ($space eq 'map') {
                   11099: 	        my ($map) = &decode_symb($symbparm);
                   11100: 	        return &symbread($map);
                   11101: 	    }
                   11102:             if ($space eq 'maptitle') {
                   11103:                 my ($map) = &decode_symb($symbparm);
                   11104:                 return &gettitle($map);
                   11105:             }
                   11106: 	    if ($space eq 'filename') {
                   11107: 	        if ($symbparm) {
                   11108: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11109: 	        }
                   11110: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11111: 	    }
1.1232    raeburn  11112: 
1.1233    raeburn  11113:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11114:                 if ($space eq 'visibleparts') {
                   11115:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11116:                     my $item;
                   11117:                     if (ref($navmap)) {
                   11118:                         my $res = $navmap->getBySymb($symbparm);
                   11119:                         my $parts = $res->parts();
                   11120:                         if (ref($parts) eq 'ARRAY') {
                   11121:                             $item = join(',',@{$parts});
                   11122:                         }
                   11123:                         undef($navmap);
1.1232    raeburn  11124:                     }
1.1233    raeburn  11125:                     return $item;
1.1232    raeburn  11126:                 }
                   11127:             }
                   11128:         }
1.693     albertel 11129: 
1.1301    raeburn  11130: 	my ($section, $group, @groups, @recurseup, $recursed);
                   11131: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  11132:         if (($courseid eq '') && ($cid)) {
                   11133:             $courseid = $cid;
                   11134:         }
                   11135: 	if (($symbparm && $courseid) && 
                   11136: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      11137: 
1.218     albertel 11138: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11139: 
1.60      www      11140: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11141: 	    my $symbp=$symbparm;
1.1301    raeburn  11142: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11143: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  11144:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 11145: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 11146: 	    if (($env{'user.name'} eq $uname) &&
                   11147: 		($env{'user.domain'} eq $udom)) {
                   11148: 		$section=$env{'request.course.sec'};
1.733     raeburn  11149:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11150:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11151: 	    } else {
1.539     albertel 11152: 		if (! defined($usection)) {
1.551     albertel 11153: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11154: 		} else {
                   11155: 		    $section = $usection;
                   11156: 		}
1.733     raeburn  11157:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11158: 	    }
                   11159: 
                   11160: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11161: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  11162:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 11163: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11164: 
1.593     albertel 11165: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11166: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  11167:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 11168: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11169: 
1.60      www      11170: # ----------------------------------------------------------- first, check user
1.624     albertel 11171: 
1.1301    raeburn  11172: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   11173:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 11174: 				       ([$courselevelr,'resource'],
                   11175: 					[$courselevelm,'map'     ],
1.1301    raeburn  11176:                                         [$courseleveli,'map'     ],
1.927     albertel 11177: 					[$courselevel, 'course'  ]));
1.931     albertel 11178: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11179: 
1.594     albertel 11180: # ------------------------------------------------ second, check some of course
1.684     raeburn  11181:             my $coursereply;
1.691     raeburn  11182:             if (@groups > 0) {
                   11183:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  11184:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   11185:                                        $mapp,\$recursed,\@recurseup);
                   11186:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  11187:             }
1.96      www      11188: 
1.684     raeburn  11189: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11190: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  11191: 				  'course',$mapp,\$recursed,\@recurseup,
                   11192:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 11193: 				  ([$seclevelr,   'resource'],
                   11194: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  11195:                                    [$secleveli,   'map'     ],
1.927     albertel 11196: 				   [$seclevel,    'course'  ],
                   11197: 				   [$courselevelr,'resource']));
                   11198: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11199: 
1.60      www      11200: # ------------------------------------------------------ third, check map parms
1.218     albertel 11201: 	    my %parmhash=();
                   11202: 	    my $thisparm='';
                   11203: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11204: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11205: 		    &GDBM_READER(),0640)) {
1.218     albertel 11206: 		$thisparm=$parmhash{$symbparm};
                   11207: 		untie(%parmhash);
                   11208: 	    }
1.927     albertel 11209: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11210: 	}
1.594     albertel 11211: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  11212:  
                   11213:         my $what = $spacequalifierrest;
                   11214: 	$what=~s/\./\_/;
1.282     albertel 11215: 	my $filename;
                   11216: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11217: 	if ($symbparm) {
1.409     www      11218: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11219: 	} else {
1.620     albertel 11220: 	    $filename=$env{'request.filename'};
1.282     albertel 11221: 	}
1.1301    raeburn  11222: 	my $metadata=&metadata($filename,$what);
1.927     albertel 11223: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1301    raeburn  11224: 	$metadata=&metadata($filename,'parameter_'.$what);
1.927     albertel 11225: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11226: 
1.1301    raeburn  11227: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 11228: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11229: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11230: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11231: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  11232: 				     'course',$mapp,\$recursed,\@recurseup,
                   11233:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 11234: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  11235:                                       [$courseleveli,'map'   ],
1.927     albertel 11236: 				      [$courselevel, 'course']));
                   11237: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11238: 	}
1.145     www      11239: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11240: 	unless ($space eq '0') {
1.336     albertel 11241: 	    my @parts=split(/_/,$space);
                   11242: 	    my $id=pop(@parts);
                   11243: 	    my $part=join('_',@parts);
                   11244: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11245: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11246: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11247: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11248: 	}
1.395     albertel 11249: 	if ($recurse) { return undef; }
                   11250: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 11251: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11252: # ---------------------------------------------------- Any other user namespace
                   11253:     } elsif ($realm eq 'environment') {
                   11254: # ----------------------------------------------------------------- environment
1.620     albertel 11255: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11256: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11257: 	} else {
1.770     albertel 11258: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11259: 		return '';
                   11260: 	    }
1.219     albertel 11261: 	    my %returnhash=&userenvironment($udom,$uname,
                   11262: 					    $spacequalifierrest);
                   11263: 	    return $returnhash{$spacequalifierrest};
                   11264: 	}
1.28      www      11265:     } elsif ($realm eq 'system') {
1.48      www      11266: # ----------------------------------------------------------------- system.time
                   11267: 	if ($space eq 'time') {
                   11268: 	    return time;
                   11269:         }
1.696     albertel 11270:     } elsif ($realm eq 'server') {
                   11271: # ----------------------------------------------------------------- system.time
                   11272: 	if ($space eq 'name') {
                   11273: 	    return $ENV{'SERVER_NAME'};
                   11274:         }
1.28      www      11275:     }
1.48      www      11276:     return '';
1.61      www      11277: }
                   11278: 
1.927     albertel 11279: sub get_reply {
                   11280:     my ($reply_value) = @_;
1.940     raeburn  11281:     if (ref($reply_value) eq 'ARRAY') {
                   11282:         if (wantarray) {
                   11283: 	    return @$reply_value;
                   11284:         }
                   11285:         return $reply_value->[0];
                   11286:     } else {
                   11287:         return $reply_value;
1.927     albertel 11288:     }
                   11289: }
                   11290: 
1.691     raeburn  11291: sub check_group_parms {
1.1301    raeburn  11292:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   11293:         $recursed,$recurseupref) = @_;
                   11294:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   11295:                   [$what,'course']);
                   11296:     my $coursereply;
1.691     raeburn  11297:     foreach my $group (@{$groups}) {
1.1301    raeburn  11298:         my @groupitems = ();
1.691     raeburn  11299:         foreach my $level (@levels) {
1.927     albertel 11300:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11301:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11302:         }
1.1301    raeburn  11303:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11304:                                    $env{'course.'.$courseid.'.domain'},
                   11305:                                    'course',$mapp,$recursed,$recurseupref,
                   11306:                                    $courseid,'.['.$group.'].',$what,
                   11307:                                    @groupitems);
                   11308:         last if (defined($coursereply));
1.691     raeburn  11309:     }
                   11310:     return $coursereply;
                   11311: }
                   11312: 
1.1301    raeburn  11313: sub get_map_hierarchy {
1.1302    raeburn  11314:     my ($mapname,$courseid) = @_;
                   11315:     my @recurseup = ();
1.1301    raeburn  11316:     if ($mapname) {
1.1302    raeburn  11317:         if (($cachedmapkey eq $courseid) &&
                   11318:             (abs($cachedmaptime-time)<5)) {
                   11319:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   11320:                 return @{$cachedmaps{$mapname}};
                   11321:             }
                   11322:         }
1.1301    raeburn  11323:         my $navmap = Apache::lonnavmaps::navmap->new();
                   11324:         if (ref($navmap)) {
                   11325:             @recurseup = $navmap->recurseup_maps($mapname);
                   11326:             undef($navmap);
1.1302    raeburn  11327:             $cachedmaps{$mapname} = \@recurseup;
                   11328:             $cachedmaptime=time;
                   11329:             $cachedmapkey=$courseid;
1.1301    raeburn  11330:         }
                   11331:     }
                   11332:     return @recurseup;
                   11333: }
                   11334: 
1.1302    raeburn  11335: }
                   11336: 
1.691     raeburn  11337: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11338:     my ($courseid,@groups) = @_;
                   11339:     @groups = sort(@groups);
1.691     raeburn  11340:     return @groups;
                   11341: }
                   11342: 
1.395     albertel 11343: sub packages_tab_default {
                   11344:     my ($uri,$varname)=@_;
                   11345:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11346: 
                   11347:     my (@extension,@specifics,$do_default);
                   11348:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11349: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11350: 	if ($pack_type eq 'default') {
                   11351: 	    $do_default=1;
                   11352: 	} elsif ($pack_type eq 'extension') {
                   11353: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11354: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11355: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11356: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11357: 	}
                   11358:     }
                   11359:     # first look for a package that matches the requested part id
                   11360:     foreach my $package (@specifics) {
                   11361: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11362: 	next if ($pack_part ne $part);
                   11363: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11364: 	    return $packagetab{"$pack_type&$name&default"};
                   11365: 	}
                   11366:     }
                   11367:     # look for any possible matching non extension_ package
                   11368:     foreach my $package (@specifics) {
                   11369: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11370: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11371: 	    return $packagetab{"$pack_type&$name&default"};
                   11372: 	}
1.585     albertel 11373: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11374: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11375: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11376: 	}
                   11377:     }
1.738     albertel 11378:     # look for any posible extension_ match
                   11379:     foreach my $package (@extension) {
                   11380: 	my ($package,$pack_type)=@{$package};
                   11381: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11382: 	    return $packagetab{"$pack_type&$name&default"};
                   11383: 	}
                   11384: 	if (defined($packagetab{$package."&$name&default"})) {
                   11385: 	    return $packagetab{$package."&$name&default"};
                   11386: 	}
                   11387:     }
                   11388:     # look for a global default setting
                   11389:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11390: 	return $packagetab{"default&$name&default"};
                   11391:     }
1.395     albertel 11392:     return undef;
                   11393: }
                   11394: 
1.334     albertel 11395: sub add_prefix_and_part {
                   11396:     my ($prefix,$part)=@_;
                   11397:     my $keyroot;
                   11398:     if (defined($prefix) && $prefix !~ /^__/) {
                   11399: 	# prefix that has a part already
                   11400: 	$keyroot=$prefix;
                   11401:     } elsif (defined($prefix)) {
                   11402: 	# prefix that is missing a part
                   11403: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11404:     } else {
                   11405: 	# no prefix at all
                   11406: 	if (defined($part)) { $keyroot='_'.$part; }
                   11407:     }
                   11408:     return $keyroot;
                   11409: }
                   11410: 
1.71      www      11411: # ---------------------------------------------------------------- Get metadata
                   11412: 
1.599     albertel 11413: my %metaentry;
1.1070    www      11414: my %importedpartids;
1.71      www      11415: sub metadata {
1.176     www      11416:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11417:     $uri=&declutter($uri);
1.288     albertel 11418:     # if it is a non metadata possible uri return quickly
1.529     albertel 11419:     if (($uri eq '') || 
                   11420: 	(($uri =~ m|^/*adm/|) && 
1.1298    raeburn  11421: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|exttools?)$})) ||
1.1108    raeburn  11422:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11423: 	return undef;
                   11424:     }
1.1261    raeburn  11425:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11426: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11427: 	return undef;
1.288     albertel 11428:     }
1.73      www      11429:     my $filename=$uri;
                   11430:     $uri=~s/\.meta$//;
1.172     www      11431: #
                   11432: # Is the metadata already cached?
1.177     www      11433: # Look at timestamp of caching
1.172     www      11434: # Everything is cached by the main uri, libraries are never directly cached
                   11435: #
1.428     albertel 11436:     if (!defined($liburi)) {
1.599     albertel 11437: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11438: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11439:     }
                   11440:     {
1.1069    www      11441: # Imported parts would go here
1.1070    www      11442:         my %importedids=();
                   11443:         my @origfileimportpartids=();
1.1069    www      11444:         my $importedparts=0;
1.172     www      11445: #
                   11446: # Is this a recursive call for a library?
                   11447: #
1.599     albertel 11448: #	if (! exists($metacache{$uri})) {
                   11449: #	    $metacache{$uri}={};
                   11450: #	}
1.924     albertel 11451: 	my $cachetime = 60*60;
1.171     www      11452:         if ($liburi) {
                   11453: 	    $liburi=&declutter($liburi);
                   11454:             $filename=$liburi;
1.401     bowersj2 11455:         } else {
1.599     albertel 11456: 	    &devalidate_cache_new('meta',$uri);
                   11457: 	    undef(%metaentry);
1.401     bowersj2 11458: 	}
1.140     www      11459:         my %metathesekeys=();
1.73      www      11460:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11461: 	my $metastring;
1.1140    www      11462: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11463: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11464: 	    $metastring = 
1.929     albertel 11465: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11466: 					  ('grade_target' => 'meta'));
                   11467: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11468: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11469:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11470: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11471: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11472: 	    $metastring=&getfile($file);
1.489     albertel 11473: 	}
1.208     albertel 11474:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11475:         my $token;
1.140     www      11476:         undef %metathesekeys;
1.71      www      11477:         while ($token=$parser->get_token) {
1.339     albertel 11478: 	    if ($token->[0] eq 'S') {
                   11479: 		if (defined($token->[2]->{'package'})) {
1.172     www      11480: #
                   11481: # This is a package - get package info
                   11482: #
1.339     albertel 11483: 		    my $package=$token->[2]->{'package'};
                   11484: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11485: 		    if (defined($token->[2]->{'id'})) { 
                   11486: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11487: 		    }
1.599     albertel 11488: 		    if ($metaentry{':packages'}) {
                   11489: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11490: 		    } else {
1.599     albertel 11491: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11492: 		    }
1.736     albertel 11493: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11494: 			my $part=$keyroot;
                   11495: 			$part=~s/^\_//;
1.736     albertel 11496: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11497: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11498: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11499: 			    # ignore package.tab specified default values
                   11500:                             # here &package_tab_default() will fetch those
                   11501: 			    if ($subp eq 'default') { next; }
1.736     albertel 11502: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11503: 			    my $unikey;
                   11504: 			    if ($pack =~ /_0$/) {
                   11505: 				$unikey='parameter_0_'.$name;
                   11506: 				$part=0;
                   11507: 			    } else {
                   11508: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11509: 			    }
1.339     albertel 11510: 			    if ($subp eq 'display') {
                   11511: 				$value.=' [Part: '.$part.']';
                   11512: 			    }
1.599     albertel 11513: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11514: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11515: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11516: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11517: 			    }
1.599     albertel 11518: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11519: 				$metaentry{':'.$unikey}=
                   11520: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11521: 			    }
1.339     albertel 11522: 			}
                   11523: 		    }
                   11524: 		} else {
1.172     www      11525: #
                   11526: # This is not a package - some other kind of start tag
1.339     albertel 11527: #
                   11528: 		    my $entry=$token->[1];
1.1068    www      11529: 		    my $unikey='';
1.175     www      11530: 
1.339     albertel 11531: 		    if ($entry eq 'import') {
1.175     www      11532: #
                   11533: # Importing a library here
1.339     albertel 11534: #
1.1067    www      11535:                         my $location=$parser->get_text('/import');
                   11536:                         my $dir=$filename;
                   11537:                         $dir=~s|[^/]*$||;
                   11538:                         $location=&filelocation($dir,$location);
1.1069    www      11539:                        
1.1068    www      11540:                         my $importmode=$token->[2]->{'importmode'};
                   11541:                         if ($importmode eq 'problem') {
1.1069    www      11542: # Import as problem/response
1.1068    www      11543:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11544:                         } elsif ($importmode eq 'part') {
                   11545: # Import as part(s)
1.1069    www      11546:                            $importedparts=1;
                   11547: # We need to get the original file and the imported file to get the part order correct
                   11548: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   11549: # Load and inspect original file
1.1070    www      11550:                            if ($#origfileimportpartids<0) {
                   11551:                               undef(%importedpartids);
                   11552:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11553:                               my $origfile=&getfile($origfilelocation);
                   11554:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11555:                            }
                   11556: 
1.1069    www      11557: # Load and inspect imported file
                   11558:                            my $impfile=&getfile($location);
                   11559:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11560:                            if ($#impfilepartids>=0) {
                   11561: # This problem had parts
1.1070    www      11562:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11563:                            } else {
                   11564: # Importing by turning a single problem into a problem part
                   11565: # It gets the import-tags ID as part-ID
                   11566:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11567:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11568:                            }
1.1068    www      11569:                         } else {
                   11570: # Normal import
                   11571:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11572:                            if (defined($token->[2]->{'id'})) {
                   11573:                               $unikey.='_'.$token->[2]->{'id'};
                   11574:                            }
1.1067    www      11575:                         }
                   11576: 
1.339     albertel 11577: 			if ($depthcount<20) {
1.736     albertel 11578: 			    my $metadata = 
                   11579: 				&metadata($uri,'keys', $location,$unikey,
                   11580: 					  $depthcount+1);
                   11581: 			    foreach my $meta (split(',',$metadata)) {
                   11582: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   11583: 				$metathesekeys{$meta}=1;
1.339     albertel 11584: 			    }
1.1068    www      11585: 			
                   11586:                         }
1.1067    www      11587: 		    } else {
                   11588: #
                   11589: # Not importing, some other kind of non-package, non-library start tag
                   11590: # 
                   11591:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11592:                         if (defined($token->[2]->{'id'})) {
                   11593:                             $unikey.='_'.$token->[2]->{'id'};
                   11594:                         }
1.339     albertel 11595: 			if (defined($token->[2]->{'name'})) { 
                   11596: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   11597: 			}
                   11598: 			$metathesekeys{$unikey}=1;
1.736     albertel 11599: 			foreach my $param (@{$token->[3]}) {
                   11600: 			    $metaentry{':'.$unikey.'.'.$param} =
                   11601: 				$token->[2]->{$param};
1.339     albertel 11602: 			}
                   11603: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 11604: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 11605: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   11606: 		 # only ws inside the tag, and not in default, so use default
                   11607: 		 # as value
1.599     albertel 11608: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 11609: 			} elsif ( $internaltext =~ /\S/ ) {
                   11610: 		  # something interesting inside the tag
                   11611: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 11612: 			} else {
1.908     albertel 11613: 		  # no interesting values, don't set a default
1.339     albertel 11614: 			}
1.172     www      11615: # end of not-a-package not-a-library import
1.339     albertel 11616: 		    }
1.172     www      11617: # end of not-a-package start tag
1.339     albertel 11618: 		}
1.172     www      11619: # the next is the end of "start tag"
1.339     albertel 11620: 	    }
                   11621: 	}
1.483     albertel 11622: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 11623: 	$extension = lc($extension);
                   11624: 	if ($extension eq 'htm') { $extension='html'; }
                   11625: 
1.737     albertel 11626: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 11627: 	    #no specific packages #how's our extension
                   11628: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 11629: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 11630: 					 \%metathesekeys);
                   11631: 	}
1.883     albertel 11632: 
                   11633: 	if (!exists($metaentry{':packages'})
                   11634: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 11635: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 11636: 		#no specific packages well let's get default then
                   11637: 		if ($key!~/^default&/) { next; }
1.488     albertel 11638: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 11639: 					     \%metathesekeys);
                   11640: 	    }
                   11641: 	}
1.338     www      11642: # are there custom rights to evaluate
1.599     albertel 11643: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 11644: 
1.338     www      11645:     #
                   11646:     # Importing a rights file here
1.339     albertel 11647:     #
                   11648: 	    unless ($depthcount) {
1.599     albertel 11649: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 11650: 		my $dir=$filename;
                   11651: 		$dir=~s|[^/]*$||;
                   11652: 		$location=&filelocation($dir,$location);
1.736     albertel 11653: 		my $rights_metadata =
                   11654: 		    &metadata($uri,'keys',$location,'_rights',
                   11655: 			      $depthcount+1);
                   11656: 		foreach my $rights (split(',',$rights_metadata)) {
                   11657: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   11658: 		    $metathesekeys{$rights}=1;
1.339     albertel 11659: 		}
                   11660: 	    }
                   11661: 	}
1.737     albertel 11662: 	# uniqifiy package listing
                   11663: 	my %seen;
                   11664: 	my @uniq_packages =
                   11665: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   11666: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   11667: 
1.1070    www      11668:         if ($importedparts) {
                   11669: # We had imported parts and need to rebuild partorder
                   11670:            $metaentry{':partorder'}='';
                   11671:            $metathesekeys{'partorder'}=1;
                   11672:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   11673:                if ($origfileimportpartids[$index] eq 'part') {
                   11674: # original part, part of the problem
                   11675:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   11676:                } else {
                   11677: # we have imported parts at this position
                   11678:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   11679:                }
                   11680:            }
                   11681:            $metaentry{':partorder'}=~s/^\,//;
                   11682:         }
                   11683: 
1.737     albertel 11684: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 11685: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  11686: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 11687: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      11688: # this is the end of "was not already recently cached
1.71      www      11689:     }
1.599     albertel 11690:     return $metaentry{':'.$what};
1.261     albertel 11691: }
                   11692: 
1.488     albertel 11693: sub metadata_create_package_def {
1.483     albertel 11694:     my ($uri,$key,$package,$metathesekeys)=@_;
                   11695:     my ($pack,$name,$subp)=split(/\&/,$key);
                   11696:     if ($subp eq 'default') { next; }
                   11697:     
1.599     albertel 11698:     if (defined($metaentry{':packages'})) {
                   11699: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 11700:     } else {
1.599     albertel 11701: 	$metaentry{':packages'}=$package;
1.483     albertel 11702:     }
                   11703:     my $value=$packagetab{$key};
                   11704:     my $unikey;
                   11705:     $unikey='parameter_0_'.$name;
1.599     albertel 11706:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 11707:     $$metathesekeys{$unikey}=1;
1.599     albertel 11708:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11709: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 11710:     }
1.599     albertel 11711:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   11712: 	$metaentry{':'.$unikey}=
                   11713: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 11714:     }
                   11715: }
                   11716: 
1.261     albertel 11717: sub metadata_generate_part0 {
                   11718:     my ($metadata,$metacache,$uri) = @_;
                   11719:     my %allnames;
1.737     albertel 11720:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 11721: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 11722: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   11723: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 11724: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 11725: 	    $allnames{$name}=$part;
                   11726: 	  }
                   11727: 	}
                   11728:     }
                   11729:     foreach my $name (keys(%allnames)) {
                   11730:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 11731:       my $key=":parameter_0_$name";
1.261     albertel 11732:       $$metacache{"$key.part"}='0';
                   11733:       $$metacache{"$key.name"}=$name;
1.428     albertel 11734:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 11735: 					   $allnames{$name}.'_'.$name.
                   11736: 					   '.type'};
1.428     albertel 11737:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 11738: 			     '.display'};
1.644     www      11739:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 11740:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 11741:       $$metacache{"$key.display"}=$olddis;
                   11742:     }
1.71      www      11743: }
                   11744: 
1.764     albertel 11745: # ------------------------------------------------------ Devalidate title cache
                   11746: 
                   11747: sub devalidate_title_cache {
                   11748:     my ($url)=@_;
                   11749:     if (!$env{'request.course.id'}) { return; }
                   11750:     my $symb=&symbread($url);
                   11751:     if (!$symb) { return; }
                   11752:     my $key=$env{'request.course.id'}."\0".$symb;
                   11753:     &devalidate_cache_new('title',$key);
                   11754: }
                   11755: 
1.1014    droeschl 11756: # ------------------------------------------------- Get the title of a course
                   11757: 
                   11758: sub current_course_title {
                   11759:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   11760: }
1.301     www      11761: # ------------------------------------------------- Get the title of a resource
                   11762: 
                   11763: sub gettitle {
                   11764:     my $urlsymb=shift;
                   11765:     my $symb=&symbread($urlsymb);
1.534     albertel 11766:     if ($symb) {
1.620     albertel 11767: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 11768: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 11769: 	if (defined($cached)) { 
                   11770: 	    return $result;
                   11771: 	}
1.534     albertel 11772: 	my ($map,$resid,$url)=&decode_symb($symb);
                   11773: 	my $title='';
1.907     albertel 11774: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   11775: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   11776: 	} else {
                   11777: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11778: 		    &GDBM_READER(),0640)) {
                   11779: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   11780: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   11781: 		untie(%bighash);
                   11782: 	    }
1.534     albertel 11783: 	}
                   11784: 	$title=~s/\&colon\;/\:/gs;
                   11785: 	if ($title) {
1.1159    www      11786: # Remember both $symb and $title for dynamic metadata
                   11787:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      11788:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      11789: # Cache this title and then return it
1.599     albertel 11790: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 11791: 	}
                   11792: 	$urlsymb=$url;
                   11793:     }
                   11794:     my $title=&metadata($urlsymb,'title');
                   11795:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   11796:     return $title;
1.301     www      11797: }
1.613     albertel 11798: 
1.614     albertel 11799: sub get_slot {
                   11800:     my ($which,$cnum,$cdom)=@_;
                   11801:     if (!$cnum || !$cdom) {
1.790     albertel 11802: 	(undef,my $courseid)=&whichuser();
1.620     albertel 11803: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   11804: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 11805:     }
1.703     albertel 11806:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   11807:     my %slotinfo;
                   11808:     if (exists($remembered{$key})) {
                   11809: 	$slotinfo{$which} = $remembered{$key};
                   11810:     } else {
                   11811: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   11812: 	&Apache::lonhomework::showhash(%slotinfo);
                   11813: 	my ($tmp)=keys(%slotinfo);
                   11814: 	if ($tmp=~/^error:/) { return (); }
                   11815: 	$remembered{$key} = $slotinfo{$which};
                   11816:     }
1.616     albertel 11817:     if (ref($slotinfo{$which}) eq 'HASH') {
                   11818: 	return %{$slotinfo{$which}};
                   11819:     }
                   11820:     return $slotinfo{$which};
1.614     albertel 11821: }
1.1150    raeburn  11822: 
                   11823: sub get_reservable_slots {
                   11824:     my ($cnum,$cdom,$uname,$udom) = @_;
                   11825:     my $now = time;
                   11826:     my $reservable_info;
                   11827:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   11828:     if (exists($remembered{$key})) {
                   11829:         $reservable_info = $remembered{$key};
                   11830:     } else {
                   11831:         my %resv;
                   11832:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   11833:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   11834:         $reservable_info = \%resv;
                   11835:         $remembered{$key} = $reservable_info;
                   11836:     }
                   11837:     return $reservable_info;
                   11838: }
                   11839: 
                   11840: sub get_course_slots {
                   11841:     my ($cnum,$cdom) = @_;
                   11842:     my $hashid=$cnum.':'.$cdom;
                   11843:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   11844:     if (defined($cached)) {
                   11845:         if (ref($result) eq 'HASH') {
                   11846:             return %{$result};
                   11847:         }
                   11848:     } else {
                   11849:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   11850:         my ($tmp) = keys(%slots);
                   11851:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  11852:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  11853:             return %slots;
                   11854:         }
                   11855:     }
                   11856:     return;
                   11857: }
                   11858: 
                   11859: sub devalidate_slots_cache {
                   11860:     my ($cnum,$cdom)=@_;
                   11861:     my $hashid=$cnum.':'.$cdom;
                   11862:     &devalidate_cache_new('allslots',$hashid);
                   11863: }
                   11864: 
1.1181    raeburn  11865: sub get_coursechange {
                   11866:     my ($cdom,$cnum) = @_;
                   11867:     if ($cdom eq '' || $cnum eq '') {
                   11868:         return unless ($env{'request.course.id'});
                   11869:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   11870:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11871:     }
                   11872:     my $hashid=$cdom.'_'.$cnum;
                   11873:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   11874:     if ((defined($cached)) && ($change ne '')) {
                   11875:         return $change;
                   11876:     } else {
                   11877:         my %crshash;
                   11878:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   11879:         if ($crshash{'internal.contentchange'} eq '') {
                   11880:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   11881:             if ($change eq '') {
                   11882:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   11883:                 $change = $crshash{'internal.created'};
                   11884:             }
                   11885:         } else {
                   11886:             $change = $crshash{'internal.contentchange'};
                   11887:         }
                   11888:         my $cachetime = 600;
                   11889:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   11890:     }
                   11891:     return $change;
                   11892: }
                   11893: 
                   11894: sub devalidate_coursechange_cache {
                   11895:     my ($cnum,$cdom)=@_;
                   11896:     my $hashid=$cnum.':'.$cdom;
                   11897:     &devalidate_cache_new('crschange',$hashid);
                   11898: }
                   11899: 
1.31      www      11900: # ------------------------------------------------- Update symbolic store links
                   11901: 
                   11902: sub symblist {
                   11903:     my ($mapname,%newhash)=@_;
1.438     www      11904:     $mapname=&deversion(&declutter($mapname));
1.31      www      11905:     my %hash;
1.620     albertel 11906:     if (($env{'request.course.fn'}) && (%newhash)) {
                   11907:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11908:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  11909: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 11910: 		next if ($url eq 'last_known'
                   11911: 			 && $env{'form.no_update_last_known'});
                   11912: 		$hash{declutter($url)}=&encode_symb($mapname,
                   11913: 						    $newhash{$url}->[1],
                   11914: 						    $newhash{$url}->[0]);
1.191     harris41 11915:             }
1.31      www      11916:             if (untie(%hash)) {
                   11917: 		return 'ok';
                   11918:             }
                   11919:         }
                   11920:     }
                   11921:     return 'error';
1.212     www      11922: }
                   11923: 
                   11924: # --------------------------------------------------------------- Verify a symb
                   11925: 
                   11926: sub symbverify {
1.1190    raeburn  11927:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      11928:     my $thisfn=$thisurl;
1.439     www      11929:     $thisfn=&declutter($thisfn);
1.215     www      11930: # direct jump to resource in page or to a sequence - will construct own symbs
                   11931:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   11932: # check URL part
1.409     www      11933:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      11934: 
1.431     www      11935:     unless ($url eq $thisfn) { return 0; }
1.213     www      11936: 
1.216     www      11937:     $symb=&symbclean($symb);
1.510     www      11938:     $thisurl=&deversion($thisurl);
1.439     www      11939:     $thisfn=&deversion($thisfn);
1.213     www      11940: 
                   11941:     my %bighash;
                   11942:     my $okay=0;
1.431     www      11943: 
1.620     albertel 11944:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11945:                             &GDBM_READER(),0640)) {
1.1204    raeburn  11946:         my $noclutter;
1.1032    raeburn  11947:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   11948:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  11949:             if ($map =~ m{^uploaded/.+\.page$}) {
                   11950:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   11951:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   11952:                 $noclutter = 1;
                   11953:             }
                   11954:         }
                   11955:         my $ids;
                   11956:         if ($noclutter) {
                   11957:             $ids=$bighash{'ids_'.$thisurl};
                   11958:         } else {
                   11959:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  11960:         }
1.1102    raeburn  11961:         unless ($ids) {
                   11962:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   11963:             $ids=$bighash{$idkey};
1.216     www      11964:         }
                   11965:         if ($ids) {
                   11966: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  11967:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  11968:                 $symb =~ s/\?.+$//;
1.1202    raeburn  11969:             }
1.800     albertel 11970: 	    foreach my $id (split(/\,/,$ids)) {
                   11971: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      11972:                if (
                   11973:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  11974:    eq $symb) {
                   11975:                    if (ref($encstate)) {
                   11976:                        $$encstate = $bighash{'encrypted_'.$id};
                   11977:                    }
1.620     albertel 11978: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  11979: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   11980:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  11981: 		       $okay=1;
1.1202    raeburn  11982:                        last;
1.582     albertel 11983: 		   }
                   11984: 	       }
1.216     www      11985: 	   }
                   11986:         }
1.213     www      11987: 	untie(%bighash);
                   11988:     }
                   11989:     return $okay;
1.31      www      11990: }
                   11991: 
1.210     www      11992: # --------------------------------------------------------------- Clean-up symb
                   11993: 
                   11994: sub symbclean {
                   11995:     my $symb=shift;
1.568     albertel 11996:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      11997: # remove version from map
                   11998:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      11999: 
1.210     www      12000: # remove version from URL
                   12001:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12002: 
1.507     www      12003: # remove wrapper
                   12004: 
1.510     www      12005:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12006:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12007:     return $symb;
1.409     www      12008: }
                   12009: 
                   12010: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12011: 
                   12012: sub encode_symb {
                   12013:     my ($map,$resid,$url)=@_;
                   12014:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12015: }
1.409     www      12016: 
                   12017: sub decode_symb {
1.568     albertel 12018:     my $symb=shift;
                   12019:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12020:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12021:     return (&fixversion($map),$resid,&fixversion($url));
                   12022: }
                   12023: 
                   12024: sub fixversion {
                   12025:     my $fn=shift;
1.609     banghart 12026:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12027:     my %bighash;
                   12028:     my $uri=&clutter($fn);
1.620     albertel 12029:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12030: # is this cached?
1.599     albertel 12031:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12032:     if (defined($cached)) { return $result; }
                   12033: # unfortunately not cached, or expired
1.620     albertel 12034:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12035: 	    &GDBM_READER(),0640)) {
                   12036:  	if ($bighash{'version_'.$uri}) {
                   12037:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12038:  	    unless (($version eq 'mostrecent') || 
                   12039: 		    ($version==&getversion($uri))) {
1.440     www      12040:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12041:  	    }
                   12042:  	}
                   12043:  	untie %bighash;
1.413     www      12044:     }
1.599     albertel 12045:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12046: }
                   12047: 
                   12048: sub deversion {
                   12049:     my $url=shift;
                   12050:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12051:     return $url;
1.210     www      12052: }
                   12053: 
1.31      www      12054: # ------------------------------------------------------ Return symb list entry
                   12055: 
                   12056: sub symbread {
1.1282    raeburn  12057:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265    raeburn  12058:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1282    raeburn  12059:     if (defined($env{$cache_str})) {
                   12060:         if ($ignorecachednull) {
                   12061:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12062:         } else {
                   12063:             return $env{$cache_str};
                   12064:         }
                   12065:     }
1.242     www      12066: # no filename provided? try from environment
1.1265    raeburn  12067:     unless ($thisfn) {
1.620     albertel 12068:         if ($env{'request.symb'}) {
                   12069: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 12070: 	}
1.620     albertel 12071: 	$thisfn=$env{'request.filename'};
1.44      www      12072:     }
1.569     albertel 12073:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12074: # is that filename actually a symb? Verify, clean, and return
                   12075:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12076: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 12077: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12078: 	}
1.242     www      12079:     }
1.44      www      12080:     $thisfn=declutter($thisfn);
1.31      www      12081:     my %hash;
1.37      www      12082:     my %bighash;
                   12083:     my $syval='';
1.620     albertel 12084:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12085:         my $targetfn = $thisfn;
1.609     banghart 12086:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12087:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12088:         }
1.687     albertel 12089: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12090: 	    $targetfn=$1;
                   12091: 	}
1.620     albertel 12092:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12093:                       &GDBM_READER(),0640)) {
1.481     raeburn  12094: 	    $syval=$hash{$targetfn};
1.37      www      12095:             untie(%hash);
                   12096:         }
                   12097: # ---------------------------------------------------------- There was an entry
                   12098:         if ($syval) {
1.601     albertel 12099: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12100: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12101: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12102: 		    #return $env{$cache_str}='';
1.601     albertel 12103: 		#}    
                   12104: 		#$syval.=$1;
                   12105: 	    #}
1.37      www      12106:         } else {
                   12107: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12108:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12109:                             &GDBM_READER(),0640)) {
1.37      www      12110: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12111:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12112:               unless ($ids) { 
                   12113:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12114:               }
                   12115:               unless ($ids) {
                   12116: # alias?
                   12117: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12118:               }
1.37      www      12119:               if ($ids) {
                   12120: # ------------------------------------------------------------------- Has ID(s)
                   12121:                  my @possibilities=split(/\,/,$ids);
1.39      www      12122:                  if ($#possibilities==0) {
                   12123: # ----------------------------------------------- There is only one possibility
1.37      www      12124: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12125: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12126: 						    $resid,$thisfn);
1.1282    raeburn  12127:                      if (ref($possibles) eq 'HASH') {
                   12128:                          $possibles->{$syval} = 1;    
                   12129:                      }
                   12130:                      if ($checkforblock) {
                   12131:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   12132:                          if (@blockers) {
                   12133:                              $syval = '';
                   12134:                              return;
                   12135:                          }
                   12136:                      }
                   12137:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      12138: # ------------------------------------------ There is more than one possibility
                   12139:                      my $realpossible=0;
1.800     albertel 12140:                      foreach my $id (@possibilities) {
                   12141: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  12142:                          my $canaccess;
                   12143:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12144:                              $canaccess = 1;
                   12145:                          } else { 
                   12146:                              $canaccess = &allowed('bre',$file);
                   12147:                          }
                   12148:                          if ($canaccess) {
                   12149:          		     my ($mapid,$resid)=split(/\./,$id);
                   12150:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12151:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12152: 						             $resid,$thisfn);
                   12153:                                  if (ref($possibles) eq 'HASH') {
                   12154:                                      $possibles->{$syval} = 1;
                   12155:                                  }
                   12156:                                  if ($checkforblock) {
                   12157:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   12158:                                      unless (@blockers > 0) {
                   12159:                                          $syval = $poss_syval;
                   12160:                                          $realpossible++;
                   12161:                                      }
                   12162:                                  } else {
                   12163:                                      $syval = $poss_syval;
                   12164:                                      $realpossible++;
                   12165:                                  }
                   12166:                              }
1.39      www      12167: 			 }
1.191     harris41 12168:                      }
1.39      www      12169: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12170:                  } else {
                   12171:                      $syval='';
1.37      www      12172:                  }
                   12173: 	      }
1.1282    raeburn  12174:               untie(%bighash);
1.481     raeburn  12175:            }
1.31      www      12176:         }
1.62      www      12177:         if ($syval) {
1.620     albertel 12178: 	    return $env{$cache_str}=$syval;
1.62      www      12179:         }
1.31      www      12180:     }
1.949     raeburn  12181:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12182:     return $env{$cache_str}='';
1.31      www      12183: }
                   12184: 
                   12185: # ---------------------------------------------------------- Return random seed
                   12186: 
1.32      www      12187: sub numval {
                   12188:     my $txt=shift;
                   12189:     $txt=~tr/A-J/0-9/;
                   12190:     $txt=~tr/a-j/0-9/;
                   12191:     $txt=~tr/K-T/0-9/;
                   12192:     $txt=~tr/k-t/0-9/;
                   12193:     $txt=~tr/U-Z/0-5/;
                   12194:     $txt=~tr/u-z/0-5/;
                   12195:     $txt=~s/\D//g;
1.564     albertel 12196:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12197:     return int($txt);
1.368     albertel 12198: }
                   12199: 
1.484     albertel 12200: sub numval2 {
                   12201:     my $txt=shift;
                   12202:     $txt=~tr/A-J/0-9/;
                   12203:     $txt=~tr/a-j/0-9/;
                   12204:     $txt=~tr/K-T/0-9/;
                   12205:     $txt=~tr/k-t/0-9/;
                   12206:     $txt=~tr/U-Z/0-5/;
                   12207:     $txt=~tr/u-z/0-5/;
                   12208:     $txt=~s/\D//g;
                   12209:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12210:     my $total;
                   12211:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12212:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12213:     return int($total);
                   12214: }
                   12215: 
1.575     albertel 12216: sub numval3 {
                   12217:     use integer;
                   12218:     my $txt=shift;
                   12219:     $txt=~tr/A-J/0-9/;
                   12220:     $txt=~tr/a-j/0-9/;
                   12221:     $txt=~tr/K-T/0-9/;
                   12222:     $txt=~tr/k-t/0-9/;
                   12223:     $txt=~tr/U-Z/0-5/;
                   12224:     $txt=~tr/u-z/0-5/;
                   12225:     $txt=~s/\D//g;
                   12226:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12227:     my $total;
                   12228:     foreach my $val (@txts) { $total+=$val; }
                   12229:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12230:     return $total;
                   12231: }
                   12232: 
1.675     albertel 12233: sub digest {
                   12234:     my ($data)=@_;
                   12235:     my $digest=&Digest::MD5::md5($data);
                   12236:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12237:     my ($e,$f);
                   12238:     {
                   12239:         use integer;
                   12240:         $e=($a+$b);
                   12241:         $f=($c+$d);
                   12242:         if ($_64bit) {
                   12243:             $e=(($e<<32)>>32);
                   12244:             $f=(($f<<32)>>32);
                   12245:         }
                   12246:     }
                   12247:     if (wantarray) {
                   12248: 	return ($e,$f);
                   12249:     } else {
                   12250: 	my $g;
                   12251: 	{
                   12252: 	    use integer;
                   12253: 	    $g=($e+$f);
                   12254: 	    if ($_64bit) {
                   12255: 		$g=(($g<<32)>>32);
                   12256: 	    }
                   12257: 	}
                   12258: 	return $g;
                   12259:     }
                   12260: }
                   12261: 
1.368     albertel 12262: sub latest_rnd_algorithm_id {
1.675     albertel 12263:     return '64bit5';
1.366     albertel 12264: }
1.32      www      12265: 
1.503     albertel 12266: sub get_rand_alg {
                   12267:     my ($courseid)=@_;
1.790     albertel 12268:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12269:     if ($courseid) {
1.620     albertel 12270: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12271:     }
                   12272:     return &latest_rnd_algorithm_id();
                   12273: }
                   12274: 
1.562     albertel 12275: sub validCODE {
                   12276:     my ($CODE)=@_;
                   12277:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12278:     return 0;
                   12279: }
                   12280: 
1.491     albertel 12281: sub getCODE {
1.620     albertel 12282:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12283:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12284: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12285: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12286: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12287:     }
                   12288:     return undef;
                   12289: }
1.1133    foxr     12290: #
                   12291: #  Determines the random seed for a specific context:
                   12292: #
                   12293: # parameters:
                   12294: #   symb      - in course context the symb for the seed.
                   12295: #   course_id - The course id of the form domain_coursenum.
                   12296: #   domain    - Domain for the user.
                   12297: #   course    - Course for the user.
                   12298: #   cenv      - environment of the course.
                   12299: #
                   12300: # NOTE:
                   12301: #   All parameters are picked out of the environment if missing
                   12302: #   or not defined.
                   12303: #   If a symb cannot be determined the current time is used instead.
                   12304: #
                   12305: #  For a given well defined symb, courside, domain, username,
                   12306: #  and course environment, the seed is reproducible.
                   12307: #
1.31      www      12308: sub rndseed {
1.1133    foxr     12309:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12310:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12311:     if (!defined($symb)) {
1.366     albertel 12312: 	unless ($symb=$wsymb) { return time; }
                   12313:     }
1.1146    foxr     12314:     if (!defined $courseid) { 
                   12315: 	$courseid=$wcourseid; 
                   12316:     }
                   12317:     if (!defined $domain) { $domain=$wdomain; }
                   12318:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12319: 
                   12320:     my $which;
                   12321:     if (defined($cenv->{'rndseed'})) {
                   12322: 	$which = $cenv->{'rndseed'};
                   12323:     } else {
                   12324: 	$which =&get_rand_alg($courseid);
                   12325:     }
1.491     albertel 12326:     if (defined(&getCODE())) {
1.1133    foxr     12327: 
1.675     albertel 12328: 	if ($which eq '64bit5') {
                   12329: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12330: 	} elsif ($which eq '64bit4') {
1.575     albertel 12331: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12332: 	} else {
                   12333: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12334: 	}
1.675     albertel 12335:     } elsif ($which eq '64bit5') {
                   12336: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12337:     } elsif ($which eq '64bit4') {
                   12338: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12339:     } elsif ($which eq '64bit3') {
                   12340: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12341:     } elsif ($which eq '64bit2') {
                   12342: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12343:     } elsif ($which eq '64bit') {
                   12344: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12345:     }
                   12346:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12347: }
                   12348: 
                   12349: sub rndseed_32bit {
                   12350:     my ($symb,$courseid,$domain,$username)=@_;
                   12351:     {
                   12352: 	use integer;
                   12353: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12354: 	my $symbseed=numval($symb) << 22;
                   12355: 	my $namechck=unpack("%32C*",$username) << 17;
                   12356: 	my $nameseed=numval($username) << 12;
                   12357: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12358: 	my $courseseed=unpack("%32C*",$courseid);
                   12359: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12360: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12361: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12362: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12363: 	return $num;
                   12364:     }
                   12365: }
                   12366: 
                   12367: sub rndseed_64bit {
                   12368:     my ($symb,$courseid,$domain,$username)=@_;
                   12369:     {
                   12370: 	use integer;
                   12371: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12372: 	my $symbseed=numval($symb) << 10;
                   12373: 	my $namechck=unpack("%32S*",$username);
                   12374: 	
                   12375: 	my $nameseed=numval($username) << 21;
                   12376: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12377: 	my $courseseed=unpack("%32S*",$courseid);
                   12378: 	
                   12379: 	my $num1=$symbchck+$symbseed+$namechck;
                   12380: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12381: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12382: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12383: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12384: 	return "$num1,$num2";
1.155     albertel 12385:     }
1.366     albertel 12386: }
                   12387: 
1.443     albertel 12388: sub rndseed_64bit2 {
                   12389:     my ($symb,$courseid,$domain,$username)=@_;
                   12390:     {
                   12391: 	use integer;
                   12392: 	# strings need to be an even # of cahracters long, it it is odd the
                   12393:         # last characters gets thrown away
                   12394: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12395: 	my $symbseed=numval($symb) << 10;
                   12396: 	my $namechck=unpack("%32S*",$username.' ');
                   12397: 	
                   12398: 	my $nameseed=numval($username) << 21;
1.501     albertel 12399: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12400: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12401: 	
                   12402: 	my $num1=$symbchck+$symbseed+$namechck;
                   12403: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12404: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12405: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12406: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12407: 	return "$num1,$num2";
                   12408:     }
                   12409: }
                   12410: 
                   12411: sub rndseed_64bit3 {
                   12412:     my ($symb,$courseid,$domain,$username)=@_;
                   12413:     {
                   12414: 	use integer;
                   12415: 	# strings need to be an even # of cahracters long, it it is odd the
                   12416:         # last characters gets thrown away
                   12417: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12418: 	my $symbseed=numval2($symb) << 10;
                   12419: 	my $namechck=unpack("%32S*",$username.' ');
                   12420: 	
                   12421: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12422: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12423: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12424: 	
                   12425: 	my $num1=$symbchck+$symbseed+$namechck;
                   12426: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12427: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12428: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12429: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12430: 	
1.503     albertel 12431: 	return "$num1:$num2";
1.443     albertel 12432:     }
                   12433: }
                   12434: 
1.575     albertel 12435: sub rndseed_64bit4 {
                   12436:     my ($symb,$courseid,$domain,$username)=@_;
                   12437:     {
                   12438: 	use integer;
                   12439: 	# strings need to be an even # of cahracters long, it it is odd the
                   12440:         # last characters gets thrown away
                   12441: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12442: 	my $symbseed=numval3($symb) << 10;
                   12443: 	my $namechck=unpack("%32S*",$username.' ');
                   12444: 	
                   12445: 	my $nameseed=numval3($username) << 21;
                   12446: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12447: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12448: 	
                   12449: 	my $num1=$symbchck+$symbseed+$namechck;
                   12450: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12451: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12452: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12453: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12454: 	
1.575     albertel 12455: 	return "$num1:$num2";
                   12456:     }
                   12457: }
                   12458: 
1.675     albertel 12459: sub rndseed_64bit5 {
                   12460:     my ($symb,$courseid,$domain,$username)=@_;
                   12461:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12462:     return "$num1:$num2";
                   12463: }
                   12464: 
1.366     albertel 12465: sub rndseed_CODE_64bit {
                   12466:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12467:     {
1.366     albertel 12468: 	use integer;
1.443     albertel 12469: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12470: 	my $symbseed=numval2($symb);
1.491     albertel 12471: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12472: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12473: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12474: 	my $num1=$symbseed+$CODEchck;
                   12475: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12476: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12477: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12478: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12479: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12480: 	return "$num1:$num2";
1.366     albertel 12481:     }
                   12482: }
                   12483: 
1.575     albertel 12484: sub rndseed_CODE_64bit4 {
                   12485:     my ($symb,$courseid,$domain,$username)=@_;
                   12486:     {
                   12487: 	use integer;
                   12488: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12489: 	my $symbseed=numval3($symb);
                   12490: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12491: 	my $CODEseed=numval3(&getCODE());
                   12492: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12493: 	my $num1=$symbseed+$CODEchck;
                   12494: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12495: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12496: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12497: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12498: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12499: 	return "$num1:$num2";
                   12500:     }
                   12501: }
                   12502: 
1.675     albertel 12503: sub rndseed_CODE_64bit5 {
                   12504:     my ($symb,$courseid,$domain,$username)=@_;
                   12505:     my $code = &getCODE();
                   12506:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12507:     return "$num1:$num2";
                   12508: }
                   12509: 
1.366     albertel 12510: sub setup_random_from_rndseed {
                   12511:     my ($rndseed)=@_;
1.503     albertel 12512:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  12513:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12514:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12515:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   12516:         } else {
                   12517:             &Math::Random::random_set_seed($num1,$num2);
                   12518:         }
1.366     albertel 12519:     } else {
                   12520: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12521:     }
1.36      albertel 12522: }
                   12523: 
1.474     albertel 12524: sub latest_receipt_algorithm_id {
1.835     albertel 12525:     return 'receipt3';
1.474     albertel 12526: }
                   12527: 
1.480     www      12528: sub recunique {
                   12529:     my $fucourseid=shift;
                   12530:     my $unique;
1.835     albertel 12531:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   12532: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12533: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      12534:     } else {
                   12535: 	$unique=$perlvar{'lonReceipt'};
                   12536:     }
                   12537:     return unpack("%32C*",$unique);
                   12538: }
                   12539: 
                   12540: sub recprefix {
                   12541:     my $fucourseid=shift;
                   12542:     my $prefix;
1.835     albertel 12543:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   12544: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12545: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      12546:     } else {
                   12547: 	$prefix=$perlvar{'lonHostID'};
                   12548:     }
                   12549:     return unpack("%32C*",$prefix);
                   12550: }
                   12551: 
1.76      www      12552: sub ireceipt {
1.474     albertel 12553:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 12554: 
                   12555:     my $return =&recprefix($fucourseid).'-';
                   12556: 
                   12557:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   12558: 	$env{'request.state'} eq 'construct') {
                   12559: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   12560: 	return $return;
                   12561:     }
                   12562: 
1.76      www      12563:     my $cuname=unpack("%32C*",$funame);
                   12564:     my $cudom=unpack("%32C*",$fudom);
                   12565:     my $cucourseid=unpack("%32C*",$fucourseid);
                   12566:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      12567:     my $cunique=&recunique($fucourseid);
1.474     albertel 12568:     my $cpart=unpack("%32S*",$part);
1.835     albertel 12569:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   12570: 
1.790     albertel 12571: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 12572: 			       
                   12573: 	$return.= ($cunique%$cuname+
                   12574: 		   $cunique%$cudom+
                   12575: 		   $cusymb%$cuname+
                   12576: 		   $cusymb%$cudom+
                   12577: 		   $cucourseid%$cuname+
                   12578: 		   $cucourseid%$cudom+
                   12579: 		   $cpart%$cuname+
                   12580: 		   $cpart%$cudom);
                   12581:     } else {
                   12582: 	$return.= ($cunique%$cuname+
                   12583: 		   $cunique%$cudom+
                   12584: 		   $cusymb%$cuname+
                   12585: 		   $cusymb%$cudom+
                   12586: 		   $cucourseid%$cuname+
                   12587: 		   $cucourseid%$cudom);
                   12588:     }
                   12589:     return $return;
1.76      www      12590: }
                   12591: 
                   12592: sub receipt {
1.474     albertel 12593:     my ($part)=@_;
1.790     albertel 12594:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 12595:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      12596: }
1.260     ng       12597: 
1.790     albertel 12598: sub whichuser {
                   12599:     my ($passedsymb)=@_;
                   12600:     my ($symb,$courseid,$domain,$name,$publicuser);
                   12601:     if (defined($env{'form.grade_symb'})) {
                   12602: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   12603: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   12604: 	if (!$allowed &&
                   12605: 	    exists($env{'request.course.sec'}) &&
                   12606: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   12607: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   12608: 			      '/'.$env{'request.course.sec'});
                   12609: 	}
                   12610: 	if ($allowed) {
                   12611: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   12612: 	    $courseid=$tmp_courseid;
                   12613: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   12614: 	    ($name)=&get_env_multiple('form.grade_username');
                   12615: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   12616: 	}
                   12617:     }
                   12618:     if (!$passedsymb) {
                   12619: 	$symb=&symbread();
                   12620:     } else {
                   12621: 	$symb=$passedsymb;
                   12622:     }
                   12623:     $courseid=$env{'request.course.id'};
                   12624:     $domain=$env{'user.domain'};
                   12625:     $name=$env{'user.name'};
                   12626:     if ($name eq 'public' && $domain eq 'public') {
                   12627: 	if (!defined($env{'form.username'})) {
                   12628: 	    $env{'form.username'}.=time.rand(10000000);
                   12629: 	}
                   12630: 	$name.=$env{'form.username'};
                   12631:     }
                   12632:     return ($symb,$courseid,$domain,$name,$publicuser);
                   12633: 
                   12634: }
                   12635: 
1.36      albertel 12636: # ------------------------------------------------------------ Serves up a file
1.472     albertel 12637: # returns either the contents of the file or 
                   12638: # -1 if the file doesn't exist
1.481     raeburn  12639: #
                   12640: # if the target is a file that was uploaded via DOCS, 
                   12641: # a check will be made to see if a current copy exists on the local server,
                   12642: # if it does this will be served, otherwise a copy will be retrieved from
                   12643: # the home server for the course and stored in /home/httpd/html/userfiles on
                   12644: # the local server.   
1.472     albertel 12645: 
1.36      albertel 12646: sub getfile {
1.538     albertel 12647:     my ($file) = @_;
1.609     banghart 12648:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 12649:     &repcopy($file);
                   12650:     return &readfile($file);
                   12651: }
                   12652: 
                   12653: sub repcopy_userfile {
                   12654:     my ($file)=@_;
1.1142    raeburn  12655:     my $londocroot = $perlvar{'lonDocRoot'};
                   12656:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  12657:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 12658:     my ($cdom,$cnum,$filename) = 
1.811     albertel 12659: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 12660:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   12661:     if (-e "$file") {
1.828     www      12662: # we already have a local copy, check it out
1.538     albertel 12663: 	my @fileinfo = stat($file);
1.828     www      12664: 	my $rtncode;
                   12665: 	my $info;
1.538     albertel 12666: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 12667: 	if ($lwpresp ne 'ok') {
1.828     www      12668: # there is no such file anymore, even though we had a local copy
1.482     albertel 12669: 	    if ($rtncode eq '404') {
1.538     albertel 12670: 		unlink($file);
1.482     albertel 12671: 	    }
                   12672: 	    return -1;
                   12673: 	}
                   12674: 	if ($info < $fileinfo[9]) {
1.828     www      12675: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  12676: 	    return 'ok';
1.828     www      12677: 	} else {
                   12678: # the file is outdated, get rid of it
                   12679: 	    unlink($file);
1.482     albertel 12680: 	}
1.828     www      12681:     }
                   12682: # one way or the other, at this point, we don't have the file
                   12683: # construct the correct path for the file
                   12684:     my @parts = ($cdom,$cnum); 
                   12685:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   12686: 	push @parts, split(/\//,$1);
                   12687:     }
                   12688:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   12689:     foreach my $part (@parts) {
                   12690: 	$path .= '/'.$part;
                   12691: 	if (!-e $path) {
                   12692: 	    mkdir($path,0770);
1.482     albertel 12693: 	}
                   12694:     }
1.828     www      12695: # now the path exists for sure
                   12696: # get a user agent
                   12697:     my $ua=new LWP::UserAgent;
                   12698:     my $transferfile=$file.'.in.transfer';
                   12699: # FIXME: this should flock
                   12700:     if (-e $transferfile) { return 'ok'; }
                   12701:     my $request;
                   12702:     $uri=~s/^\///;
1.980     raeburn  12703:     my $homeserver = &homeserver($cnum,$cdom);
                   12704:     my $protocol = $protocol{$homeserver};
                   12705:     $protocol = 'http' if ($protocol ne 'https');
                   12706:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      12707:     my $response=$ua->request($request,$transferfile);
                   12708: # did it work?
                   12709:     if ($response->is_error()) {
                   12710: 	unlink($transferfile);
                   12711: 	&logthis("Userfile repcopy failed for $uri");
                   12712: 	return -1;
                   12713:     }
                   12714: # worked, rename the transfer file
                   12715:     rename($transferfile,$file);
1.607     raeburn  12716:     return 'ok';
1.481     raeburn  12717: }
                   12718: 
1.517     albertel 12719: sub tokenwrapper {
                   12720:     my $uri=shift;
1.980     raeburn  12721:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 12722:     $uri=~s|^/||;
1.620     albertel 12723:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 12724:     my $token=$1;
1.552     albertel 12725:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   12726:     if ($udom && $uname && $file) {
                   12727: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  12728:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  12729:         my $homeserver = &homeserver($uname,$udom);
                   12730:         my $protocol = $protocol{$homeserver};
                   12731:         $protocol = 'http' if ($protocol ne 'https');
                   12732:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 12733:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   12734:                                '&tokenissued='.$perlvar{'lonHostID'};
                   12735:     } else {
                   12736:         return '/adm/notfound.html';
                   12737:     }
                   12738: }
                   12739: 
1.828     www      12740: # call with reqtype HEAD: get last modification time
                   12741: # call with reqtype GET: get the file contents
                   12742: # Do not call this with reqtype GET for large files! It loads everything into memory
                   12743: #
1.481     raeburn  12744: sub getuploaded {
                   12745:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   12746:     $uri=~s/^\///;
1.980     raeburn  12747:     my $homeserver = &homeserver($cnum,$cdom);
                   12748:     my $protocol = $protocol{$homeserver};
                   12749:     $protocol = 'http' if ($protocol ne 'https');
                   12750:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  12751:     my $ua=new LWP::UserAgent;
                   12752:     my $request=new HTTP::Request($reqtype,$uri);
                   12753:     my $response=$ua->request($request);
                   12754:     $$rtncode = $response->code;
1.482     albertel 12755:     if (! $response->is_success()) {
                   12756: 	return 'failed';
                   12757:     }      
                   12758:     if ($reqtype eq 'HEAD') {
1.486     www      12759: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 12760:     } elsif ($reqtype eq 'GET') {
                   12761: 	$$info = $response->content;
1.472     albertel 12762:     }
1.482     albertel 12763:     return 'ok';
1.36      albertel 12764: }
                   12765: 
1.481     raeburn  12766: sub readfile {
                   12767:     my $file = shift;
                   12768:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   12769:     my $fh;
                   12770:     open($fh,"<$file");
                   12771:     my $a='';
1.800     albertel 12772:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  12773:     return $a;
                   12774: }
                   12775: 
1.36      albertel 12776: sub filelocation {
1.590     banghart 12777:     my ($dir,$file) = @_;
                   12778:     my $location;
                   12779:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 12780: 
                   12781:     if ($file =~ m-^/adm/-) {
                   12782: 	$file=~s-^/adm/wrapper/-/-;
                   12783: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   12784:     }
1.882     albertel 12785: 
1.1139    www      12786:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  12787:         $location = $file;
1.609     banghart 12788:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 12789:         my ($udom,$uname,$filename)=
1.811     albertel 12790:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 12791:         my $home=&homeserver($uname,$udom);
                   12792:         my $is_me=0;
                   12793:         my @ids=&current_machine_ids();
                   12794:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   12795:         if ($is_me) {
1.1117    foxr     12796:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 12797:         } else {
                   12798:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   12799:   	      $udom.'/'.$uname.'/'.$filename;
                   12800:         }
1.882     albertel 12801:     } elsif ($file =~ m-^/adm/-) {
                   12802: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 12803:     } else {
                   12804:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      12805:         $file=~s:^/(res|priv)/:/:;
                   12806:         my $space=$1;
1.590     banghart 12807:         if ( !( $file =~ m:^/:) ) {
                   12808:             $location = $dir. '/'.$file;
                   12809:         } else {
1.1142    raeburn  12810:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 12811:         }
1.59      albertel 12812:     }
1.590     banghart 12813:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 12814:     while ($location=~m{/\.\./}) {
                   12815: 	if ($location =~ m{/[^/]+/\.\./}) {
                   12816: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   12817: 	} else {
                   12818: 	    $location=~ s{/\.\./}{/}g;
                   12819: 	}
                   12820:     } #remove dir/..
1.590     banghart 12821:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   12822:     return $location;
1.46      www      12823: }
1.36      albertel 12824: 
1.46      www      12825: sub hreflocation {
                   12826:     my ($dir,$file)=@_;
1.980     raeburn  12827:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 12828: 	$file=filelocation($dir,$file);
1.700     albertel 12829:     } elsif ($file=~m-^/adm/-) {
                   12830: 	$file=~s-^/adm/wrapper/-/-;
                   12831: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 12832:     }
                   12833:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   12834: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   12835:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  12836: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   12837: 	        {/uploaded/$1/$2/}x;
1.46      www      12838:     }
1.913     albertel 12839:     if ($file=~ m{^/userfiles/}) {
                   12840: 	$file =~ s{^/userfiles/}{/uploaded/};
                   12841:     }
1.462     albertel 12842:     return $file;
1.465     albertel 12843: }
                   12844: 
1.1139    www      12845: 
                   12846: 
                   12847: 
                   12848: 
1.465     albertel 12849: sub current_machine_domains {
1.853     albertel 12850:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   12851: }
                   12852: 
                   12853: sub machine_domains {
                   12854:     my ($hostname) = @_;
1.465     albertel 12855:     my @domains;
1.838     albertel 12856:     my %hostname = &all_hostnames();
1.465     albertel 12857:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  12858: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 12859: 	if ($hostname eq $name) {
1.844     albertel 12860: 	    push(@domains,&host_domain($id));
1.465     albertel 12861: 	}
                   12862:     }
                   12863:     return @domains;
                   12864: }
                   12865: 
                   12866: sub current_machine_ids {
1.853     albertel 12867:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   12868: }
                   12869: 
                   12870: sub machine_ids {
                   12871:     my ($hostname) = @_;
                   12872:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 12873:     my @ids;
1.888     albertel 12874:     my %name_to_host = &all_names();
1.889     albertel 12875:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   12876: 	return @{ $name_to_host{$hostname} };
                   12877:     }
                   12878:     return;
1.31      www      12879: }
                   12880: 
1.824     raeburn  12881: sub additional_machine_domains {
                   12882:     my @domains;
                   12883:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   12884:     while( my $line = <$fh>) {
                   12885:         $line =~ s/\s//g;
                   12886:         push(@domains,$line);
                   12887:     }
                   12888:     return @domains;
                   12889: }
                   12890: 
                   12891: sub default_login_domain {
                   12892:     my $domain = $perlvar{'lonDefDomain'};
                   12893:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   12894:     foreach my $posdom (&current_machine_domains(),
                   12895:                         &additional_machine_domains()) {
                   12896:         if (lc($posdom) eq lc($testdomain)) {
                   12897:             $domain=$posdom;
                   12898:             last;
                   12899:         }
                   12900:     }
                   12901:     return $domain;
                   12902: }
                   12903: 
1.31      www      12904: # ------------------------------------------------------------- Declutters URLs
                   12905: 
                   12906: sub declutter {
                   12907:     my $thisfn=shift;
1.569     albertel 12908:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  12909:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   12910:         $thisfn=~s{^/home/httpd/html}{};
                   12911:     }
1.31      www      12912:     $thisfn=~s/^\///;
1.697     albertel 12913:     $thisfn=~s|^adm/wrapper/||;
                   12914:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      12915:     $thisfn=~s/^res\///;
1.1172    bisitz   12916:     $thisfn=~s/^priv\///;
1.1032    raeburn  12917:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   12918:         $thisfn=~s/\?.+$//;
                   12919:     }
1.268     www      12920:     return $thisfn;
                   12921: }
                   12922: 
                   12923: # ------------------------------------------------------------- Clutter up URLs
                   12924: 
                   12925: sub clutter {
                   12926:     my $thisfn='/'.&declutter(shift);
1.887     albertel 12927:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 12928: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      12929:        $thisfn='/res'.$thisfn; 
                   12930:     }
1.1031    raeburn  12931:     if ($thisfn !~m|^/adm|) {
                   12932: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 12933: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 12934: 	} else {
                   12935: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   12936: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 12937: 	    if ($embstyle eq 'ssi'
                   12938: 		|| ($embstyle eq 'hdn')
                   12939: 		|| ($embstyle eq 'rat')
                   12940: 		|| ($embstyle eq 'prv')
                   12941: 		|| ($embstyle eq 'ign')) {
                   12942: 		#do nothing with these
                   12943: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 12944: 		|| ($embstyle eq 'emb')
                   12945: 		|| ($embstyle eq 'wrp')) {
                   12946: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 12947: 	    } elsif ($embstyle eq 'unk'
                   12948: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 12949: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 12950: 	    } else {
1.718     www      12951: #		&logthis("Got a blank emb style");
1.695     albertel 12952: 	    }
1.694     albertel 12953: 	}
1.1298    raeburn  12954:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/exttools?$}) {
                   12955:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 12956:     }
1.31      www      12957:     return $thisfn;
1.12      www      12958: }
                   12959: 
1.787     albertel 12960: sub clutter_with_no_wrapper {
                   12961:     my $uri = &clutter(shift);
                   12962:     if ($uri =~ m-^/adm/-) {
                   12963: 	$uri =~ s-^/adm/wrapper/-/-;
                   12964: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   12965:     }
                   12966:     return $uri;
                   12967: }
                   12968: 
1.557     albertel 12969: sub freeze_escape {
                   12970:     my ($value)=@_;
                   12971:     if (ref($value)) {
                   12972: 	$value=&nfreeze($value);
                   12973: 	return '__FROZEN__'.&escape($value);
                   12974:     }
                   12975:     return &escape($value);
                   12976: }
                   12977: 
1.11      www      12978: 
1.557     albertel 12979: sub thaw_unescape {
                   12980:     my ($value)=@_;
                   12981:     if ($value =~ /^__FROZEN__/) {
                   12982: 	substr($value,0,10,undef);
                   12983: 	$value=&unescape($value);
                   12984: 	return &thaw($value);
                   12985:     }
                   12986:     return &unescape($value);
                   12987: }
                   12988: 
1.436     albertel 12989: sub correct_line_ends {
                   12990:     my ($result)=@_;
                   12991:     $$result =~s/\r\n/\n/mg;
                   12992:     $$result =~s/\r/\n/mg;
1.415     albertel 12993: }
1.1       albertel 12994: # ================================================================ Main Program
                   12995: 
1.184     www      12996: sub goodbye {
1.204     albertel 12997:    &logthis("Starting Shut down");
1.443     albertel 12998: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 12999:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13000: #converted
1.599     albertel 13001: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13002:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13003: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13004: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13005: #1.1 only
1.870     albertel 13006: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13007: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13008: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13009: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13010:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13011:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13012:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13013:    &flushcourselogs();
                   13014:    &logthis("Shutting down");
                   13015: }
                   13016: 
1.852     albertel 13017: sub get_dns {
1.1210    raeburn  13018:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13019:     if (!$ignore_cache) {
                   13020: 	my ($content,$cached)=
                   13021: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13022: 	if ($cached) {
1.1210    raeburn  13023: 	    &$func($content,$hashref);
1.869     albertel 13024: 	    return;
                   13025: 	}
                   13026:     }
                   13027: 
                   13028:     my %alldns;
1.852     albertel 13029:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   13030:     foreach my $dns (<$config>) {
                   13031: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  13032:         my $line = $1;
                   13033:         my ($host,$protocol) = split(/:/,$line);
                   13034:         if ($protocol ne 'https') {
                   13035:             $protocol = 'http';
                   13036:         }
                   13037: 	$alldns{$host} = $protocol;
1.869     albertel 13038:     }
                   13039:     while (%alldns) {
1.1263    raeburn  13040: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 13041: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  13042:         $ua->timeout(30);
1.979     raeburn  13043: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 13044: 	my $response=$ua->request($request);
1.979     raeburn  13045:         delete($alldns{$dns});
1.852     albertel 13046: 	next if ($response->is_error());
                   13047: 	my @content = split("\n",$response->content);
1.1210    raeburn  13048: 	unless ($nocache) {
1.1219    raeburn  13049: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210    raeburn  13050: 	}
                   13051: 	&$func(\@content,$hashref);
1.869     albertel 13052: 	return;
1.852     albertel 13053:     }
                   13054:     close($config);
1.871     albertel 13055:     my $which = (split('/',$url))[3];
                   13056:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   13057:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 13058:     my @content = <$config>;
1.1210    raeburn  13059:     &$func(\@content,$hashref);
                   13060:     return;
                   13061: }
                   13062: 
                   13063: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  13064: sub parse_dns_checksums_tab {
1.1210    raeburn  13065:     my ($lines,$hashref) = @_;
1.1264    raeburn  13066:     my $lonhost = $perlvar{'lonHostID'};
                   13067:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  13068:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  13069:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13070:     my $webconfdir = '/etc/httpd/conf';
                   13071:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13072:         $webconfdir = '/etc/apache2';
                   13073:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13074:         if ($1 >= 10) {
                   13075:             $webconfdir = '/etc/apache2';
                   13076:         }
                   13077:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13078:         if ($1 >= 10.0) {
                   13079:             $webconfdir = '/etc/apache2';
                   13080:         }
                   13081:     }
1.1210    raeburn  13082:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13083:     my (%chksum,%revnum);
                   13084:     if (ref($lines) eq 'ARRAY') {
                   13085:         chomp(@{$lines});
1.1238    raeburn  13086:         my $version = shift(@{$lines});
                   13087:         if ($version eq $release) {  
1.1210    raeburn  13088:             foreach my $line (@{$lines}) {
1.1238    raeburn  13089:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  13090:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13091:                     if ($webconfdir eq '/etc/apache2') {
                   13092:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13093:                     }
                   13094:                 }
1.1238    raeburn  13095:                 $chksum{$file} = $shasum;
                   13096:                 $revnum{$file} = $version;
1.1210    raeburn  13097:             }
                   13098:             if (ref($hashref) eq 'HASH') {
                   13099:                 %{$hashref} = (
                   13100:                                 sums     => \%chksum,
                   13101:                                 versions => \%revnum,
                   13102:                               );
                   13103:             }
                   13104:         }
                   13105:     }
1.869     albertel 13106:     return;
1.852     albertel 13107: }
1.1210    raeburn  13108: 
                   13109: sub fetch_dns_checksums {
1.1238    raeburn  13110:     my %checksums;
                   13111:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  13112:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  13113:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13114:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  13115:              \%checksums);
1.1210    raeburn  13116:     return \%checksums;
                   13117: }
                   13118: 
1.327     albertel 13119: # ------------------------------------------------------------ Read domain file
                   13120: {
1.852     albertel 13121:     my $loaded;
1.846     albertel 13122:     my %domain;
                   13123: 
1.852     albertel 13124:     sub parse_domain_tab {
                   13125: 	my ($lines) = @_;
                   13126: 	foreach my $line (@$lines) {
                   13127: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13128: 
1.846     albertel 13129: 	    chomp($line);
1.852     albertel 13130: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13131: 	    my %this_domain;
                   13132: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13133: 			       'lang_def', 'city', 'longi', 'lati',
                   13134: 			       'primary') {
                   13135: 		$this_domain{$field} = shift(@elements);
                   13136: 	    }
                   13137: 	    $domain{$name} = \%this_domain;
1.852     albertel 13138: 	}
                   13139:     }
1.864     albertel 13140: 
                   13141:     sub reset_domain_info {
                   13142: 	undef($loaded);
                   13143: 	undef(%domain);
                   13144:     }
                   13145: 
1.852     albertel 13146:     sub load_domain_tab {
1.1293    raeburn  13147: 	my ($ignore_cache,$nocache) = @_;
                   13148: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13149: 	my $fh;
                   13150: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   13151: 	    my @lines = <$fh>;
                   13152: 	    &parse_domain_tab(\@lines);
1.448     albertel 13153: 	}
1.852     albertel 13154: 	close($fh);
                   13155: 	$loaded = 1;
1.327     albertel 13156:     }
1.846     albertel 13157: 
                   13158:     sub domain {
1.852     albertel 13159: 	&load_domain_tab() if (!$loaded);
                   13160: 
1.846     albertel 13161: 	my ($name,$what) = @_;
                   13162: 	return if ( !exists($domain{$name}) );
                   13163: 
                   13164: 	if (!$what) {
                   13165: 	    return $domain{$name}{'description'};
                   13166: 	}
                   13167: 	return $domain{$name}{$what};
                   13168:     }
1.974     raeburn  13169: 
                   13170:     sub domain_info {
                   13171:         &load_domain_tab() if (!$loaded);
                   13172:         return %domain;
                   13173:     }
                   13174: 
1.327     albertel 13175: }
                   13176: 
                   13177: 
1.1       albertel 13178: # ------------------------------------------------------------- Read hosts file
                   13179: {
1.838     albertel 13180:     my %hostname;
1.844     albertel 13181:     my %hostdom;
1.845     albertel 13182:     my %libserv;
1.852     albertel 13183:     my $loaded;
1.888     albertel 13184:     my %name_to_host;
1.1074    raeburn  13185:     my %internetdom;
1.1107    raeburn  13186:     my %LC_dns_serv;
1.852     albertel 13187: 
                   13188:     sub parse_hosts_tab {
                   13189: 	my ($file) = @_;
                   13190: 	foreach my $configline (@$file) {
                   13191: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13192:             chomp($configline);
                   13193: 	    if ($configline =~ /^\^/) {
                   13194:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13195:                     $LC_dns_serv{$1} = 1;
                   13196:                 }
                   13197:                 next;
                   13198:             }
1.1074    raeburn  13199: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13200: 	    $name=~s/\s//g;
                   13201: 	    if ($id && $domain && $role && $name) {
                   13202: 		$hostname{$id}=$name;
1.888     albertel 13203: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 13204: 		$hostdom{$id}=$domain;
                   13205: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13206:                 if (defined($protocol)) {
                   13207:                     if ($protocol eq 'https') {
                   13208:                         $protocol{$id} = $protocol;
                   13209:                     } else {
                   13210:                         $protocol{$id} = 'http'; 
                   13211:                     }
1.968     raeburn  13212:                 } else {
1.969     raeburn  13213:                     $protocol{$id} = 'http';
1.968     raeburn  13214:                 }
1.1074    raeburn  13215:                 if (defined($intdom)) {
                   13216:                     $internetdom{$id} = $intdom;
                   13217:                 }
1.852     albertel 13218: 	    }
                   13219: 	}
                   13220:     }
1.864     albertel 13221:     
                   13222:     sub reset_hosts_info {
1.897     albertel 13223: 	&purge_remembered();
1.864     albertel 13224: 	&reset_domain_info();
                   13225: 	&reset_hosts_ip_info();
1.892     albertel 13226: 	undef(%name_to_host);
1.864     albertel 13227: 	undef(%hostname);
                   13228: 	undef(%hostdom);
                   13229: 	undef(%libserv);
                   13230: 	undef($loaded);
                   13231:     }
1.1       albertel 13232: 
1.852     albertel 13233:     sub load_hosts_tab {
1.1293    raeburn  13234: 	my ($ignore_cache,$nocache) = @_;
                   13235: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852     albertel 13236: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   13237: 	my @config = <$config>;
                   13238: 	&parse_hosts_tab(\@config);
                   13239: 	close($config);
                   13240: 	$loaded=1;
1.1       albertel 13241:     }
1.852     albertel 13242: 
1.838     albertel 13243:     sub hostname {
1.852     albertel 13244: 	&load_hosts_tab() if (!$loaded);
                   13245: 
1.838     albertel 13246: 	my ($lonid) = @_;
                   13247: 	return $hostname{$lonid};
                   13248:     }
1.845     albertel 13249: 
1.838     albertel 13250:     sub all_hostnames {
1.852     albertel 13251: 	&load_hosts_tab() if (!$loaded);
                   13252: 
1.838     albertel 13253: 	return %hostname;
                   13254:     }
1.845     albertel 13255: 
1.888     albertel 13256:     sub all_names {
1.1293    raeburn  13257:         my ($ignore_cache,$nocache) = @_;
                   13258: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13259: 
                   13260: 	return %name_to_host;
                   13261:     }
                   13262: 
1.974     raeburn  13263:     sub all_host_domain {
                   13264:         &load_hosts_tab() if (!$loaded);
                   13265:         return %hostdom;
                   13266:     }
                   13267: 
1.845     albertel 13268:     sub is_library {
1.852     albertel 13269: 	&load_hosts_tab() if (!$loaded);
                   13270: 
1.845     albertel 13271: 	return exists($libserv{$_[0]});
                   13272:     }
                   13273: 
                   13274:     sub all_library {
1.852     albertel 13275: 	&load_hosts_tab() if (!$loaded);
                   13276: 
1.845     albertel 13277: 	return %libserv;
                   13278:     }
                   13279: 
1.1062    droeschl 13280:     sub unique_library {
                   13281: 	#2x reverse removes all hostnames that appear more than once
                   13282:         my %unique = reverse &all_library();
                   13283:         return reverse %unique;
                   13284:     }
                   13285: 
1.841     albertel 13286:     sub get_servers {
1.852     albertel 13287: 	&load_hosts_tab() if (!$loaded);
                   13288: 
1.841     albertel 13289: 	my ($domain,$type) = @_;
                   13290: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13291: 	                                          : %hostname;
                   13292: 	my %result;
1.842     albertel 13293: 	if (ref($domain) eq 'ARRAY') {
                   13294: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13295: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13296: 		    $result{$host} = $hostname;
                   13297: 		}
                   13298: 	    }
                   13299: 	} else {
                   13300: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13301: 		if ($hostdom{$host} eq $domain) {
                   13302: 		    $result{$host} = $hostname;
                   13303: 		}
1.841     albertel 13304: 	    }
                   13305: 	}
                   13306: 	return %result;
                   13307:     }
1.845     albertel 13308: 
1.1062    droeschl 13309:     sub get_unique_servers {
                   13310:         my %unique = reverse &get_servers(@_);
                   13311: 	return reverse %unique;
                   13312:     }
                   13313: 
1.844     albertel 13314:     sub host_domain {
1.852     albertel 13315: 	&load_hosts_tab() if (!$loaded);
                   13316: 
1.844     albertel 13317: 	my ($lonid) = @_;
                   13318: 	return $hostdom{$lonid};
                   13319:     }
                   13320: 
1.841     albertel 13321:     sub all_domains {
1.852     albertel 13322: 	&load_hosts_tab() if (!$loaded);
                   13323: 
1.841     albertel 13324: 	my %seen;
                   13325: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13326: 	return @uniq;
                   13327:     }
1.1074    raeburn  13328: 
                   13329:     sub internet_dom {
                   13330:         &load_hosts_tab() if (!$loaded);
                   13331: 
                   13332:         my ($lonid) = @_;
                   13333:         return $internetdom{$lonid};
                   13334:     }
1.1107    raeburn  13335: 
                   13336:     sub is_LC_dns {
                   13337:         &load_hosts_tab() if (!$loaded);
                   13338: 
                   13339:         my ($hostname) = @_;
                   13340:         return exists($LC_dns_serv{$hostname});
                   13341:     }
                   13342: 
1.1       albertel 13343: }
                   13344: 
1.847     albertel 13345: { 
                   13346:     my %iphost;
1.856     albertel 13347:     my %name_to_ip;
                   13348:     my %lonid_to_ip;
1.869     albertel 13349: 
1.847     albertel 13350:     sub get_hosts_from_ip {
                   13351: 	my ($ip) = @_;
                   13352: 	my %iphosts = &get_iphost();
                   13353: 	if (ref($iphosts{$ip})) {
                   13354: 	    return @{$iphosts{$ip}};
                   13355: 	}
                   13356: 	return;
1.839     albertel 13357:     }
1.864     albertel 13358:     
                   13359:     sub reset_hosts_ip_info {
                   13360: 	undef(%iphost);
                   13361: 	undef(%name_to_ip);
                   13362: 	undef(%lonid_to_ip);
                   13363:     }
1.856     albertel 13364: 
                   13365:     sub get_host_ip {
                   13366: 	my ($lonid) = @_;
                   13367: 	if (exists($lonid_to_ip{$lonid})) {
                   13368: 	    return $lonid_to_ip{$lonid};
                   13369: 	}
                   13370: 	my $name=&hostname($lonid);
                   13371:    	my $ip = gethostbyname($name);
                   13372: 	return if (!$ip || length($ip) ne 4);
                   13373: 	$ip=inet_ntoa($ip);
                   13374: 	$name_to_ip{$name}   = $ip;
                   13375: 	$lonid_to_ip{$lonid} = $ip;
                   13376: 	return $ip;
                   13377:     }
1.847     albertel 13378:     
                   13379:     sub get_iphost {
1.1293    raeburn  13380: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13381: 
1.869     albertel 13382: 	if (!$ignore_cache) {
                   13383: 	    if (%iphost) {
                   13384: 		return %iphost;
                   13385: 	    }
                   13386: 	    my ($ip_info,$cached)=
                   13387: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13388: 	    if ($cached) {
                   13389: 		%iphost      = %{$ip_info->[0]};
                   13390: 		%name_to_ip  = %{$ip_info->[1]};
                   13391: 		%lonid_to_ip = %{$ip_info->[2]};
                   13392: 		return %iphost;
                   13393: 	    }
                   13394: 	}
1.894     albertel 13395: 
                   13396: 	# get yesterday's info for fallback
                   13397: 	my %old_name_to_ip;
                   13398: 	my ($ip_info,$cached)=
                   13399: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13400: 	if ($cached) {
                   13401: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13402: 	}
                   13403: 
1.1293    raeburn  13404: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13405: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13406: 	    my $ip;
                   13407: 	    if (!exists($name_to_ip{$name})) {
                   13408: 		$ip = gethostbyname($name);
                   13409: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13410: 		    if (defined($old_name_to_ip{$name})) {
                   13411: 			$ip = $old_name_to_ip{$name};
                   13412: 			&logthis("Can't find $name defaulting to old $ip");
                   13413: 		    } else {
                   13414: 			&logthis("Name $name no IP found");
                   13415: 			next;
                   13416: 		    }
                   13417: 		} else {
                   13418: 		    $ip=inet_ntoa($ip);
1.847     albertel 13419: 		}
                   13420: 		$name_to_ip{$name} = $ip;
                   13421: 	    } else {
                   13422: 		$ip = $name_to_ip{$name};
1.653     albertel 13423: 	    }
1.888     albertel 13424: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13425: 		$lonid_to_ip{$id} = $ip;
                   13426: 	    }
                   13427: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13428: 	}
1.1293    raeburn  13429:         unless ($nocache) {
                   13430: 	    &do_cache_new('iphost','iphost',
                   13431: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   13432: 		          48*60*60);
                   13433:         }
1.869     albertel 13434: 
1.847     albertel 13435: 	return %iphost;
1.598     albertel 13436:     }
                   13437: 
1.992     raeburn  13438:     #
                   13439:     #  Given a DNS returns the loncapa host name for that DNS 
                   13440:     # 
                   13441:     sub host_from_dns {
                   13442:         my ($dns) = @_;
                   13443:         my @hosts;
                   13444:         my $ip;
                   13445: 
1.993     raeburn  13446:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  13447:             $ip = $name_to_ip{$dns};
                   13448:         }
                   13449:         if (!$ip) {
                   13450:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   13451:             if (length($ip) == 4) { 
                   13452: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   13453:             }
                   13454:         }
                   13455:         if ($ip) {
                   13456: 	    @hosts = get_hosts_from_ip($ip);
                   13457: 	    return $hosts[0];
                   13458:         }
                   13459:         return undef;
1.986     foxr     13460:     }
1.992     raeburn  13461: 
1.1074    raeburn  13462:     sub get_internet_names {
                   13463:         my ($lonid) = @_;
                   13464:         return if ($lonid eq '');
                   13465:         my ($idnref,$cached)=
                   13466:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   13467:         if ($cached) {
                   13468:             return $idnref;
                   13469:         }
                   13470:         my $ip = &get_host_ip($lonid);
                   13471:         my @hosts = &get_hosts_from_ip($ip);
                   13472:         my %iphost = &get_iphost();
                   13473:         my (@idns,%seen);
                   13474:         foreach my $id (@hosts) {
                   13475:             my $dom = &host_domain($id);
                   13476:             my $prim_id = &domain($dom,'primary');
                   13477:             my $prim_ip = &get_host_ip($prim_id);
                   13478:             next if ($seen{$prim_ip});
                   13479:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   13480:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   13481:                     my $intdom = &internet_dom($id);
                   13482:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   13483:                         push(@idns,$intdom);
                   13484:                     }
                   13485:                 }
                   13486:             }
                   13487:             $seen{$prim_ip} = 1;
                   13488:         }
1.1219    raeburn  13489:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  13490:     }
                   13491: 
1.986     foxr     13492: }
                   13493: 
1.1079    raeburn  13494: sub all_loncaparevs {
1.1249    raeburn  13495:     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  13496: }
                   13497: 
1.1227    raeburn  13498: # ---------------------------------------------------------- Read loncaparev table
                   13499: {
                   13500:     sub load_loncaparevs { 
                   13501:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   13502:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   13503:                 while (my $configline=<$config>) {
                   13504:                     chomp($configline);
                   13505:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   13506:                     $loncaparevs{$hostid}=$loncaparev;
                   13507:                 }
                   13508:                 close($config);
                   13509:             }
                   13510:         }
                   13511:     }
                   13512: }
                   13513: 
                   13514: # ---------------------------------------------------------- Read serverhostID table
                   13515: {
                   13516:     sub load_serverhomeIDs {
                   13517:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   13518:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   13519:                 while (my $configline=<$config>) {
                   13520:                     chomp($configline);
                   13521:                     my ($name,$id)=split(/:/,$configline);
                   13522:                     $serverhomeIDs{$name}=$id;
                   13523:                 }
                   13524:                 close($config);
                   13525:             }
                   13526:         }
                   13527:     }
                   13528: }
                   13529: 
                   13530: 
1.862     albertel 13531: BEGIN {
                   13532: 
                   13533: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   13534:     unless ($readit) {
                   13535: {
                   13536:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   13537:     %perlvar = (%perlvar,%{$configvars});
                   13538: }
                   13539: 
                   13540: 
1.1       albertel 13541: # ------------------------------------------------------ Read spare server file
                   13542: {
1.448     albertel 13543:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 13544: 
                   13545:     while (my $configline=<$config>) {
                   13546:        chomp($configline);
1.284     matthew  13547:        if ($configline) {
1.784     albertel 13548: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 13549: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 13550: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 13551:        }
                   13552:     }
1.448     albertel 13553:     close($config);
1.1       albertel 13554: }
1.11      www      13555: # ------------------------------------------------------------ Read permissions
                   13556: {
1.448     albertel 13557:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      13558: 
                   13559:     while (my $configline=<$config>) {
1.448     albertel 13560: 	chomp($configline);
                   13561: 	if ($configline) {
                   13562: 	    my ($role,$perm)=split(/ /,$configline);
                   13563: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   13564: 	}
1.11      www      13565:     }
1.448     albertel 13566:     close($config);
1.11      www      13567: }
                   13568: 
                   13569: # -------------------------------------------- Read plain texts for permissions
                   13570: {
1.448     albertel 13571:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      13572: 
                   13573:     while (my $configline=<$config>) {
1.448     albertel 13574: 	chomp($configline);
                   13575: 	if ($configline) {
1.742     raeburn  13576: 	    my ($short,@plain)=split(/:/,$configline);
                   13577:             %{$prp{$short}} = ();
                   13578: 	    if (@plain > 0) {
                   13579:                 $prp{$short}{'std'} = $plain[0];
                   13580:                 for (my $i=1; $i<@plain; $i++) {
                   13581:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   13582:                 }
                   13583:             }
1.448     albertel 13584: 	}
1.135     www      13585:     }
1.448     albertel 13586:     close($config);
1.135     www      13587: }
                   13588: 
                   13589: # ---------------------------------------------------------- Read package table
                   13590: {
1.448     albertel 13591:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      13592: 
                   13593:     while (my $configline=<$config>) {
1.483     albertel 13594: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 13595: 	chomp($configline);
                   13596: 	my ($short,$plain)=split(/:/,$configline);
                   13597: 	my ($pack,$name)=split(/\&/,$short);
                   13598: 	if ($plain ne '') {
                   13599: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   13600: 	    $packagetab{$short}=$plain; 
                   13601: 	}
1.11      www      13602:     }
1.448     albertel 13603:     close($config);
1.329     matthew  13604: }
                   13605: 
1.1073    raeburn  13606: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  13607: 
                   13608: &load_loncaparevs();
1.1073    raeburn  13609: 
1.1074    raeburn  13610: # ---------------------------------------------------------- Read serverhostID table
                   13611: 
1.1227    raeburn  13612: &load_serverhomeIDs();
                   13613: 
                   13614: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  13615: {
                   13616:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   13617:     if (-e $file) {
                   13618:         my $parser = HTML::LCParser->new($file);
                   13619:         while (my $token = $parser->get_token()) {
                   13620:             if ($token->[0] eq 'S') {
                   13621:                 my $item = $token->[1];
                   13622:                 my $name = $token->[2]{'name'};
                   13623:                 my $value = $token->[2]{'value'};
1.1285    raeburn  13624:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  13625:                 my $namematch = $token->[2]{'namematch'};
                   13626:                 if ($item eq 'parameter') {
                   13627:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   13628:                         my $release = $parser->get_text();
                   13629:                         $release =~ s/(^\s*|\s*$ )//gx;
                   13630:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   13631:                     }
                   13632:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  13633:                     my $release = $parser->get_text();
                   13634:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  13635:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  13636:                 }
                   13637:             }
                   13638:         }
                   13639:     }
1.1073    raeburn  13640: }
                   13641: 
1.1138    raeburn  13642: # ---------------------------------------------------------- Read managers table
                   13643: {
                   13644:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   13645:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   13646:             while (my $configline=<$config>) {
                   13647:                 chomp($configline);
                   13648:                 next if ($configline =~ /^\#/);
                   13649:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   13650:                     $managerstab{$configline} = 1;
                   13651:                 }
                   13652:             }
                   13653:             close($config);
                   13654:         }
                   13655:     }
                   13656: }
                   13657: 
1.329     matthew  13658: # ------------- set up temporary directory
                   13659: {
1.1117    foxr     13660:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  13661: 
1.11      www      13662: }
                   13663: 
1.794     albertel 13664: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   13665: 				'compress_threshold'=> 20_000,
                   13666:  			        });
1.185     www      13667: 
1.281     www      13668: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      13669: $dumpcount=0;
1.958     www      13670: $locknum=0;
1.22      www      13671: 
1.163     harris41 13672: &logtouch();
1.672     albertel 13673: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      13674: $readit=1;
1.564     albertel 13675:     {
                   13676: 	use integer;
                   13677: 	my $test=(2**32)+1;
1.568     albertel 13678: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 13679: 	&logthis(" Detected 64bit platform ($_64bit)");
                   13680:     }
1.195     www      13681: }
1.1       albertel 13682: }
1.179     www      13683: 
1.1       albertel 13684: 1;
1.191     harris41 13685: __END__
                   13686: 
1.243     albertel 13687: =pod
                   13688: 
1.191     harris41 13689: =head1 NAME
                   13690: 
1.243     albertel 13691: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 13692: 
                   13693: =head1 SYNOPSIS
                   13694: 
1.243     albertel 13695: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 13696: 
                   13697:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   13698: 
1.243     albertel 13699: Common parameters:
                   13700: 
                   13701: =over 4
                   13702: 
                   13703: =item *
                   13704: 
                   13705: $uname : an internal username (if $cname expecting a course Id specifically)
                   13706: 
                   13707: =item *
                   13708: 
                   13709: $udom : a domain (if $cdom expecting a course's domain specifically)
                   13710: 
                   13711: =item *
                   13712: 
                   13713: $symb : a resource instance identifier
                   13714: 
                   13715: =item *
                   13716: 
                   13717: $namespace : the name of a .db file that contains the data needed or
                   13718: being set.
                   13719: 
                   13720: =back
                   13721: 
1.394     bowersj2 13722: =head1 OVERVIEW
1.191     harris41 13723: 
1.394     bowersj2 13724: lonnet provides subroutines which interact with the
                   13725: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   13726: about classes, users, and resources.
1.243     albertel 13727: 
                   13728: For many of these objects you can also use this to store data about
                   13729: them or modify them in various ways.
1.191     harris41 13730: 
1.394     bowersj2 13731: =head2 Symbs
1.191     harris41 13732: 
1.394     bowersj2 13733: To identify a specific instance of a resource, LON-CAPA uses symbols
                   13734: or "symbs"X<symb>. These identifiers are built from the URL of the
                   13735: map, the resource number of the resource in the map, and the URL of
                   13736: the resource itself. The latter is somewhat redundant, but might help
                   13737: if maps change.
                   13738: 
                   13739: An example is
                   13740: 
                   13741:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   13742: 
                   13743: The respective map entry is
                   13744: 
                   13745:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   13746:   title="Problem 2">
                   13747:  </resource>
                   13748: 
                   13749: Symbs are used by the random number generator, as well as to store and
                   13750: restore data specific to a certain instance of for example a problem.
                   13751: 
                   13752: =head2 Storing And Retrieving Data
                   13753: 
                   13754: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   13755: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   13756: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   13757: is is the non-critical message twin of cstore. These functions are for
                   13758: handlers to store a perl hash to a user's permanent data space in an
                   13759: easy manner, and to retrieve it again on another call. It is expected
                   13760: that a handler would use this once at the beginning to retrieve data,
                   13761: and then again once at the end to send only the new data back.
                   13762: 
                   13763: The data is stored in the user's data directory on the user's
                   13764: homeserver under the ID of the course.
                   13765: 
                   13766: The hash that is returned by restore will have all of the previous
                   13767: value for all of the elements of the hash.
                   13768: 
                   13769: Example:
                   13770: 
                   13771:  #creating a hash
                   13772:  my %hash;
                   13773:  $hash{'foo'}='bar';
                   13774: 
                   13775:  #storing it
                   13776:  &Apache::lonnet::cstore(\%hash);
                   13777: 
                   13778:  #changing a value
                   13779:  $hash{'foo'}='notbar';
                   13780: 
                   13781:  #adding a new value
                   13782:  $hash{'bar'}='foo';
                   13783:  &Apache::lonnet::cstore(\%hash);
                   13784: 
                   13785:  #retrieving the hash
                   13786:  my %history=&Apache::lonnet::restore();
                   13787: 
                   13788:  #print the hash
                   13789:  foreach my $key (sort(keys(%history))) {
                   13790:    print("\%history{$key} = $history{$key}");
                   13791:  }
                   13792: 
                   13793: Will print out:
1.191     harris41 13794: 
1.394     bowersj2 13795:  %history{1:foo} = bar
                   13796:  %history{1:keys} = foo:timestamp
                   13797:  %history{1:timestamp} = 990455579
                   13798:  %history{2:bar} = foo
                   13799:  %history{2:foo} = notbar
                   13800:  %history{2:keys} = foo:bar:timestamp
                   13801:  %history{2:timestamp} = 990455580
                   13802:  %history{bar} = foo
                   13803:  %history{foo} = notbar
                   13804:  %history{timestamp} = 990455580
                   13805:  %history{version} = 2
                   13806: 
                   13807: Note that the special hash entries C<keys>, C<version> and
                   13808: C<timestamp> were added to the hash. C<version> will be equal to the
                   13809: total number of versions of the data that have been stored. The
                   13810: C<timestamp> attribute will be the UNIX time the hash was
                   13811: stored. C<keys> is available in every historical section to list which
                   13812: keys were added or changed at a specific historical revision of a
                   13813: hash.
                   13814: 
                   13815: B<Warning>: do not store the hash that restore returns directly. This
                   13816: will cause a mess since it will restore the historical keys as if the
                   13817: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 13818: 
1.394     bowersj2 13819: Calling convention:
1.191     harris41 13820: 
1.1225    raeburn  13821:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  13822:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 13823: 
1.394     bowersj2 13824: For more detailed information, see lonnet specific documentation.
1.191     harris41 13825: 
1.394     bowersj2 13826: =head1 RETURN MESSAGES
1.191     harris41 13827: 
1.394     bowersj2 13828: =over 4
1.191     harris41 13829: 
1.394     bowersj2 13830: =item * B<con_lost>: unable to contact remote host
1.191     harris41 13831: 
1.394     bowersj2 13832: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   13833: when the connection is brought back up
1.191     harris41 13834: 
1.394     bowersj2 13835: =item * B<con_failed>: unable to contact remote host and unable to save message
                   13836: for later delivery
1.191     harris41 13837: 
1.967     bisitz   13838: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 13839: 
1.394     bowersj2 13840: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 13841: that was requested
1.191     harris41 13842: 
1.243     albertel 13843: =back
1.191     harris41 13844: 
1.243     albertel 13845: =head1 PUBLIC SUBROUTINES
1.191     harris41 13846: 
1.243     albertel 13847: =head2 Session Environment Functions
1.191     harris41 13848: 
1.243     albertel 13849: =over 4
1.191     harris41 13850: 
1.394     bowersj2 13851: =item * 
                   13852: X<appenv()>
1.949     raeburn  13853: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 13854: the user envirnoment file, and will be restored for each access this
1.620     albertel 13855: user makes during this session, also modifies the %env for the current
1.949     raeburn  13856: process. Optional rolesarrayref - if defined contains a reference to an array
                   13857: of roles which are exempt from the restriction on modifying user.role entries 
                   13858: in the user's environment.db and in %env.    
1.191     harris41 13859: 
                   13860: =item *
1.394     bowersj2 13861: X<delenv()>
1.987     raeburn  13862: B<delenv($delthis,$regexp)>: removes all items from the session
                   13863: environment file that begin with $delthis. If the 
                   13864: optional second arg - $regexp - is true, $delthis is treated as a 
                   13865: regular expression, otherwise \Q$delthis\E is used. 
                   13866: The values are also deleted from the current processes %env.
1.191     harris41 13867: 
1.795     albertel 13868: =item * get_env_multiple($name) 
                   13869: 
                   13870: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   13871: values may be defined and end up as an array ref.
                   13872: 
                   13873: returns an array of values
                   13874: 
1.243     albertel 13875: =back
                   13876: 
                   13877: =head2 User Information
1.191     harris41 13878: 
1.243     albertel 13879: =over 4
1.191     harris41 13880: 
                   13881: =item *
1.394     bowersj2 13882: X<queryauthenticate()>
                   13883: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 13884: authentication scheme
                   13885: 
                   13886: =item *
1.394     bowersj2 13887: X<authenticate()>
1.1073    raeburn  13888: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 13889: authenticate user from domain's lib servers (first use the current
                   13890: one). C<$upass> should be the users password.
1.1073    raeburn  13891: $checkdefauth is optional (value is 1 if a check should be made to
                   13892:    authenticate user using default authentication method, and allow
                   13893:    account creation if username does not have account in the domain).
                   13894: $clientcancheckhost is optional (value is 1 if checking whether the
                   13895:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 13896: 
                   13897: =item *
1.394     bowersj2 13898: X<homeserver()>
                   13899: B<homeserver($uname,$udom)>: find the server which has
                   13900: the user's directory and files (there must be only one), this caches
                   13901: the answer, and also caches if there is a borken connection.
1.191     harris41 13902: 
                   13903: =item *
1.394     bowersj2 13904: X<idget()>
1.1300    raeburn  13905: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   13906: a list of student/employee IDs or clicker IDs
                   13907: (student/employee IDs are a unique resource in a domain, there must be 
                   13908: only 1 ID per username, and only 1 username per ID in a specific domain).
                   13909: clickerIDs are not necessarily unique, as students might share clickers.
                   13910: (returns hash: id=>name,id=>name)
1.191     harris41 13911: 
                   13912: =item *
1.394     bowersj2 13913: X<idrget()>
                   13914: B<idrget($udom,@unames)>: find the IDs behind a list of
                   13915: usernames (returns hash: name=>id,name=>id)
1.191     harris41 13916: 
                   13917: =item *
1.394     bowersj2 13918: X<idput()>
1.1300    raeburn  13919: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   13920: names and associated student/employee IDs or clicker IDs.
                   13921: 
                   13922: =item *
                   13923: X<iddel()>
                   13924: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   13925: student/employee ID or clicker ID username look-ups from domain.
                   13926: The homeserver ($uhome) and namespace ($namespace) are optional.
                   13927: If no $uhome is provided, it will be determined usig &homeserver()
                   13928: for each user.  If no $namespace is provided, the default is ids.
                   13929: 
                   13930: =item *
                   13931: X<updateclickers()>
                   13932: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   13933: clicker ID-to-username look-ups in clickers.db on library server.
                   13934: Permitted actions are add or del (i.e., add or delete). The 
                   13935: clickers.db contains clickerID as keys (escaped), and each corresponding
                   13936: value is an escaped comma-separated list of usernames (for whom the
                   13937: library server is the homeserver), who registered that particular ID.
                   13938: If $critical is true, the update will be sent via &critical, otherwise
                   13939: &reply() will be used.
1.191     harris41 13940: 
                   13941: =item *
1.394     bowersj2 13942: X<rolesinit()>
1.1169    droeschl 13943: B<rolesinit($udom,$username)>: get user privileges.
                   13944: returns user role, first access and timer interval hashes
1.243     albertel 13945: 
                   13946: =item *
1.1171    droeschl 13947: X<privileged()>
                   13948: B<privileged($username,$domain)>: returns a true if user has a
                   13949: privileged and active role (i.e. su or dc), false otherwise.
                   13950: 
                   13951: =item *
1.551     albertel 13952: X<getsection()>
                   13953: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 13954: course $cname, return section name/number or '' for "not in course"
                   13955: and '-1' for "no section"
                   13956: 
                   13957: =item *
1.394     bowersj2 13958: X<userenvironment()>
                   13959: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 13960: passed in @what from the requested user's environment, returns a hash
                   13961: 
1.858     raeburn  13962: =item * 
                   13963: X<userlog_query()>
1.859     albertel 13964: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   13965: activity.log file. %filters defines filters applied when parsing the
                   13966: log file. These can be start or end timestamps, or the type of action
                   13967: - log to look for Login or Logout events, check for Checkin or
                   13968: Checkout, role for role selection. The response is in the form
                   13969: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   13970: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  13971: 
1.243     albertel 13972: =back
                   13973: 
                   13974: =head2 User Roles
                   13975: 
                   13976: =over 4
                   13977: 
                   13978: =item *
                   13979: 
1.1284    raeburn  13980: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   13981: returns codes for allowed actions.
                   13982: 
                   13983: The first argument is required, all others are optional.
                   13984: 
                   13985: $priv is the privilege being checked.
                   13986: $uri contains additional information about what is being checked for access (e.g.,
                   13987: URL, course ID etc.). 
                   13988: $symb is the unique resource instance identifier in a course; if needed,
                   13989: but not provided, it will be retrieved via a call to &symbread(). 
                   13990: $role is the role for which a priv is being checked (only used if priv is evb). 
                   13991: $clientip is the user's IP address (only used when checking for access to portfolio 
                   13992: files).
                   13993: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   13994: prevents recursive calls to &allowed.
                   13995: 
1.243     albertel 13996:  F: full access
                   13997:  U,I,K: authentication modes (cxx only)
                   13998:  '': forbidden
                   13999:  1: user needs to choose course
                   14000:  2: browse allowed
1.766     albertel 14001:  A: passphrase authentication needed
1.1284    raeburn  14002:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14003: 
                   14004: =item *
                   14005: 
1.1192    raeburn  14006: constructaccess($url,$setpriv) : check for access to construction space URL
                   14007: 
                   14008: See if the owner domain and name in the URL match those in the
                   14009: expected environment.  If so, return three element list
                   14010: ($ownername,$ownerdomain,$ownerhome).
                   14011: 
                   14012: Otherwise return the null string.
                   14013: 
                   14014: If second argument 'setpriv' is true, it assigns the privileges,
                   14015: and returns the same three element list, unless the owner has
                   14016: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14017: in which case the null string is returned.
                   14018: 
                   14019: =item *
                   14020: 
1.1326    raeburn  14021: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14022: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14023: for system, domain, and course level. $uname and $udom are optional (current
                   14024: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14025: 
                   14026: =item *
                   14027: 
1.988     raeburn  14028: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14029: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14030: $type is Course (default) or Community.
1.988     raeburn  14031: If $forcedefault evaluates to true, text returned will be default 
                   14032: text for $type. Otherwise, if this is a course, the text returned 
                   14033: will be a custom name for the role (if defined in the course's 
                   14034: environment).  If no custom name is defined the default is returned.
                   14035:    
1.832     raeburn  14036: =item *
                   14037: 
1.1219    raeburn  14038: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14039: All arguments are optional. Returns a hash of a roles, either for
                   14040: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14041: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14042: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14043: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14044: For each key, value is set to colon-separated start and end times for
                   14045: the role.  If no username and domain are specified, will default to
1.934     raeburn  14046: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14047: of role statuses (active, future or previous), roles 
                   14048: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14049: to restrict the list of roles reported. If no array ref is 
                   14050: provided for types, will default to return only active roles.
1.834     albertel 14051: 
1.1195    raeburn  14052: =item *
                   14053: 
                   14054: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  14055: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   14056: 
                   14057: Additional optional arguments are: $type (if role checking is to be restricted 
                   14058: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  14059: available roles) or future (roles available in the future), and
                   14060: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  14061: have active Domain Coordinator role in course's domain or in additional
                   14062: domains (specified in 'Domains to check for privileged users' in course
                   14063: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14064: 
                   14065: =item *
                   14066: 
                   14067: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14068: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14069: $possdomains and $possroles are optional array refs -- to domains to check and
                   14070: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14071: users' roles.db to check for a dc or su role in any domain. This can be
                   14072: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14073: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14074: this then allows &privileged_by_domain() to be used, which caches the identity
                   14075: of privileged users, eliminating the need for repeated calls to &dump().
                   14076: 
                   14077: =item *
                   14078: 
                   14079: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14080: where the outer hash keys are domains specified in the $possdomains array ref,
                   14081: next inner hash keys are privileged roles specified in the $roles array ref,
                   14082: and the innermost hash contains key = value pairs for username:domain = end:start
                   14083: for active or future "privileged" users with that role in that domain. To avoid
                   14084: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14085: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  14086: 
1.243     albertel 14087: =back
                   14088: 
                   14089: =head2 User Modification
                   14090: 
                   14091: =over 4
                   14092: 
                   14093: =item *
                   14094: 
1.957     raeburn  14095: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14096: user for the level given by URL.  Optional start and end dates (leave empty
                   14097: string or zero for "no date")
1.191     harris41 14098: 
                   14099: =item *
                   14100: 
1.243     albertel 14101: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14102: change a users, password, possible return values are: ok,
                   14103: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14104: refused
1.191     harris41 14105: 
                   14106: =item *
                   14107: 
1.243     albertel 14108: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14109: 
                   14110: =item *
                   14111: 
1.1058    raeburn  14112: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14113:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14114: 
                   14115: will update user information (firstname,middlename,lastname,generation,
                   14116: permanentemail), and if forceid is true, student/employee ID also.
                   14117: A user's institutional affiliation(s) can also be updated.
                   14118: User information fields will not be overwritten with empty entries 
                   14119: unless the field is included in the $candelete array reference.
                   14120: This array is included when a single user is modified via "Manage Users",
                   14121: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14122: 
                   14123: =item *
                   14124: 
1.286     matthew  14125: modifystudent
                   14126: 
1.957     raeburn  14127: modify a student's enrollment and identification information.
1.1235    raeburn  14128: The course id is resolved based on the current user's environment.  
                   14129: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14130: associated with a course.
                   14131: 
1.297     matthew  14132: This call is essentially a wrapper for lonnet::modifyuser and
                   14133: lonnet::modify_student_enrollment
1.286     matthew  14134: 
                   14135: Inputs: 
                   14136: 
                   14137: =over 4
                   14138: 
1.957     raeburn  14139: =item B<$udom> Student's loncapa domain
1.286     matthew  14140: 
1.957     raeburn  14141: =item B<$uname> Student's loncapa login name
1.286     matthew  14142: 
1.964     bisitz   14143: =item B<$uid> Student/Employee ID
1.286     matthew  14144: 
1.957     raeburn  14145: =item B<$umode> Student's authentication mode
1.286     matthew  14146: 
1.957     raeburn  14147: =item B<$upass> Student's password
1.286     matthew  14148: 
1.957     raeburn  14149: =item B<$first> Student's first name
1.286     matthew  14150: 
1.957     raeburn  14151: =item B<$middle> Student's middle name
1.286     matthew  14152: 
1.957     raeburn  14153: =item B<$last> Student's last name
1.286     matthew  14154: 
1.957     raeburn  14155: =item B<$gene> Student's generation
1.286     matthew  14156: 
1.957     raeburn  14157: =item B<$usec> Student's section in course
1.286     matthew  14158: 
                   14159: =item B<$end> Unix time of the roles expiration
                   14160: 
                   14161: =item B<$start> Unix time of the roles start date
                   14162: 
                   14163: =item B<$forceid> If defined, allow $uid to be changed
                   14164: 
                   14165: =item B<$desiredhome> server to use as home server for student
                   14166: 
1.957     raeburn  14167: =item B<$email> Student's permanent e-mail address
                   14168: 
                   14169: =item B<$type> Type of enrollment (auto or manual)
                   14170: 
1.963     raeburn  14171: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14172: 
                   14173: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14174: 
1.963     raeburn  14175: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14176: 
1.963     raeburn  14177: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14178: 
1.1216    raeburn  14179: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14180: 
                   14181: =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  14182: 
1.286     matthew  14183: =back
1.297     matthew  14184: 
                   14185: =item *
                   14186: 
                   14187: modify_student_enrollment
                   14188: 
1.1235    raeburn  14189: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14190: 'role.request.course' must be defined for this function to proceed.
                   14191: 
                   14192: Inputs:
                   14193: 
                   14194: =over 4
                   14195: 
1.1235    raeburn  14196: =item $udom, student's domain
1.297     matthew  14197: 
1.1235    raeburn  14198: =item $uname, student's name
1.297     matthew  14199: 
1.1235    raeburn  14200: =item $uid, student's user id
1.297     matthew  14201: 
1.1235    raeburn  14202: =item $first, student's first name
1.297     matthew  14203: 
                   14204: =item $middle
                   14205: 
                   14206: =item $last
                   14207: 
                   14208: =item $gene
                   14209: 
                   14210: =item $usec
                   14211: 
                   14212: =item $end
                   14213: 
                   14214: =item $start
                   14215: 
1.957     raeburn  14216: =item $type
                   14217: 
                   14218: =item $locktype
                   14219: 
                   14220: =item $cid
                   14221: 
                   14222: =item $selfenroll
                   14223: 
                   14224: =item $context
                   14225: 
1.1216    raeburn  14226: =item $credits, number of credits student will earn from this class
                   14227: 
1.1314    raeburn  14228: =item $instsec, institutional course section code for student
                   14229: 
1.297     matthew  14230: =back
                   14231: 
1.191     harris41 14232: 
                   14233: =item *
                   14234: 
1.243     albertel 14235: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14236: custom role; give a custom role to a user for the level given by URL.  Specify
                   14237: name and domain of role author, and role name
1.191     harris41 14238: 
                   14239: =item *
                   14240: 
1.243     albertel 14241: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14242: 
                   14243: =item *
                   14244: 
1.243     albertel 14245: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14246: 
                   14247: =back
                   14248: 
                   14249: =head2 Course Infomation
                   14250: 
                   14251: =over 4
1.191     harris41 14252: 
                   14253: =item *
                   14254: 
1.1118    foxr     14255: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14256: specified course id, including all environment settings for the
                   14257: course, the description of the course will be in the hash under the
                   14258: key 'description'
1.191     harris41 14259: 
1.1118    foxr     14260: $options is an optional parameter that if supplied is a hash reference that controls
                   14261: what how this function works.  It has the following key/values:
                   14262: 
                   14263: =over 4
                   14264: 
                   14265: =item freshen_cache
                   14266: 
                   14267: If defined, and the environment cache for the course is valid, it is 
                   14268: returned in the returned hash.
                   14269: 
                   14270: =item one_time
                   14271: 
                   14272: If defined, the last cache time is set to _now_
                   14273: 
                   14274: =item user
                   14275: 
                   14276: If defined, the supplied username is used instead of the current user.
                   14277: 
                   14278: 
                   14279: =back
                   14280: 
1.191     harris41 14281: =item *
                   14282: 
1.624     albertel 14283: resdata($name,$domain,$type,@which) : request for current parameter
                   14284: setting for a specific $type, where $type is either 'course' or 'user',
                   14285: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  14286: answers for 10 minutes.
1.243     albertel 14287: 
1.877     foxr     14288: =item *
                   14289: 
                   14290: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14291: data base, returning a hash that is keyed by the resource name and has
                   14292: values that are the resource value.  I believe that the timestamps and
                   14293: versions are also returned.
                   14294: 
1.1236    raeburn  14295: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14296: supplemental content area. This routine caches the number of files for 
                   14297: 10 minutes.
                   14298: 
1.243     albertel 14299: =back
                   14300: 
                   14301: =head2 Course Modification
                   14302: 
                   14303: =over 4
1.191     harris41 14304: 
                   14305: =item *
                   14306: 
1.243     albertel 14307: writecoursepref($courseid,%prefs) : write preferences (environment
                   14308: database) for a course
1.191     harris41 14309: 
                   14310: =item *
                   14311: 
1.1011    raeburn  14312: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14313: 
                   14314: =item *
                   14315: 
1.1038    raeburn  14316: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14317: 
1.1167    droeschl 14318: =item *
                   14319: 
                   14320: is_course($courseid), is_course($cdom, $cnum)
                   14321: 
                   14322: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14323: two component version $cdom, $cnum. It checks if the specified course exists.
                   14324: 
                   14325: Returns:
                   14326:     undef if the course doesn't exist, otherwise
                   14327:     in scalar context the combined courseid.
                   14328:     in list context the two components of the course identifier, domain and 
                   14329:     courseid.    
                   14330: 
1.243     albertel 14331: =back
                   14332: 
                   14333: =head2 Resource Subroutines
                   14334: 
                   14335: =over 4
1.191     harris41 14336: 
                   14337: =item *
                   14338: 
1.243     albertel 14339: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 14340: 
                   14341: =item *
                   14342: 
1.243     albertel 14343: repcopy($filename) : subscribes to the requested file, and attempts to
                   14344: replicate from the owning library server, Might return
1.607     raeburn  14345: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   14346: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 14347: resource. Expects the local filesystem pathname
                   14348: (/home/httpd/html/res/....)
                   14349: 
                   14350: =back
                   14351: 
                   14352: =head2 Resource Information
                   14353: 
                   14354: =over 4
1.191     harris41 14355: 
                   14356: =item *
                   14357: 
1.1228    raeburn  14358: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   14359: and returns the value of a variety of different possible values,
                   14360: $varname should be a request string, and the other parameters can be
                   14361: used to specify who and what one is asking about. Ordinarily, $cid 
                   14362: does not need to be specified, as it is retrived from 
                   14363: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14364: within lonuserstate::loadmap() when initializing a course, before
                   14365: $env{'request.course.id'} has been set, so it needs to be provided
                   14366: in that one case.
1.243     albertel 14367: 
                   14368: Possible values for $varname are environment.lastname (or other item
                   14369: from the envirnment hash), user.name (or someother aspect about the
                   14370: user), resource.0.maxtries (or some other part and parameter of a
                   14371: resource)
1.204     albertel 14372: 
                   14373: =item *
                   14374: 
1.243     albertel 14375: directcondval($number) : get current value of a condition; reads from a state
                   14376: string
1.204     albertel 14377: 
                   14378: =item *
                   14379: 
1.243     albertel 14380: condval($condidx) : value of condition index based on state
1.204     albertel 14381: 
                   14382: =item *
                   14383: 
1.243     albertel 14384: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   14385: resource's metadata, $what should be either a specific key, or either
                   14386: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   14387: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   14388: 
                   14389: this function automatically caches all requests
1.191     harris41 14390: 
                   14391: =item *
                   14392: 
1.243     albertel 14393: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   14394: network of library servers; returns file handle of where SQL and regex results
                   14395: will be stored for query
1.191     harris41 14396: 
                   14397: =item *
                   14398: 
1.1282    raeburn  14399: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   14400: return symbolic list entry (all arguments optional). 
                   14401: 
                   14402: Args: filename is the filename (including path) for the file for which a symb 
                   14403: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   14404: to check access status if more than one resource was found in the bighash 
                   14405: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   14406: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   14407: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   14408: cause possible symbs to be checked to determine if they are subject to content
                   14409: blocking, if so they will not be included as possible symbs; possibles is a
                   14410: ref to a hash, which, as a side effect, will be populated with all possible 
                   14411: symbs (content blocking not tested).
                   14412:  
1.243     albertel 14413: returns the data handle
1.191     harris41 14414: 
                   14415: =item *
                   14416: 
1.1190    raeburn  14417: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   14418: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 14419: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  14420: on failure, user must be in a course, as it assumes the existence of
                   14421: the course initial hash, and uses $env('request.course.id'}.  The third
                   14422: arg is an optional reference to a scalar.  If this arg is passed in the 
                   14423: call to symbverify, it will be set to 1 if the symb has been set to be 
                   14424: encrypted; otherwise it will be null.  
1.191     harris41 14425: 
                   14426: =item *
                   14427: 
1.243     albertel 14428: symbclean($symb) : removes versions numbers from a symb, returns the
                   14429: cleaned symb
1.191     harris41 14430: 
                   14431: =item *
                   14432: 
1.243     albertel 14433: is_on_map($uri) : checks if the $uri is somewhere on the current
                   14434: course map, user must be in a course for it to work.
1.191     harris41 14435: 
                   14436: =item *
                   14437: 
1.243     albertel 14438: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 14439: 
                   14440: =item *
                   14441: 
1.243     albertel 14442: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   14443: a random seed, all arguments are optional, if they aren't sent it uses the
                   14444: environment to derive them. Note: if symb isn't sent and it can't get one
                   14445: from &symbread it will use the current time as its return value
1.191     harris41 14446: 
                   14447: =item *
                   14448: 
1.243     albertel 14449: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   14450: unfakeable, receipt
1.191     harris41 14451: 
                   14452: =item *
                   14453: 
1.620     albertel 14454: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 14455: 
                   14456: =item *
                   14457: 
1.243     albertel 14458: countacc($url) : count the number of accesses to a given URL
1.191     harris41 14459: 
                   14460: =item *
                   14461: 
1.243     albertel 14462: 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 14463: 
                   14464: =item *
                   14465: 
1.243     albertel 14466: 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 14467: 
                   14468: =item *
                   14469: 
1.243     albertel 14470: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 14471: 
                   14472: =item *
                   14473: 
1.243     albertel 14474: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   14475: forcing spreadsheet to reevaluate the resource scores next time.
                   14476: 
1.1195    raeburn  14477: =item * 
                   14478: 
1.1196    raeburn  14479: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   14480: when viewing in course context.
1.1195    raeburn  14481: 
1.1196    raeburn  14482:  input: six args -- filename (decluttered), course number, course domain,
                   14483:                     url, symb (if registered) and group (if this is a 
                   14484:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  14485: 
1.1196    raeburn  14486:  output: array of five scalars --
1.1195    raeburn  14487:          $cfile -- url for file editing if editable on current server
                   14488:          $home -- homeserver of resource (i.e., for author if published,
                   14489:                                           or course if uploaded.).
                   14490:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  14491:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   14492:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  14493: 
                   14494: =item *
                   14495: 
                   14496: is_course_upload($file,$cnum,$cdom)
                   14497: 
                   14498: Used in course context to determine if current file was uploaded to 
                   14499: the course (i.e., would be found in /userfiles/docs on the course's 
                   14500: homeserver.
                   14501: 
                   14502:   input: 3 args -- filename (decluttered), course number and course domain.
                   14503:   output: boolean -- 1 if file was uploaded.
                   14504: 
1.243     albertel 14505: =back
                   14506: 
                   14507: =head2 Storing/Retreiving Data
                   14508: 
                   14509: =over 4
1.191     harris41 14510: 
                   14511: =item *
                   14512: 
1.1269    raeburn  14513: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   14514: permanently for this url; hashref needs to be given and should be a \%hashname;
                   14515: the remaining args aren't required and if they aren't passed or are '' they will
                   14516: be derived from the env (with the exception of $laststore, which is an 
                   14517: optional arg used when a user's submission is stored in grading).
                   14518: $laststore is $version=$timestamp, where $version is the most recent version
                   14519: number retrieved for the corresponding $symb in the $namespace db file, and
                   14520: $timestamp is the timestamp for that transaction (UNIX time).
                   14521: $laststore is currently only passed when cstore() is called by 
                   14522: structuretags::finalize_storage().
1.191     harris41 14523: 
                   14524: =item *
                   14525: 
1.1269    raeburn  14526: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   14527: but uses critical subroutine
1.191     harris41 14528: 
                   14529: =item *
                   14530: 
1.243     albertel 14531: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   14532: all args are optional
1.191     harris41 14533: 
                   14534: =item *
                   14535: 
1.717     albertel 14536: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   14537: dumps the complete (or key matching regexp) namespace into a hash
                   14538: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   14539: normally &store()ed into
                   14540: 
                   14541: $range should be either an integer '100' (give me the first 100
                   14542:                                            matching records)
                   14543:               or be  two integers sperated by a - with no spaces
                   14544:                  '30-50' (give me the 30th through the 50th matching
                   14545:                           records)
                   14546: 
                   14547: 
                   14548: =item *
                   14549: 
1.1269    raeburn  14550: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 14551: replaces a &store() version of data with a replacement set of data
                   14552: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  14553: reference. If $tolog is true, the transaction is logged in the courselog
                   14554: with an action=PUTSTORE.
1.717     albertel 14555: 
                   14556: =item *
                   14557: 
1.243     albertel 14558: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   14559: works very similar to store/cstore, but all data is stored in a
                   14560: temporary location and can be reset using tmpreset, $storehash should
                   14561: be a hash reference, returns nothing on success
1.191     harris41 14562: 
                   14563: =item *
                   14564: 
1.243     albertel 14565: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   14566: similar to restore, but all data is stored in a temporary location and
                   14567: can be reset using tmpreset. Returns a hash of values on success,
                   14568: error string otherwise.
1.191     harris41 14569: 
                   14570: =item *
                   14571: 
1.243     albertel 14572: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   14573: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 14574: 
                   14575: =item *
                   14576: 
1.243     albertel 14577: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14578: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 14579: 
                   14580: =item *
                   14581: 
1.243     albertel 14582: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   14583: namesp ($udom and $uname are optional)
1.191     harris41 14584: 
                   14585: =item *
                   14586: 
1.702     albertel 14587: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 14588: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 14589: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  14590: 
1.702     albertel 14591: $range should be either an integer '100' (give me the first 100
                   14592:                                            matching records)
                   14593:               or be  two integers sperated by a - with no spaces
                   14594:                  '30-50' (give me the 30th through the 50th matching
                   14595:                           records)
1.449     matthew  14596: =item *
                   14597: 
                   14598: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   14599: $store can be a scalar, an array reference, or if the amount to be 
                   14600: incremented is > 1, a hash reference.
                   14601: 
                   14602: ($udom and $uname are optional)
1.191     harris41 14603: 
                   14604: =item *
                   14605: 
1.243     albertel 14606: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   14607: ($udom and $uname are optional)
1.191     harris41 14608: 
                   14609: =item *
                   14610: 
1.243     albertel 14611: cput($namespace,$storehash,$udom,$uname) : critical put
                   14612: ($udom and $uname are optional)
1.191     harris41 14613: 
                   14614: =item *
                   14615: 
1.748     albertel 14616: newput($namespace,$storehash,$udom,$uname) :
                   14617: 
                   14618: Attempts to store the items in the $storehash, but only if they don't
                   14619: currently exist, if this succeeds you can be certain that you have 
                   14620: successfully created a new key value pair in the $namespace db.
                   14621: 
                   14622: 
                   14623: Args:
                   14624:  $namespace: name of database to store values to
                   14625:  $storehash: hashref to store to the db
                   14626:  $udom: (optional) domain of user containing the db
                   14627:  $uname: (optional) name of user caontaining the db
                   14628: 
                   14629: Returns:
                   14630:  'ok' -> succeeded in storing all keys of $storehash
                   14631:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   14632:                         least <key> already existed in the db (other
                   14633:                         requested keys may also already exist)
1.967     bisitz   14634:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 14635:  'con_lost' -> unable to contact request server
                   14636:  'refused' -> action was not allowed by remote machine
                   14637: 
                   14638: 
                   14639: =item *
                   14640: 
1.243     albertel 14641: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14642: reference filled in from namesp (encrypts the return communication)
                   14643: ($udom and $uname are optional)
1.191     harris41 14644: 
                   14645: =item *
                   14646: 
1.243     albertel 14647: log($udom,$name,$home,$message) : write to permanent log for user; use
                   14648: critical subroutine
                   14649: 
1.806     raeburn  14650: =item *
                   14651: 
1.860     raeburn  14652: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   14653: array reference filled in from namespace found in domain level on either
                   14654: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  14655: 
                   14656: =item *
                   14657: 
1.860     raeburn  14658: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   14659: domain level either on specified domain server ($uhome) or primary domain 
                   14660: server ($udom and $uhome are optional)
1.806     raeburn  14661: 
1.943     raeburn  14662: =item * 
                   14663: 
1.1240    raeburn  14664: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   14665: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   14666: the target domain.
                   14667: 
                   14668: May also include additional key => value pairs for the following groups:
                   14669: 
                   14670: =over
                   14671: 
                   14672: =item
                   14673: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   14674: 
                   14675: =over
                   14676: 
                   14677: =item defaultquota, authorquota
                   14678: 
                   14679: =back
                   14680: 
                   14681: =item
                   14682: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   14683: portfolio for users).
                   14684: 
                   14685: =over
                   14686: 
                   14687: =item
                   14688: aboutme, blog, webdav, portfolio
                   14689: 
                   14690: =back
                   14691: 
                   14692: =item
                   14693: requestcourses: ability to request courses, and how requests are processed.
                   14694: 
                   14695: =over
                   14696: 
                   14697: =item
1.1305    raeburn  14698: official, unofficial, community, textbook, placement
1.1240    raeburn  14699: 
                   14700: =back
                   14701: 
                   14702: =item
                   14703: inststatus: types of institutional affiliation, and order in which they are displayed.
                   14704: 
                   14705: =over
                   14706: 
                   14707: =item
1.1256    raeburn  14708: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  14709: 
                   14710: =back
                   14711: 
                   14712: =item
                   14713: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   14714: for course's uploaded content.
                   14715: 
                   14716: =over
                   14717: 
                   14718: =item
1.1246    raeburn  14719: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  14720: communityquota, textbookquota, placementquota
1.1240    raeburn  14721: 
                   14722: =back
                   14723: 
                   14724: =item
                   14725: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   14726: on your servers.
                   14727: 
                   14728: =over
                   14729: 
                   14730: =item 
                   14731: remotesessions, hostedsessions
                   14732: 
                   14733: =back
                   14734: 
                   14735: =back
                   14736: 
                   14737: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   14738: utility to create a configuration.db file on a domain's primary library server 
                   14739: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   14740: -- corresponding values are authentication type (internal, krb4, krb5,
                   14741: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   14742: will be available. Values are retrieved from cache (if current), unless the
                   14743: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   14744: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   14745: 
                   14746: Typical usage:
1.943     raeburn  14747: 
1.1240    raeburn  14748: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  14749: 
1.243     albertel 14750: =back
                   14751: 
                   14752: =head2 Network Status Functions
                   14753: 
                   14754: =over 4
1.191     harris41 14755: 
                   14756: =item *
                   14757: 
1.1137    raeburn  14758: dirlist() : return directory list based on URI (first arg).
                   14759: 
                   14760: Inputs: 1 required, 5 optional.
                   14761: 
                   14762: =over
                   14763: 
                   14764: =item 
                   14765: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   14766: 
                   14767: =item
                   14768: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   14769: 
                   14770: =item
                   14771: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   14772: 
                   14773: =item
                   14774: $getpropath - boolean: 1 if prepend path using &propath(). 
                   14775: 
                   14776: =item
                   14777: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   14778: 
                   14779: =item 
                   14780: $alternateRoot - path to prepend in place of path from $uri.
                   14781: 
                   14782: =back
                   14783: 
                   14784: Returns: Array of up to two items.
                   14785: 
                   14786: =over
                   14787: 
                   14788: a reference to an array of files/subdirectories
                   14789: 
                   14790: =over
                   14791: 
                   14792: Each element in the array of files/subdirectories is a & separated list of
                   14793: item name and the result of running stat on the item.  If dirlist was requested
                   14794: for a file instead of a directory, the item name will be ''. For a directory 
                   14795: listing, if the item is a metadata file, the element will end &N&M 
                   14796: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   14797: default copyright set (1).  
                   14798: 
                   14799: =back
                   14800: 
                   14801: a scalar containing error condition (if encountered).
                   14802: 
                   14803: =over
                   14804: 
                   14805: =item 
                   14806: no_host (no homeserver identified for $username:$domain).
                   14807: 
                   14808: =item 
                   14809: no_such_host (server contacted for listing not identified as valid host).
                   14810: 
                   14811: =item 
                   14812: con_lost (connection to remote server failed).
                   14813: 
                   14814: =item 
                   14815: refused (invalid $username:$domain received on lond side).
                   14816: 
                   14817: =item 
                   14818: no_such_dir (directory at specified path on lond side does not exist). 
                   14819: 
                   14820: =item 
                   14821: empty (directory at specified path on lond side is empty).
                   14822: 
                   14823: =over
                   14824: 
                   14825: This is currently not encountered because the &ls3, &ls2, 
                   14826: &ls (_handler) routines on the lond side do not filter out
                   14827: . and .. from a directory listing. 
                   14828: 
                   14829: =back
                   14830: 
                   14831: =back
                   14832: 
                   14833: =back
1.191     harris41 14834: 
                   14835: =item *
                   14836: 
1.243     albertel 14837: spareserver() : find server with least workload from spare.tab
                   14838: 
1.986     foxr     14839: 
                   14840: =item *
                   14841: 
                   14842: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   14843: if there is no corresponding loncapa host.
                   14844: 
1.243     albertel 14845: =back
                   14846: 
1.986     foxr     14847: 
1.243     albertel 14848: =head2 Apache Request
                   14849: 
                   14850: =over 4
1.191     harris41 14851: 
                   14852: =item *
                   14853: 
1.243     albertel 14854: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   14855: localhost, posts hash
                   14856: 
                   14857: =back
                   14858: 
                   14859: =head2 Data to String to Data
                   14860: 
                   14861: =over 4
1.191     harris41 14862: 
                   14863: =item *
                   14864: 
1.243     albertel 14865: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   14866: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 14867: 
                   14868: =item *
                   14869: 
1.243     albertel 14870: hashref2str($hashref) : convert a hashref into a string complete with
                   14871: escaping and '=' and '&' separators, supports elements that are
                   14872: arrayrefs and hashrefs
1.191     harris41 14873: 
                   14874: =item *
                   14875: 
1.243     albertel 14876: arrayref2str($arrayref) : convert an arrayref into a string complete
                   14877: with escaping and '&' separators, supports elements that are arrayrefs
                   14878: and hashrefs
1.191     harris41 14879: 
                   14880: =item *
                   14881: 
1.243     albertel 14882: str2hash($string) : convert string to hash using unescaping and
                   14883: splitting on '=' and '&', supports elements that are arrayrefs and
                   14884: hashrefs
1.191     harris41 14885: 
                   14886: =item *
                   14887: 
1.243     albertel 14888: str2array($string) : convert string to hash using unescaping and
                   14889: splitting on '&', supports elements that are arrayrefs and hashrefs
                   14890: 
                   14891: =back
                   14892: 
                   14893: =head2 Logging Routines
                   14894: 
                   14895: 
                   14896: These routines allow one to make log messages in the lonnet.log and
                   14897: lonnet.perm logfiles.
1.191     harris41 14898: 
1.1119    foxr     14899: =over 4
                   14900: 
1.191     harris41 14901: =item *
                   14902: 
1.243     albertel 14903: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 14904: 
                   14905: =item *
                   14906: 
1.243     albertel 14907: logthis() : append message to the normal lonnet.log file, it gets
                   14908: preiodically rolled over and deleted.
1.191     harris41 14909: 
                   14910: =item *
                   14911: 
1.243     albertel 14912: logperm() : append a permanent message to lonnet.perm.log, this log
                   14913: file never gets deleted by any automated portion of the system, only
                   14914: messages of critical importance should go in here.
                   14915: 
1.1119    foxr     14916: 
1.243     albertel 14917: =back
                   14918: 
                   14919: =head2 General File Helper Routines
                   14920: 
                   14921: =over 4
1.191     harris41 14922: 
                   14923: =item *
                   14924: 
1.481     raeburn  14925: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   14926: (a) files in /uploaded
                   14927:   (i) If a local copy of the file exists - 
                   14928:       compares modification date of local copy with last-modified date for 
                   14929:       definitive version stored on home server for course. If local copy is 
                   14930:       stale, requests a new version from the home server and stores it. 
                   14931:       If the original has been removed from the home server, then local copy 
                   14932:       is unlinked.
                   14933:   (ii) If local copy does not exist -
                   14934:       requests the file from the home server and stores it. 
                   14935:   
                   14936:   If $caller is 'uploadrep':  
                   14937:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   14938:     for request for files originally uploaded via DOCS. 
                   14939:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   14940:   
                   14941:   Otherwise:
                   14942:      This indicates a call from the content generation phase of the request.
                   14943:      -  returns the entire contents of the file or -1.
                   14944:      
                   14945: (b) files in /res
                   14946:    - returns the entire contents of a file or -1; 
                   14947:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 14948: 
1.712     albertel 14949: 
                   14950: =item *
                   14951: 
                   14952: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   14953:                   reference
                   14954: 
                   14955: returns either a stat() list of data about the file or an empty list
                   14956: if the file doesn't exist or couldn't find out about it (connection
                   14957: problems or user unknown)
                   14958: 
1.191     harris41 14959: =item *
                   14960: 
1.243     albertel 14961: filelocation($dir,$file) : returns file system location of a file
                   14962: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   14963: directory that relative $file lookups are to looked in ($dir of /a/dir
                   14964: and a file of ../bob will become /a/bob)
1.191     harris41 14965: 
                   14966: =item *
                   14967: 
                   14968: hreflocation($dir,$file) : returns file system location or a URL; same as
                   14969: filelocation except for hrefs
                   14970: 
                   14971: =item *
                   14972: 
1.1261    raeburn  14973: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   14974: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 14975: 
1.243     albertel 14976: =back
                   14977: 
1.608     albertel 14978: =head2 Usererfile file routines (/uploaded*)
                   14979: 
                   14980: =over 4
                   14981: 
                   14982: =item *
                   14983: 
                   14984: userfileupload(): main rotine for putting a file in a user or course's
                   14985:                   filespace, arguments are,
                   14986: 
1.620     albertel 14987:  formname - required - this is the name of the element in $env where the
1.608     albertel 14988:            filename, and the contents of the file to create/modifed exist
1.620     albertel 14989:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   14990:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  14991:  context - if coursedoc, store the file in the course of the active role
                   14992:              of the current user; 
                   14993:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   14994:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 14995:  subdir - required - subdirectory to put the file in under ../userfiles/
                   14996:          if undefined, it will be placed in "unknown"
                   14997: 
                   14998:  (This routine calls clean_filename() to remove any dangerous
                   14999:  characters from the filename, and then calls finuserfileupload() to
                   15000:  complete the transaction)
                   15001: 
                   15002:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15003:  and /adm/notfound.html if unsuccessful
                   15004: 
                   15005: =item *
                   15006: 
                   15007: clean_filename(): routine for cleaing a filename up for storage in
                   15008:                  userfile space, argument is:
                   15009: 
                   15010:  filename - proposed filename
                   15011: 
                   15012: returns: the new clean filename
                   15013: 
                   15014: =item *
                   15015: 
1.1090    raeburn  15016: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15017: userspace, probably shouldn't be called directly
                   15018: 
                   15019:   docuname: username or courseid of destination for the file
                   15020:   docudom: domain of user/course of destination for the file
                   15021:   formname: same as for userfileupload()
1.1090    raeburn  15022:   fname: filename (including subdirectories) for the file
                   15023:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   15024:   allfiles: reference to hash used to store objects found by parser
                   15025:   codebase: reference to hash used for codebases of java objects found by parser
                   15026:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15027:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15028:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15029:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15030:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15031:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15032:   mimetype: reference to scalar to accommodate mime type determined
                   15033:             from File::MMagic if $parser = parse.
1.608     albertel 15034: 
                   15035:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15036:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15037:  was 'overwrite').
                   15038:  
1.608     albertel 15039: 
                   15040: =item *
                   15041: 
                   15042: renameuserfile(): renames an existing userfile to a new name
                   15043: 
                   15044:   Args:
                   15045:    docuname: username or courseid of destination for the file
                   15046:    docudom: domain of user/course of destination for the file
                   15047:    old: current file name (including any subdirs under userfiles)
                   15048:    new: desired file name (including any subdirs under userfiles)
                   15049: 
                   15050: =item *
                   15051: 
                   15052: mkdiruserfile(): creates a directory is a userfiles dir
                   15053: 
                   15054:   Args:
                   15055:    docuname: username or courseid of destination for the file
                   15056:    docudom: domain of user/course of destination for the file
                   15057:    dir: dir to create (including any subdirs under userfiles)
                   15058: 
                   15059: =item *
                   15060: 
                   15061: removeuserfile(): removes a file that exists in userfiles
                   15062: 
                   15063:   Args:
                   15064:    docuname: username or courseid of destination for the file
                   15065:    docudom: domain of user/course of destination for the file
                   15066:    fname: filname to delete (including any subdirs under userfiles)
                   15067: 
                   15068: =item *
                   15069: 
                   15070: removeuploadedurl(): convience function for removeuserfile()
                   15071: 
                   15072:   Args:
                   15073:    url:  a full /uploaded/... url to delete
                   15074: 
1.747     albertel 15075: =item * 
                   15076: 
                   15077: get_portfile_permissions():
                   15078:   Args:
                   15079:     domain: domain of user or course contain the portfolio files
                   15080:     user: name of user or num of course contain the portfolio files
                   15081:   Returns:
                   15082:     hashref of a dump of the proper file_permissions.db
                   15083:    
                   15084: 
                   15085: =item * 
                   15086: 
                   15087: get_access_controls():
                   15088: 
                   15089: Args:
                   15090:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15091:   group: (optional) the group you want the files associated with
                   15092:   file: (optional) the file you want access info on
                   15093: 
                   15094: Returns:
1.749     raeburn  15095:     a hash (keys are file names) of hashes containing
                   15096:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15097:         values are XML containing access control settings (see below) 
1.747     albertel 15098: 
                   15099: Internal notes:
                   15100: 
1.749     raeburn  15101:  access controls are stored in file_permissions.db as key=value pairs.
                   15102:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15103:         where scope -> public,guest,course,group,domains or users.
                   15104:               end -> UNIX time for end of access (0 -> no end date)
                   15105:               start -> UNIX time for start of access
                   15106: 
                   15107:     value -> XML description of access control
                   15108:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15109:             <start></start>
                   15110:             <end></end>
                   15111: 
                   15112:             <password></password>  for scope type = guest
                   15113: 
                   15114:             <domain></domain>     for scope type = course or group
                   15115:             <number></number>
                   15116:             <roles id="">
                   15117:              <role></role>
                   15118:              <access></access>
                   15119:              <section></section>
                   15120:              <group></group>
                   15121:             </roles>
                   15122: 
                   15123:             <dom></dom>         for scope type = domains
                   15124: 
                   15125:             <users>             for scope type = users
                   15126:              <user>
                   15127:               <uname></uname>
                   15128:               <udom></udom>
                   15129:              </user>
                   15130:             </users>
                   15131:            </scope> 
                   15132:               
                   15133:  Access data is also aggregated for each file in an additional key=value pair:
                   15134:  key -> path to file/file_name\0accesscontrol 
                   15135:  value -> reference to hash
                   15136:           hash contains key = value pairs
                   15137:           where key = uniqueID:scope_end_start
                   15138:                 value = UNIX time record was last updated
                   15139: 
                   15140:           Used to improve speed of look-ups of access controls for each file.  
                   15141:  
                   15142:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15143: 
1.1198    raeburn  15144: =item *
                   15145: 
1.749     raeburn  15146: modify_access_controls():
                   15147: 
                   15148: Modifies access controls for a portfolio file
                   15149: Args
                   15150: 1. file name
                   15151: 2. reference to hash of required changes,
                   15152: 3. domain
                   15153: 4. username
                   15154:   where domain,username are the domain of the portfolio owner 
                   15155:   (either a user or a course) 
                   15156: 
                   15157: Returns:
                   15158: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15159: 2. result of deletions ('ok' or 'error', with error message).
                   15160: 3. reference to hash of any new or updated access controls.
                   15161: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15162:    key = integer (inbound ID)
1.1198    raeburn  15163:    value = uniqueID
                   15164: 
                   15165: =item *
                   15166: 
                   15167: get_timebased_id():
                   15168: 
                   15169: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   15170: course via the Course Editor (e.g., folders, composite pages, 
                   15171: group bulletin boards).
                   15172: 
                   15173: Args: (first three required; six others optional)
                   15174: 
                   15175: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15176:    docssequence, or name of group
                   15177: 
                   15178: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15179:    e.g., num, boardids
                   15180: 
                   15181: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   15182:    file will be named nohist_namespace.db
                   15183: 
                   15184: 4. cdom: domain of course; default is current course domain from %env
                   15185: 
                   15186: 5. cnum: course number; default is current course number from %env
                   15187: 
                   15188: 6. idtype: set to concat if an additional digit is to be appended to the 
                   15189:    unix timestamp to form the suffix, if the plain timestamp is already
                   15190:    in use.  Default is to not do this, but simply increment the unix 
                   15191:    timestamp by 1 until a unique key is obtained.
                   15192: 
                   15193: 7. who: holder of locking key; defaults to user:domain for user.
                   15194: 
                   15195: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   15196:    retrying); default is 3.
                   15197: 
                   15198: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   15199: 
                   15200: Returns:
                   15201: 
                   15202: 1. suffix obtained (numeric)
                   15203: 
                   15204: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15205: 
                   15206: 3. error: contains (localized) error message if an error occurred.
                   15207: 
1.747     albertel 15208: 
1.608     albertel 15209: =back
                   15210: 
1.243     albertel 15211: =head2 HTTP Helper Routines
                   15212: 
                   15213: =over 4
                   15214: 
1.191     harris41 15215: =item *
                   15216: 
                   15217: escape() : unpack non-word characters into CGI-compatible hex codes
                   15218: 
                   15219: =item *
                   15220: 
                   15221: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15222: 
1.243     albertel 15223: =back
                   15224: 
                   15225: =head1 PRIVATE SUBROUTINES
                   15226: 
                   15227: =head2 Underlying communication routines (Shouldn't call)
                   15228: 
                   15229: =over 4
                   15230: 
                   15231: =item *
                   15232: 
                   15233: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15234: 
                   15235: =item *
                   15236: 
                   15237: reply() : uses subreply to send a message to remote machine, logs all failures
                   15238: 
                   15239: =item *
                   15240: 
                   15241: critical() : passes a critical message to another server; if cannot
                   15242: get through then place message in connection buffer directory and
                   15243: returns con_delayed, if incapable of saving message, returns
                   15244: con_failed
                   15245: 
                   15246: =item *
                   15247: 
                   15248: reconlonc() : tries to reconnect lonc client processes.
                   15249: 
                   15250: =back
                   15251: 
                   15252: =head2 Resource Access Logging
                   15253: 
                   15254: =over 4
                   15255: 
                   15256: =item *
                   15257: 
                   15258: flushcourselogs() : flush (save) buffer logs and access logs
                   15259: 
                   15260: =item *
                   15261: 
                   15262: courselog($what) : save message for course in hash
                   15263: 
                   15264: =item *
                   15265: 
                   15266: courseacclog($what) : save message for course using &courselog().  Perform
                   15267: special processing for specific resource types (problems, exams, quizzes, etc).
                   15268: 
1.191     harris41 15269: =item *
                   15270: 
                   15271: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15272: as a PerlChildExitHandler
1.243     albertel 15273: 
                   15274: =back
                   15275: 
                   15276: =head2 Other
                   15277: 
                   15278: =over 4
                   15279: 
                   15280: =item *
                   15281: 
                   15282: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15283: 
                   15284: =back
                   15285: 
                   15286: =cut
1.877     foxr     15287: 

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