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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.106! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.105 2019/02/18 15:19:30 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.1172.2.104  raeburn    78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
1.1138    raeburn    79:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
                     80:             %managerstab);
1.871     albertel   81: 
                     82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     83:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     84:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        85:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        86: 
1.1       albertel   87: use IO::Socket;
1.31      www        88: use GDBM_File;
1.208     albertel   89: use HTML::LCParser;
1.88      www        90: use Fcntl qw(:flock);
1.870     albertel   91: use Storable qw(thaw nfreeze);
1.1172.2.79  raeburn    92: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599     albertel   93: use Cache::Memcached;
1.676     albertel   94: use Digest::MD5;
1.790     albertel   95: use Math::Random;
1.1024    raeburn    96: use File::MMagic;
1.807     albertel   97: use LONCAPA qw(:DEFAULT :match);
1.740     www        98: use LONCAPA::Configuration;
1.1160    www        99: use LONCAPA::lonmetadata;
1.1172.2.22  raeburn   100: use LONCAPA::Lond;
1.1117    foxr      101: 
1.1090    raeburn   102: use File::Copy;
1.676     albertel  103: 
1.195     www       104: my $readit;
1.1172.2.79  raeburn   105: my $max_connection_retries = 20;     # Or some such value.
1.1       albertel  106: 
1.619     albertel  107: require Exporter;
                    108: 
                    109: our @ISA = qw (Exporter);
                    110: our @EXPORT = qw(%env);
                    111: 
1.1172.2.9  raeburn   112: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       113: {
                    114:     my $logid;
1.1172.2.9  raeburn   115:     sub write_log {
                    116: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    117:         if ($context eq 'course') {
                    118:             if (($cnum eq '') || ($cdom eq '')) {
                    119:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    120:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    121:             }
1.957     raeburn   122:         }
1.1172.2.13  raeburn   123: 	$logid ++;
1.957     raeburn   124:         my $now = time();
                    125: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.9  raeburn   126:         my $logentry = {
                    127:                          $id => {
                    128:                                   'exe_uname' => $env{'user.name'},
                    129:                                   'exe_udom'  => $env{'user.domain'},
                    130:                                   'exe_time'  => $now,
                    131:                                   'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    132:                                   'delflag'   => $delflag,
                    133:                                   'logentry'  => $storehash,
                    134:                                   'uname'     => $uname,
                    135:                                   'udom'      => $udom,
                    136:                                 }
                    137:                        };
                    138:         return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       139:     }
                    140: }
1.1       albertel  141: 
1.163     harris41  142: sub logtouch {
                    143:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  144:     unless (-e "$execdir/logs/lonnet.log") {	
1.1172.2.96  raeburn   145: 	open(my $fh,">>","$execdir/logs/lonnet.log");
1.163     harris41  146: 	close $fh;
                    147:     }
                    148:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    149:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    150: }
                    151: 
1.1       albertel  152: sub logthis {
                    153:     my $message=shift;
                    154:     my $execdir=$perlvar{'lonDaemons'};
                    155:     my $now=time;
                    156:     my $local=localtime($now);
1.1172.2.96  raeburn   157:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986     foxr      158: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    159: 	print $fh $logstring;
1.448     albertel  160: 	close($fh);
                    161:     }
1.1       albertel  162:     return 1;
                    163: }
                    164: 
                    165: sub logperm {
                    166:     my $message=shift;
                    167:     my $execdir=$perlvar{'lonDaemons'};
                    168:     my $now=time;
                    169:     my $local=localtime($now);
1.1172.2.96  raeburn   170:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448     albertel  171: 	print $fh "$now:$message:$local\n";
                    172: 	close($fh);
                    173:     }
1.1       albertel  174:     return 1;
                    175: }
                    176: 
1.850     albertel  177: sub create_connection {
1.853     albertel  178:     my ($hostname,$lonid) = @_;
1.851     albertel  179:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  180: 				     Type    => SOCK_STREAM,
                    181: 				     Timeout => 10);
                    182:     return 0 if (!$client);
1.890     albertel  183:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  184:     my $result = <$client>;
                    185:     chomp($result);
                    186:     return 1 if ($result eq 'done');
                    187:     return 0;
                    188: }
                    189: 
1.983     raeburn   190: sub get_server_timezone {
                    191:     my ($cnum,$cdom) = @_;
                    192:     my $home=&homeserver($cnum,$cdom);
                    193:     if ($home ne 'no_host') {
                    194:         my $cachetime = 24*3600;
                    195:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    196:         if (defined($cached)) {
                    197:             return $timezone;
                    198:         } else {
                    199:             my $timezone = &reply('servertimezone',$home);
                    200:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    201:         }
                    202:     }
                    203: }
1.850     albertel  204: 
1.1106    raeburn   205: sub get_server_distarch {
                    206:     my ($lonhost,$ignore_cache) = @_;
                    207:     if (defined($lonhost)) {
                    208:         if (!defined(&hostname($lonhost))) {
                    209:             return;
                    210:         }
                    211:         my $cachetime = 12*3600;
                    212:         if (!$ignore_cache) {
                    213:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    214:             if (defined($cached)) {
                    215:                 return $distarch;
                    216:             }
                    217:         }
                    218:         my $rep = &reply('serverdistarch',$lonhost);
                    219:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    220:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    221:                 $rep eq '') {
                    222:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    223:         }
                    224:     }
                    225:     return;
                    226: }
                    227: 
1.993     raeburn   228: sub get_server_loncaparev {
1.1073    raeburn   229:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   230:     if (defined($lonhost)) {
                    231:         if (!defined(&hostname($lonhost))) {
                    232:             undef($lonhost);
                    233:         }
                    234:     }
                    235:     if (!defined($lonhost)) {
                    236:         if (defined(&domain($dom,'primary'))) {
                    237:             $lonhost=&domain($dom,'primary');
                    238:             if ($lonhost eq 'no_host') {
                    239:                 undef($lonhost);
                    240:             }
                    241:         }
                    242:     }
                    243:     if (defined($lonhost)) {
1.1073    raeburn   244:         my $cachetime = 12*3600;
                    245:         if (!$ignore_cache) {
                    246:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    247:             if (defined($cached)) {
                    248:                 return $loncaparev;
                    249:             }
                    250:         }
                    251:         my ($answer,$loncaparev);
                    252:         my @ids=&current_machine_ids();
                    253:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    254:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   255:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   256:                 $loncaparev = $1;
                    257:             }
                    258:         } else {
                    259:             $answer = &reply('serverloncaparev',$lonhost);
                    260:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    261:                 if ($caller eq 'loncron') {
                    262:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   263:                     $ua->timeout(4);
1.1073    raeburn   264:                     my $protocol = $protocol{$lonhost};
                    265:                     $protocol = 'http' if ($protocol ne 'https');
                    266:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    267:                     my $request=new HTTP::Request('GET',$url);
                    268:                     my $response=$ua->request($request);
                    269:                     unless ($response->is_error()) {
                    270:                         my $content = $response->content;
1.1081    raeburn   271:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   272:                             $loncaparev = $1;
                    273:                         }
                    274:                     }
                    275:                 } else {
                    276:                     $loncaparev = $loncaparevs{$lonhost};
                    277:                 }
1.1081    raeburn   278:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   279:                 $loncaparev = $1;
                    280:             }
1.993     raeburn   281:         }
1.1073    raeburn   282:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   283:     }
                    284: }
                    285: 
1.1074    raeburn   286: sub get_server_homeID {
                    287:     my ($hostname,$ignore_cache,$caller) = @_;
                    288:     unless ($ignore_cache) {
                    289:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    290:         if (defined($cached)) {
                    291:             return $serverhomeID;
                    292:         }
                    293:     }
                    294:     my $cachetime = 12*3600;
                    295:     my $serverhomeID;
                    296:     if ($caller eq 'loncron') { 
                    297:         my @machine_ids = &machine_ids($hostname);
                    298:         foreach my $id (@machine_ids) {
                    299:             my $response = &reply('serverhomeID',$id);
                    300:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    301:                 $serverhomeID = $response;
                    302:                 last;
                    303:             }
                    304:         }
                    305:         if ($serverhomeID eq '') {
                    306:             $serverhomeID = $machine_ids[-1];
                    307:         }
                    308:     } else {
                    309:         $serverhomeID = $serverhomeIDs{$hostname};
                    310:     }
                    311:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    312: }
                    313: 
1.1121    raeburn   314: sub get_remote_globals {
                    315:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   316:     my ($result,%returnhash,%whatneeded);
                    317:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   318:         foreach my $what (sort(keys(%{$whathash}))) {
                    319:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   320:             my ($response,$cached);
1.1121    raeburn   321:             unless ($ignore_cache) {
1.1125    raeburn   322:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   323:             }
                    324:             if (defined($cached)) {
1.1125    raeburn   325:                 $returnhash{$what} = $response;
1.1121    raeburn   326:             } else {
1.1125    raeburn   327:                 $whatneeded{$what} = 1;
1.1121    raeburn   328:             }
                    329:         }
1.1125    raeburn   330:         if (keys(%whatneeded) == 0) {
                    331:             $result = 'ok';
                    332:         } else {
1.1121    raeburn   333:             my $requested = &freeze_escape(\%whatneeded);
                    334:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   335:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    336:                 ($rep eq 'unknown_cmd')) {
                    337:                 $result = $rep;
                    338:             } else {
                    339:                 $result = 'ok';
1.1121    raeburn   340:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   341:                 foreach my $item (@pairs) {
                    342:                     my ($key,$value)=split(/=/,$item,2);
                    343:                     my $what = &unescape($key);
                    344:                     my $hashid = $lonhost.'-'.$what;
                    345:                     $returnhash{$what}=&thaw_unescape($value);
                    346:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   347:                 }
                    348:             }
                    349:         }
                    350:     }
1.1125    raeburn   351:     return ($result,\%returnhash);
1.1121    raeburn   352: }
                    353: 
1.1124    raeburn   354: sub remote_devalidate_cache {
1.1172.2.35  raeburn   355:     my ($lonhost,$cachekeys) = @_;
                    356:     my $items;
                    357:     return unless (ref($cachekeys) eq 'ARRAY');
                    358:     my $cachestr = join('&',@{$cachekeys});
                    359:     return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   360: }
                    361: 
1.1       albertel  362: # -------------------------------------------------- Non-critical communication
                    363: sub subreply {
                    364:     my ($cmd,$server)=@_;
1.838     albertel  365:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      366:     #
                    367:     #  With loncnew process trimming, there's a timing hole between lonc server
                    368:     #  process exit and the master server picking up the listen on the AF_UNIX
                    369:     #  socket.  In that time interval, a lock file will exist:
                    370: 
                    371:     my $lockfile=$peerfile.".lock";
                    372:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1172.2.79  raeburn   373: 	sleep(0.1);
1.549     foxr      374:     }
                    375:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      376:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      377:     #
1.550     foxr      378:     #   We'll give the connection a few tries before abandoning it.  If
                    379:     #   connection is not possible, we'll con_lost back to the client.
                    380:     #   
                    381:     my $client;
                    382:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    383: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    384: 				      Type    => SOCK_STREAM,
                    385: 				      Timeout => 10);
1.869     albertel  386: 	if ($client) {
1.550     foxr      387: 	    last;		# Connected!
1.850     albertel  388: 	} else {
1.853     albertel  389: 	    &create_connection(&hostname($server),$server);
1.550     foxr      390: 	}
1.1172.2.79  raeburn   391:         sleep(0.1);		# Try again later if failed connection.
1.550     foxr      392:     }
                    393:     my $answer;
                    394:     if ($client) {
1.704     albertel  395: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      396: 	$answer=<$client>;
                    397: 	if (!$answer) { $answer="con_lost"; }
                    398: 	chomp($answer);
                    399:     } else {
                    400: 	$answer = 'con_lost';	# Failed connection.
                    401:     }
1.1       albertel  402:     return $answer;
                    403: }
                    404: 
                    405: sub reply {
                    406:     my ($cmd,$server)=@_;
1.838     albertel  407:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  408:     my $answer=subreply($cmd,$server);
1.65      www       409:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  410:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       411:                 " $cmd to $server returned $answer</font>");
                    412:     }
1.1       albertel  413:     return $answer;
                    414: }
                    415: 
                    416: # ----------------------------------------------------------- Send USR1 to lonc
                    417: 
                    418: sub reconlonc {
1.891     albertel  419:     my ($lonid) = @_;
                    420:     if ($lonid) {
1.1172.2.72  raeburn   421:         my $hostname = &hostname($lonid);
1.891     albertel  422: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    423: 	if ($hostname && -e $peerfile) {
                    424: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    425: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    426: 					     Type    => SOCK_STREAM,
                    427: 					     Timeout => 10);
                    428: 	    if ($client) {
                    429: 		print $client ("reset_retries\n");
                    430: 		my $answer=<$client>;
                    431: 		#reset just this one.
                    432: 	    }
                    433: 	}
                    434: 	return;
                    435:     }
                    436: 
1.836     www       437:     &logthis("Trying to reconnect lonc");
1.1       albertel  438:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1172.2.96  raeburn   439:     if (open(my $fh,"<",$loncfile)) {
1.1       albertel  440: 	my $loncpid=<$fh>;
                    441:         chomp($loncpid);
                    442:         if (kill 0 => $loncpid) {
                    443: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    444:             kill USR1 => $loncpid;
                    445:             sleep 1;
1.836     www       446:          } else {
1.12      www       447: 	    &logthis(
1.672     albertel  448:                "<font color=\"blue\">WARNING:".
1.12      www       449:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  450:         }
                    451:     } else {
1.836     www       452: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  453:     }
                    454: }
                    455: 
                    456: # ------------------------------------------------------ Critical communication
1.12      www       457: 
1.1       albertel  458: sub critical {
                    459:     my ($cmd,$server)=@_;
1.838     albertel  460:     unless (&hostname($server)) {
1.672     albertel  461:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       462:                " Critical message to unknown server ($server)</font>");
                    463:         return 'no_such_host';
                    464:     }
1.1       albertel  465:     my $answer=reply($cmd,$server);
                    466:     if ($answer eq 'con_lost') {
1.1172.2.72  raeburn   467: 	&reconlonc($server);
1.589     albertel  468: 	my $answer=reply($cmd,$server);
1.1       albertel  469:         if ($answer eq 'con_lost') {
                    470:             my $now=time;
                    471:             my $middlename=$cmd;
1.5       www       472:             $middlename=substr($middlename,0,16);
1.1       albertel  473:             $middlename=~s/\W//g;
                    474:             my $dfilename=
1.305     www       475:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    476:             $dumpcount++;
1.1       albertel  477:             {
1.448     albertel  478: 		my $dfh;
1.1172.2.96  raeburn   479: 		if (open($dfh,">",$dfilename)) {
1.448     albertel  480: 		    print $dfh "$cmd\n"; 
                    481: 		    close($dfh);
                    482: 		}
1.1       albertel  483:             }
1.1172.2.79  raeburn   484:             sleep 1;
1.1       albertel  485:             my $wcmd='';
                    486:             {
1.448     albertel  487: 		my $dfh;
1.1172.2.96  raeburn   488: 		if (open($dfh,"<",$dfilename)) {
1.448     albertel  489: 		    $wcmd=<$dfh>; 
                    490: 		    close($dfh);
                    491: 		}
1.1       albertel  492:             }
                    493:             chomp($wcmd);
1.7       www       494:             if ($wcmd eq $cmd) {
1.672     albertel  495: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       496:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  497:                 &logperm("D:$server:$cmd");
                    498: 	        return 'con_delayed';
                    499:             } else {
1.672     albertel  500:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       501:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  502:                 &logperm("F:$server:$cmd");
                    503:                 return 'con_failed';
                    504:             }
                    505:         }
                    506:     }
                    507:     return $answer;
1.405     albertel  508: }
                    509: 
1.755     albertel  510: # ------------------------------------------- check if return value is an error
                    511: 
                    512: sub error {
                    513:     my ($result) = @_;
1.756     albertel  514:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  515: 	if ($2 == 2) { return undef; }
                    516: 	return $1;
                    517:     }
                    518:     return undef;
                    519: }
                    520: 
1.783     albertel  521: sub convert_and_load_session_env {
                    522:     my ($lonidsdir,$handle)=@_;
                    523:     my @profile;
                    524:     {
1.917     albertel  525: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    526: 	if (!$opened) {
1.915     albertel  527: 	    return 0;
                    528: 	}
1.783     albertel  529: 	flock($idf,LOCK_SH);
                    530: 	@profile=<$idf>;
                    531: 	close($idf);
                    532:     }
                    533:     my %temp_env;
                    534:     foreach my $line (@profile) {
1.786     albertel  535: 	if ($line !~ m/=/) {
                    536: 	    return 0;
                    537: 	}
1.783     albertel  538: 	chomp($line);
                    539: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    540: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    541:     }
                    542:     unlink("$lonidsdir/$handle.id");
                    543:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    544: 	    0640)) {
                    545: 	%disk_env = %temp_env;
                    546: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    547: 	untie(%disk_env);
                    548:     }
1.786     albertel  549:     return 1;
1.783     albertel  550: }
                    551: 
1.374     www       552: # ------------------------------------------- Transfer profile into environment
1.780     albertel  553: my $env_loaded;
                    554: sub transfer_profile_to_env {
1.788     albertel  555:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    556:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       557: 
1.720     albertel  558:     if (!defined($lonidsdir)) {
                    559: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    560:     }
                    561:     if (!defined($handle)) {
                    562:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    563:     }
                    564: 
1.786     albertel  565:     my $convert;
                    566:     {
1.917     albertel  567:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    568: 	if (!$opened) {
1.915     albertel  569: 	    return;
                    570: 	}
1.786     albertel  571: 	flock($idf,LOCK_SH);
                    572: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    573: 		&GDBM_READER(),0640)) {
                    574: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    575: 	    untie(%disk_env);
                    576: 	} else {
                    577: 	    $convert = 1;
                    578: 	}
                    579:     }
                    580:     if ($convert) {
                    581: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    582: 	    &logthis("Failed to load session, or convert session.");
                    583: 	}
1.374     www       584:     }
1.783     albertel  585: 
1.786     albertel  586:     my %remove;
1.783     albertel  587:     while ( my $envname = each(%env) ) {
1.433     matthew   588:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    589:             if ($time < time-300) {
1.783     albertel  590:                 $remove{$key}++;
1.433     matthew   591:             }
                    592:         }
                    593:     }
1.783     albertel  594: 
1.619     albertel  595:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  596:     $env_loaded=1;
1.783     albertel  597:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   598:         &delenv($expired_key);
1.374     www       599:     }
1.1       albertel  600: }
                    601: 
1.916     albertel  602: # ---------------------------------------------------- Check for valid session 
                    603: sub check_for_valid_session {
1.1172.2.96  raeburn   604:     my ($r,$name,$userhashref,$domref) = @_;
1.916     albertel  605:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155    raeburn   606:     if ($name eq '') {
                    607:         $name = 'lonID';
                    608:     }
                    609:     my $lonid=$cookies{$name};
1.916     albertel  610:     return undef if (!$lonid);
                    611: 
                    612:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155    raeburn   613:     my $lonidsdir;
                    614:     if ($name eq 'lonDAV') {
                    615:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    616:     } else {
                    617:         $lonidsdir=$r->dir_config('lonIDsDir');
                    618:     }
1.1172.2.96  raeburn   619:     if (!-e "$lonidsdir/$handle.id") {
                    620:         if ((ref($domref)) && ($name eq 'lonID') &&
                    621:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    622:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    623:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    624:                 $$domref = $possudom;
                    625:             }
                    626:         }
                    627:         return undef;
                    628:     }
1.916     albertel  629: 
1.917     albertel  630:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    631:     return undef if (!$opened);
1.916     albertel  632: 
                    633:     flock($idf,LOCK_SH);
                    634:     my %disk_env;
                    635:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    636: 	    &GDBM_READER(),0640)) {
                    637: 	return undef;	
                    638:     }
                    639: 
                    640:     if (!defined($disk_env{'user.name'})
                    641: 	|| !defined($disk_env{'user.domain'})) {
                    642: 	return undef;
                    643:     }
1.1172.2.18  raeburn   644: 
1.1172.2.36  raeburn   645:     if (ref($userhashref) eq 'HASH') {
                    646:         $userhashref->{'name'} = $disk_env{'user.name'};
                    647:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18  raeburn   648:     }
                    649: 
1.916     albertel  650:     return $handle;
                    651: }
                    652: 
1.830     albertel  653: sub timed_flock {
                    654:     my ($file,$lock_type) = @_;
                    655:     my $failed=0;
                    656:     eval {
                    657: 	local $SIG{__DIE__}='DEFAULT';
                    658: 	local $SIG{ALRM}=sub {
                    659: 	    $failed=1;
                    660: 	    die("failed lock");
                    661: 	};
                    662: 	alarm(13);
                    663: 	flock($file,$lock_type);
                    664: 	alarm(0);
                    665:     };
                    666:     if ($failed) {
                    667: 	return undef;
                    668:     } else {
                    669: 	return 1;
                    670:     }
                    671: }
                    672: 
1.5       www       673: # ---------------------------------------------------------- Append Environment
                    674: 
                    675: sub appenv {
1.949     raeburn   676:     my ($newenv,$roles) = @_;
                    677:     if (ref($newenv) eq 'HASH') {
                    678:         foreach my $key (keys(%{$newenv})) {
                    679:             my $refused = 0;
                    680: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    681:                 $refused = 1;
                    682:                 if (ref($roles) eq 'ARRAY') {
1.1172.2.40  raeburn   683:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   684:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    685:                         $refused = 0;
                    686:                     }
                    687:                 }
                    688:             }
                    689:             if ($refused) {
                    690:                 &logthis("<font color=\"blue\">WARNING: ".
                    691:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    692:                          .'</font>');
                    693: 	        delete($newenv->{$key});
                    694:             } else {
                    695:                 $env{$key}=$newenv->{$key};
                    696:             }
                    697:         }
1.1172.2.96  raeburn   698:         my $lonids = $perlvar{'lonIDsDir'};
                    699:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
                    700:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    701:             if ($opened
                    702: 	        && &timed_flock($env_file,LOCK_EX)
                    703: 	        &&
                    704: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    705: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    706: 	        while (my ($key,$value) = each(%{$newenv})) {
                    707: 	            $disk_env{$key} = $value;
                    708: 	        }
                    709: 	        untie(%disk_env);
                    710:             }
1.35      www       711:         }
1.191     harris41  712:     }
1.56      www       713:     return 'ok';
                    714: }
                    715: # ----------------------------------------------------- Delete from Environment
                    716: 
                    717: sub delenv {
1.1104    raeburn   718:     my ($delthis,$regexp,$roles) = @_;
                    719:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    720:         my $refused = 1;
                    721:         if (ref($roles) eq 'ARRAY') {
                    722:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    723:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    724:                 $refused = 0;
                    725:             }
                    726:         }
                    727:         if ($refused) {
                    728:             &logthis("<font color=\"blue\">WARNING: ".
                    729:                      "Attempt to delete from environment ".$delthis);
                    730:             return 'error';
                    731:         }
1.56      www       732:     }
1.917     albertel  733:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    734:     if ($opened
1.915     albertel  735: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  736: 	&&
                    737: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    738: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  739: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   740: 	    if ($regexp) {
                    741:                 if ($key=~/^$delthis/) {
                    742:                     delete($env{$key});
                    743:                     delete($disk_env{$key});
                    744:                 } 
                    745:             } else {
                    746:                 if ($key=~/^\Q$delthis\E/) {
                    747: 		    delete($env{$key});
                    748: 		    delete($disk_env{$key});
                    749: 	        }
                    750:             }
1.448     albertel  751: 	}
1.783     albertel  752: 	untie(%disk_env);
1.5       www       753:     }
                    754:     return 'ok';
1.369     albertel  755: }
                    756: 
1.790     albertel  757: sub get_env_multiple {
                    758:     my ($name) = @_;
                    759:     my @values;
                    760:     if (defined($env{$name})) {
                    761:         # exists is it an array
                    762:         if (ref($env{$name})) {
                    763:             @values=@{ $env{$name} };
                    764:         } else {
                    765:             $values[0]=$env{$name};
                    766:         }
                    767:     }
                    768:     return(@values);
                    769: }
                    770: 
1.958     www       771: # ------------------------------------------------------------------- Locking
                    772: 
                    773: sub set_lock {
                    774:     my ($text)=@_;
                    775:     $locknum++;
                    776:     my $id=$$.'-'.$locknum;
                    777:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    778:              'session.lock.'.$id => $text});
                    779:     return $id;
                    780: }
                    781: 
                    782: sub get_locks {
                    783:     my $num=0;
                    784:     my %texts=();
                    785:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    786:        if ($lock=~/\w/) {
                    787:           $num++;
                    788:           $texts{$lock}=$env{'session.lock.'.$lock};
                    789:        }
                    790:    }
                    791:    return ($num,%texts);
                    792: }
                    793: 
                    794: sub remove_lock {
                    795:     my ($id)=@_;
                    796:     my $newlocks='';
                    797:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    798:        if (($lock=~/\w/) && ($lock ne $id)) {
                    799:           $newlocks.=','.$lock;
                    800:        }
                    801:     }
                    802:     &appenv({'session.locks' => $newlocks});
                    803:     &delenv('session.lock.'.$id);
                    804: }
                    805: 
                    806: sub remove_all_locks {
                    807:     my $activelocks=$env{'session.locks'};
                    808:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    809:        if ($lock=~/\w/) {
                    810:           &remove_lock($lock);
                    811:        }
                    812:     }
                    813: }
                    814: 
                    815: 
1.369     albertel  816: # ------------------------------------------ Find out current server userload
                    817: sub userload {
                    818:     my $numusers=0;
                    819:     {
                    820: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    821: 	my $filename;
                    822: 	my $curtime=time;
                    823: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  824: 	    next if ($filename eq '.' || $filename eq '..');
                    825: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  826: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  827: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  828: 	}
                    829: 	closedir(LONIDS);
                    830:     }
                    831:     my $userloadpercent=0;
                    832:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    833:     if ($maxuserload) {
1.371     albertel  834: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  835:     }
1.372     albertel  836:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  837:     return $userloadpercent;
1.283     www       838: }
                    839: 
1.1       albertel  840: # ------------------------------ Find server with least workload from spare.tab
1.11      www       841: 
1.1       albertel  842: sub spareserver {
1.1083    raeburn   843:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  844:     my $spare_server;
1.370     albertel  845:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  846:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    847:                                                      :  $userloadpercent;
1.1083    raeburn   848:     my ($uint_dom,$remotesessions);
                    849:     if (($udom ne '') && (&domain($udom) ne '')) {
                    850:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    851:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    852:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    853:         $remotesessions = $udomdefaults{'remotesessions'};
                    854:     }
1.1123    raeburn   855:     my $spareshash = &this_host_spares($udom);
                    856:     if (ref($spareshash) eq 'HASH') {
                    857:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    858:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62  raeburn   859:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    860:                                              $try_server));
1.1123    raeburn   861: 	        ($spare_server, $lowest_load) =
                    862: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    863:             }
1.1083    raeburn   864:         }
1.784     albertel  865: 
1.1123    raeburn   866:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    867: 
                    868:         if (!$found_server) {
                    869:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    870: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62  raeburn   871:                     next unless (&spare_can_host($udom,$uint_dom,
                    872:                                                  $remotesessions,$try_server));
1.1123    raeburn   873: 	            ($spare_server, $lowest_load) =
                    874: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    875:                 }
                    876: 	    }
                    877:         }
1.784     albertel  878:     }
                    879: 
                    880:     if (!$want_server_name) {
1.968     raeburn   881:         my $protocol = 'http';
                    882:         if ($protocol{$spare_server} eq 'https') {
                    883:             $protocol = $protocol{$spare_server};
                    884:         }
1.1001    raeburn   885:         if (defined($spare_server)) {
                    886:             my $hostname = &hostname($spare_server);
1.1083    raeburn   887:             if (defined($hostname)) {
1.1001    raeburn   888: 	        $spare_server = $protocol.'://'.$hostname;
                    889:             }
                    890:         }
1.784     albertel  891:     }
                    892:     return $spare_server;
                    893: }
                    894: 
                    895: sub compare_server_load {
1.1172.2.41  raeburn   896:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    897: 
                    898:     if ($required) {
                    899:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    900:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    901:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    902:         if (($major eq '' && $minor eq '') ||
                    903:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    904:             return ($spare_server,$lowest_load);
                    905:         }
                    906:     }
1.784     albertel  907: 
                    908:     my $loadans     = &reply('load',    $try_server);
                    909:     my $userloadans = &reply('userload',$try_server);
                    910: 
                    911:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   912: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  913:     }
                    914: 
                    915:     my $load;
                    916:     if ($loadans =~ /\d/) {
                    917: 	if ($userloadans =~ /\d/) {
                    918: 	    #both are numbers, pick the bigger one
                    919: 	    $load = ($loadans > $userloadans) ? $loadans 
                    920: 		                              : $userloadans;
1.411     albertel  921: 	} else {
1.784     albertel  922: 	    $load = $loadans;
1.411     albertel  923: 	}
1.784     albertel  924:     } else {
                    925: 	$load = $userloadans;
                    926:     }
                    927: 
                    928:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    929: 	$spare_server = $try_server;
                    930: 	$lowest_load  = $load;
1.370     albertel  931:     }
1.784     albertel  932:     return ($spare_server,$lowest_load);
1.202     matthew   933: }
1.914     albertel  934: 
                    935: # --------------------------- ask offload servers if user already has a session
                    936: sub find_existing_session {
                    937:     my ($udom,$uname) = @_;
1.1123    raeburn   938:     my $spareshash = &this_host_spares($udom);
                    939:     if (ref($spareshash) eq 'HASH') {
                    940:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    941:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    942:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    943:             }
                    944:         }
                    945:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    946:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    947:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    948:             }
                    949:         }
1.914     albertel  950:     }
                    951:     return;
                    952: }
                    953: 
                    954: # -------------------------------- ask if server already has a session for user
                    955: sub has_user_session {
                    956:     my ($lonid,$udom,$uname) = @_;
                    957:     my $result = &reply(join(':','userhassession',
                    958: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    959:     return 1 if ($result eq 'ok');
                    960: 
                    961:     return 0;
                    962: }
                    963: 
1.1076    raeburn   964: # --------- determine least loaded server in a user's domain which allows login
                    965: 
                    966: sub choose_server {
1.1172.2.47  raeburn   967:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn   968:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   969:     my %servers = &get_servers($udom);
1.1076    raeburn   970:     my $lowest_load = 30000;
1.1172.2.47  raeburn   971:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                    972:     if ($skiploadbal) {
                    973:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                    974:         unless (defined($cached)) {
                    975:             my $cachetime = 60*60*24;
                    976:             my %domconfig =
                    977:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                    978:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                    979:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                    980:                                            $cachetime);
                    981:             }
                    982:         }
                    983:     }
1.1076    raeburn   984:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   985:         my $loginvia;
1.1172.2.47  raeburn   986:         if ($skiploadbal) {
                    987:             if (ref($balancers) eq 'HASH') {
                    988:                 next if (exists($balancers->{$lonhost}));
                    989:             }
                    990:         }
1.1115    raeburn   991:         if ($checkloginvia) {
                    992:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   993:             if ($loginvia) {
                    994:                 my ($server,$path) = split(/:/,$loginvia);
                    995:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn   996:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn   997:                 if ($login_host eq $server) {
                    998:                     $portal_path = $path;
1.1151    raeburn   999:                     $isredirect = 1;
1.1116    raeburn  1000:                 }
                   1001:             } else {
                   1002:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1003:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1004:                 if ($login_host eq $lonhost) {
                   1005:                     $portal_path = '';
1.1151    raeburn  1006:                     $isredirect = ''; 
1.1116    raeburn  1007:                 }
                   1008:             }
                   1009:         } else {
1.1076    raeburn  1010:             ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1011:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1012:         }
                   1013:     }
                   1014:     if ($login_host ne '') {
1.1116    raeburn  1015:         $hostname = &hostname($login_host);
1.1076    raeburn  1016:     }
1.1172.2.88  raeburn  1017:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1018: }
                   1019: 
1.202     matthew  1020: # --------------------------------------------- Try to change a user's password
                   1021: 
                   1022: sub changepass {
1.799     raeburn  1023:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1024:     $currentpass = &escape($currentpass);
                   1025:     $newpass     = &escape($newpass);
1.1030    raeburn  1026:     my $lonhost = $perlvar{'lonHostID'};
                   1027:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1028: 		       $server);
                   1029:     if (! $answer) {
                   1030: 	&logthis("No reply on password change request to $server ".
                   1031: 		 "by $uname in domain $udom.");
                   1032:     } elsif ($answer =~ "^ok") {
                   1033:         &logthis("$uname in $udom successfully changed their password ".
                   1034: 		 "on $server.");
                   1035:     } elsif ($answer =~ "^pwchange_failure") {
                   1036: 	&logthis("$uname in $udom was unable to change their password ".
                   1037: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1038: 		 "or pwchange");
                   1039:     } elsif ($answer =~ "^non_authorized") {
                   1040:         &logthis("$uname in $udom did not get their password correct when ".
                   1041: 		 "attempting to change it on $server.");
                   1042:     } elsif ($answer =~ "^auth_mode_error") {
                   1043:         &logthis("$uname in $udom attempted to change their password despite ".
                   1044: 		 "not being locally or internally authenticated on $server.");
                   1045:     } elsif ($answer =~ "^unknown_user") {
                   1046:         &logthis("$uname in $udom attempted to change their password ".
                   1047: 		 "on $server but were unable to because $server is not ".
                   1048: 		 "their home server.");
                   1049:     } elsif ($answer =~ "^refused") {
                   1050: 	&logthis("$server refused to change $uname in $udom password because ".
                   1051: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1052:     } elsif ($answer =~ "invalid_client") {
                   1053:         &logthis("$server refused to change $uname in $udom password because ".
                   1054:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1055:     }
                   1056:     return $answer;
1.1       albertel 1057: }
                   1058: 
1.169     harris41 1059: # ----------------------- Try to determine user's current authentication scheme
                   1060: 
                   1061: sub queryauthenticate {
                   1062:     my ($uname,$udom)=@_;
1.456     albertel 1063:     my $uhome=&homeserver($uname,$udom);
                   1064:     if (!$uhome) {
                   1065: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1066: 	return 'no_host';
                   1067:     }
                   1068:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1069:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1070: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1071:     }
1.456     albertel 1072:     return $answer;
1.169     harris41 1073: }
                   1074: 
1.1       albertel 1075: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1076: 
1.1       albertel 1077: sub authenticate {
1.1073    raeburn  1078:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1079:     $upass=&escape($upass);
                   1080:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1081:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1082:     my $newhome;
1.836     www      1083:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1084: # Maybe the machine was offline and only re-appeared again recently?
                   1085:         &reconlonc();
                   1086: # One more
1.952     raeburn  1087: 	$uhome=&homeserver($uname,$udom,1);
                   1088:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1089:             if (defined(&domain($udom,'primary'))) {
                   1090:                 $newhome=&domain($udom,'primary');
                   1091:             }
                   1092:             if ($newhome ne '') {
                   1093:                 $uhome = $newhome;
                   1094:             }
                   1095:         }
1.836     www      1096: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1097: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1098: 	    return 'no_host';
                   1099:         }
1.1       albertel 1100:     }
1.1073    raeburn  1101:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1102:     if ($answer eq 'authorized') {
1.952     raeburn  1103:         if ($newhome) {
                   1104:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1105:             return 'no_account_on_host'; 
                   1106:         } else {
                   1107:             &logthis("User $uname at $udom authorized by $uhome");
                   1108:             return $uhome;
                   1109:         }
1.471     albertel 1110:     }
                   1111:     if ($answer eq 'non_authorized') {
                   1112: 	&logthis("User $uname at $udom rejected by $uhome");
                   1113: 	return 'no_host'; 
1.9       www      1114:     }
1.471     albertel 1115:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1116:     return 'no_host';
                   1117: }
                   1118: 
1.1073    raeburn  1119: sub can_host_session {
1.1074    raeburn  1120:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1121:     my $canhost = 1;
1.1074    raeburn  1122:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1123:     if (ref($remotesessions) eq 'HASH') {
                   1124:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1125:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1126:                 $canhost = 0;
                   1127:             } else {
                   1128:                 $canhost = 1;
                   1129:             }
                   1130:         }
                   1131:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1132:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1133:                 $canhost = 1;
                   1134:             } else {
                   1135:                 $canhost = 0;
                   1136:             }
                   1137:         }
                   1138:         if ($canhost) {
                   1139:             if ($remotesessions->{'version'} ne '') {
                   1140:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1141:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1142:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1143:                         my $major = $1;
                   1144:                         my $minor = $2;
                   1145:                         if (($major < $reqmajor ) ||
                   1146:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1147:                             $canhost = 0;
                   1148:                         }
                   1149:                     } else {
                   1150:                         $canhost = 0;
                   1151:                     }
                   1152:                 }
                   1153:             }
                   1154:         }
                   1155:     }
                   1156:     if ($canhost) {
                   1157:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1158:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1159:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1160:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1161:                 if (($uint_dom ne '') && 
                   1162:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1163:                     $canhost = 0;
                   1164:                 } else {
                   1165:                     $canhost = 1;
                   1166:                 }
                   1167:             }
                   1168:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1169:                 if (($uint_dom ne '') && 
                   1170:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1171:                     $canhost = 1;
                   1172:                 } else {
                   1173:                     $canhost = 0;
                   1174:                 }
                   1175:             }
                   1176:         }
                   1177:     }
                   1178:     return $canhost;
                   1179: }
                   1180: 
1.1083    raeburn  1181: sub spare_can_host {
                   1182:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1183:     my $canhost=1;
1.1172.2.62  raeburn  1184:     my $try_server_hostname = &hostname($try_server);
                   1185:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1186:     my $serverhomedom = &host_domain($serverhomeID);
                   1187:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1188:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1189:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1190:             $canhost = 0;
                   1191:         }
                   1192:     }
                   1193:     if (($canhost) && ($uint_dom)) {
                   1194:         my @intdoms;
                   1195:         my $internet_names = &get_internet_names($try_server);
                   1196:         if (ref($internet_names) eq 'ARRAY') {
                   1197:             @intdoms = @{$internet_names};
                   1198:         }
                   1199:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1200:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1201:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1202:                                          $remotesessions,
                   1203:                                          $defdomdefaults{'hostedsessions'});
                   1204:         }
1.1083    raeburn  1205:     }
                   1206:     return $canhost;
                   1207: }
                   1208: 
1.1123    raeburn  1209: sub this_host_spares {
                   1210:     my ($dom) = @_;
1.1126    raeburn  1211:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1212:     my @hosts = &current_machine_ids();
                   1213:     foreach my $lonhost (@hosts) {
                   1214:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1215:             $dom_in_use = $dom;
                   1216:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1217:             last;
                   1218:         }
                   1219:     }
1.1126    raeburn  1220:     if ($dom_in_use ne '') {
                   1221:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1222:     }
                   1223:     if (ref($result) ne 'HASH') {
                   1224:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1225:         $dom_in_use = &host_domain($lonhost_in_use);
                   1226:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1227:         if (ref($result) ne 'HASH') {
                   1228:             $result = \%spareid;
                   1229:         }
                   1230:     }
                   1231:     return $result;
                   1232: }
                   1233: 
                   1234: sub spares_for_offload  {
                   1235:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1236:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1237:     if (defined($cached)) {
                   1238:         return $result;
                   1239:     } else {
1.1126    raeburn  1240:         my $cachetime = 60*60*24;
                   1241:         my %domconfig =
                   1242:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1243:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1244:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1245:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1246:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1247:                 }
                   1248:             }
                   1249:         }
                   1250:     }
1.1126    raeburn  1251:     return;
1.1123    raeburn  1252: }
                   1253: 
1.1129    raeburn  1254: sub get_lonbalancer_config {
                   1255:     my ($servers) = @_;
                   1256:     my ($currbalancer,$currtargets);
                   1257:     if (ref($servers) eq 'HASH') {
                   1258:         foreach my $server (keys(%{$servers})) {
                   1259:             my %what = (
                   1260:                          spareid => 1,
                   1261:                          perlvar => 1,
                   1262:                        );
                   1263:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1264:             if ($result eq 'ok') {
                   1265:                 if (ref($returnhash) eq 'HASH') {
                   1266:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1267:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1268:                             $currbalancer = $server;
                   1269:                             $currtargets = {};
                   1270:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1271:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1272:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1273:                                 }
                   1274:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1275:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1276:                                 }
                   1277:                             }
                   1278:                             last;
                   1279:                         }
                   1280:                     }
                   1281:                 }
                   1282:             }
                   1283:         }
                   1284:     }
                   1285:     return ($currbalancer,$currtargets);
                   1286: }
                   1287: 
                   1288: sub check_loadbalancing {
1.1172.2.88  raeburn  1289:     my ($uname,$udom,$caller) = @_;
1.1172.2.12  raeburn  1290:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1291:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1292:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1293:     my @hosts = &current_machine_ids();
1.1129    raeburn  1294:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1295:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1296:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1297:     my $serverhomedom = &host_domain($lonhost);
1.1172.2.75  raeburn  1298:     my $domneedscache; 
1.1129    raeburn  1299:     my $cachetime = 60*60*24;
                   1300: 
                   1301:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1302:         $dom_in_use = $udom;
                   1303:         $homeintdom = 1;
                   1304:     } else {
                   1305:         $dom_in_use = $serverhomedom;
                   1306:     }
                   1307:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1308:     unless (defined($cached)) {
                   1309:         my %domconfig =
                   1310:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1311:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1312:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75  raeburn  1313:         } else {
                   1314:             $domneedscache = $dom_in_use;
1.1129    raeburn  1315:         }
                   1316:     }
                   1317:     if (ref($result) eq 'HASH') {
1.1172.2.12  raeburn  1318:         ($is_balancer,$currtargets,$currrules) =
                   1319:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1320:         if ($is_balancer) {
                   1321:             if (ref($currrules) eq 'HASH') {
                   1322:                 if ($homeintdom) {
                   1323:                     if ($uname ne '') {
                   1324:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1325:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1326:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1327:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1328:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1329:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1330:                             }
                   1331:                         }
                   1332:                         if ($rule_in_effect eq '') {
                   1333:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1334:                             if ($userenv{'inststatus'} ne '') {
                   1335:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1336:                                 my ($othertitle,$usertypes,$types) =
                   1337:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1338:                                 if (ref($types) eq 'ARRAY') {
                   1339:                                     foreach my $type (@{$types}) {
                   1340:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1341:                                             if (exists($currrules->{$type})) {
                   1342:                                                 $rule_in_effect = $currrules->{$type};
                   1343:                                             }
                   1344:                                         }
                   1345:                                     }
                   1346:                                 }
                   1347:                             } else {
                   1348:                                 if (exists($currrules->{'default'})) {
                   1349:                                     $rule_in_effect = $currrules->{'default'};
                   1350:                                 }
                   1351:                             }
                   1352:                         }
                   1353:                     } else {
                   1354:                         if (exists($currrules->{'default'})) {
                   1355:                             $rule_in_effect = $currrules->{'default'};
                   1356:                         }
                   1357:                     }
                   1358:                 } else {
                   1359:                     if ($currrules->{'_LC_external'} ne '') {
                   1360:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1361:                     }
                   1362:                 }
                   1363:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1364:                                                        $uname,$udom);
                   1365:             }
                   1366:         }
                   1367:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35  raeburn  1368:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1369:         unless (defined($cached)) {
                   1370:             my %domconfig =
                   1371:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1372:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75  raeburn  1373:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1374:             } else {
                   1375:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1376:             }
                   1377:         }
                   1378:         if (ref($result) eq 'HASH') {
1.1172.2.12  raeburn  1379:             ($is_balancer,$currtargets,$currrules) =
                   1380:                 &check_balancer_result($result,@hosts);
                   1381:             if ($is_balancer) {
1.1129    raeburn  1382:                 if (ref($currrules) eq 'HASH') {
                   1383:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1384:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1385:                     }
                   1386:                 }
                   1387:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1388:                                                        $uname,$udom);
                   1389:             }
                   1390:         } else {
                   1391:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1392:                 $is_balancer = 1;
                   1393:                 $offloadto = &this_host_spares($dom_in_use);
                   1394:             }
1.1172.2.75  raeburn  1395:             unless (defined($cached)) {
                   1396:                 $domneedscache = $serverhomedom;
                   1397:             }
1.1129    raeburn  1398:         }
                   1399:     } else {
                   1400:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1401:             $is_balancer = 1;
                   1402:             $offloadto = &this_host_spares($dom_in_use);
                   1403:         }
1.1172.2.75  raeburn  1404:         unless (defined($cached)) {
                   1405:             $domneedscache = $serverhomedom;
                   1406:         }
                   1407:     }
                   1408:     if ($domneedscache) {
                   1409:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1410:     }
1.1172.2.5  raeburn  1411:     if ($is_balancer) {
                   1412:         my $lowest_load = 30000;
                   1413:         if (ref($offloadto) eq 'HASH') {
                   1414:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1415:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1416:                     ($otherserver,$lowest_load) =
                   1417:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1418:                 }
1.1129    raeburn  1419:             }
1.1172.2.5  raeburn  1420:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1421: 
1.1172.2.5  raeburn  1422:             if (!$found_server) {
                   1423:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1424:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1425:                         ($otherserver,$lowest_load) =
                   1426:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1427:                     }
                   1428:                 }
                   1429:             }
                   1430:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1431:             if (@{$offloadto} == 1) {
                   1432:                 $otherserver = $offloadto->[0];
                   1433:             } elsif (@{$offloadto} > 1) {
                   1434:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1435:                     ($otherserver,$lowest_load) =
                   1436:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1437:                 }
                   1438:             }
                   1439:         }
1.1172.2.88  raeburn  1440:         unless ($caller eq 'login') {
                   1441:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1442:                 $is_balancer = 0;
                   1443:                 if ($uname ne '' && $udom ne '') {
                   1444:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1172.2.5  raeburn  1445: 
1.1172.2.88  raeburn  1446:                         &appenv({'user.loadbalexempt'     => $lonhost,
                   1447:                                  'user.loadbalcheck.time' => time});
                   1448:                     }
1.1172.2.5  raeburn  1449:                 }
1.1129    raeburn  1450:             }
                   1451:         }
                   1452:     }
                   1453:     return ($is_balancer,$otherserver);
                   1454: }
                   1455: 
1.1172.2.12  raeburn  1456: sub check_balancer_result {
                   1457:     my ($result,@hosts) = @_;
                   1458:     my ($is_balancer,$currtargets,$currrules);
                   1459:     if (ref($result) eq 'HASH') {
                   1460:         if ($result->{'lonhost'} ne '') {
                   1461:             my $currbalancer = $result->{'lonhost'};
                   1462:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1463:                 $is_balancer = 1;
                   1464:                 $currtargets = $result->{'targets'};
                   1465:                 $currrules = $result->{'rules'};
                   1466:             }
                   1467:         } else {
                   1468:             foreach my $key (keys(%{$result})) {
                   1469:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1470:                     (ref($result->{$key}) eq 'HASH')) {
                   1471:                     $is_balancer = 1;
                   1472:                     $currrules = $result->{$key}{'rules'};
                   1473:                     $currtargets = $result->{$key}{'targets'};
                   1474:                     last;
                   1475:                 }
                   1476:             }
                   1477:         }
                   1478:     }
                   1479:     return ($is_balancer,$currtargets,$currrules);
                   1480: }
                   1481: 
1.1129    raeburn  1482: sub get_loadbalancer_targets {
                   1483:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1484:     my $offloadto;
1.1172.2.4  raeburn  1485:     if ($rule_in_effect eq 'none') {
                   1486:         return [$perlvar{'lonHostID'}];
                   1487:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1488:         $offloadto = $currtargets;
                   1489:     } else {
                   1490:         if ($rule_in_effect eq 'homeserver') {
                   1491:             my $homeserver = &homeserver($uname,$udom);
                   1492:             if ($homeserver ne 'no_host') {
                   1493:                 $offloadto = [$homeserver];
                   1494:             }
                   1495:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1496:             my %domconfig =
                   1497:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1498:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1499:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1500:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1501:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1502:                     }
                   1503:                 }
                   1504:             } else {
1.1172.2.7  raeburn  1505:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1506:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1507:                 if (&hostname($remotebalancer) ne '') {
                   1508:                     $offloadto = [$remotebalancer];
                   1509:                 }
                   1510:             }
                   1511:         } elsif (&hostname($rule_in_effect) ne '') {
                   1512:             $offloadto = [$rule_in_effect];
                   1513:         }
                   1514:     }
                   1515:     return $offloadto;
                   1516: }
                   1517: 
1.1127    raeburn  1518: sub internet_dom_servers {
                   1519:     my ($dom) = @_;
                   1520:     my (%uniqservers,%servers);
                   1521:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1522:     my @machinedoms = &machine_domains($primaryserver);
                   1523:     foreach my $mdom (@machinedoms) {
                   1524:         my %currservers = %servers;
                   1525:         my %server = &get_servers($mdom);
                   1526:         %servers = (%currservers,%server);
                   1527:     }
                   1528:     my %by_hostname;
                   1529:     foreach my $id (keys(%servers)) {
                   1530:         push(@{$by_hostname{$servers{$id}}},$id);
                   1531:     }
                   1532:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1533:         if (@{$by_hostname{$hostname}} > 1) {
                   1534:             my $match = 0;
                   1535:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1536:                 if (&host_domain($id) eq $dom) {
                   1537:                     $uniqservers{$id} = $hostname;
                   1538:                     $match = 1;
                   1539:                 }
                   1540:             }
                   1541:             unless ($match) {
                   1542:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1543:             }
                   1544:         } else {
                   1545:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1546:         }
                   1547:     }
                   1548:     return %uniqservers;
                   1549: }
                   1550: 
1.1       albertel 1551: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1552: 
1.599     albertel 1553: my %homecache;
1.1       albertel 1554: sub homeserver {
1.230     stredwic 1555:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1556:     my $index="$uname:$udom";
1.426     albertel 1557: 
1.599     albertel 1558:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1559: 
                   1560:     my %servers = &get_servers($udom,'library');
                   1561:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1562:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1563: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1564: 
                   1565: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1566: 	if ($answer eq 'found') {
                   1567: 	    delete($badServerCache{$tryserver}); 
                   1568: 	    return $homecache{$index}=$tryserver;
                   1569: 	} elsif ($answer eq 'no_host') {
                   1570: 	    $badServerCache{$tryserver}=1;
                   1571: 	}
1.1       albertel 1572:     }    
                   1573:     return 'no_host';
1.70      www      1574: }
                   1575: 
                   1576: # ------------------------------------- Find the usernames behind a list of IDs
                   1577: 
                   1578: sub idget {
                   1579:     my ($udom,@ids)=@_;
                   1580:     my %returnhash=();
                   1581:     
1.841     albertel 1582:     my %servers = &get_servers($udom,'library');
                   1583:     foreach my $tryserver (keys(%servers)) {
1.1172.2.73  raeburn  1584: 	my $idlist=join('&', map { &escape($_); } @ids);
1.841     albertel 1585: 	$idlist=~tr/A-Z/a-z/; 
                   1586: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1587: 	my @answer=();
                   1588: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1589: 	    @answer=split(/\&/,$reply);
                   1590: 	}                    ;
                   1591: 	my $i;
                   1592: 	for ($i=0;$i<=$#ids;$i++) {
                   1593: 	    if ($answer[$i]) {
1.1172.2.73  raeburn  1594: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841     albertel 1595: 	    } 
                   1596: 	}
                   1597:     } 
1.70      www      1598:     return %returnhash;
                   1599: }
                   1600: 
                   1601: # ------------------------------------- Find the IDs behind a list of usernames
                   1602: 
                   1603: sub idrget {
                   1604:     my ($udom,@unames)=@_;
                   1605:     my %returnhash=();
1.800     albertel 1606:     foreach my $uname (@unames) {
                   1607:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1608:     }
1.70      www      1609:     return %returnhash;
                   1610: }
                   1611: 
                   1612: # ------------------------------- Store away a list of names and associated IDs
                   1613: 
                   1614: sub idput {
                   1615:     my ($udom,%ids)=@_;
                   1616:     my %servers=();
1.800     albertel 1617:     foreach my $uname (keys(%ids)) {
                   1618: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1619:         my $uhom=&homeserver($uname,$udom);
1.70      www      1620:         if ($uhom ne 'no_host') {
1.800     albertel 1621:             my $id=&escape($ids{$uname});
1.70      www      1622:             $id=~tr/A-Z/a-z/;
1.800     albertel 1623:             my $esc_unam=&escape($uname);
1.70      www      1624: 	    if ($servers{$uhom}) {
1.800     albertel 1625: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1626:             } else {
1.800     albertel 1627:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1628:             }
                   1629:         }
1.191     harris41 1630:     }
1.800     albertel 1631:     foreach my $server (keys(%servers)) {
                   1632:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1633:     }
1.344     www      1634: }
                   1635: 
1.1172.2.30  raeburn  1636: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1637: 
                   1638: sub iddel {
                   1639:     my ($udom,$idshashref,$uhome)=@_;
                   1640:     my %result=();
                   1641:     unless (ref($idshashref) eq 'HASH') {
                   1642:         return %result;
                   1643:     }
                   1644:     my %servers=();
                   1645:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1646:         my $uhom;
                   1647:         if ($uhome) {
                   1648:             $uhom = $uhome;
                   1649:         } else {
                   1650:             $uhom=&homeserver($uname,$udom);
                   1651:         }
                   1652:         if ($uhom ne 'no_host') {
                   1653:             if ($servers{$uhom}) {
                   1654:                 $servers{$uhom}.='&'.&escape($id);
                   1655:             } else {
                   1656:                 $servers{$uhom}=&escape($id);
                   1657:             }
                   1658:         }
                   1659:     }
                   1660:     foreach my $server (keys(%servers)) {
                   1661:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1662:     }
                   1663:     return %result;
                   1664: }
                   1665: 
1.1023    raeburn  1666: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1667: sub dump_dom {
1.1165    droeschl 1668:     my ($namespace, $udom, $regexp) = @_;
                   1669: 
                   1670:     $udom ||= $env{'user.domain'};
                   1671: 
                   1672:     return () unless $udom;
                   1673: 
                   1674:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1675: }
                   1676: 
1.1023    raeburn  1677: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1678: 
                   1679: sub get_dom {
1.860     raeburn  1680:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57  raeburn  1681:     return if ($udom eq 'public');
1.806     raeburn  1682:     my $items='';
                   1683:     foreach my $item (@$storearr) {
                   1684:         $items.=&escape($item).'&';
                   1685:     }
                   1686:     $items=~s/\&$//;
1.860     raeburn  1687:     if (!$udom) {
                   1688:         $udom=$env{'user.domain'};
1.1172.2.57  raeburn  1689:         return if ($udom eq 'public');
1.860     raeburn  1690:         if (defined(&domain($udom,'primary'))) {
                   1691:             $uhome=&domain($udom,'primary');
                   1692:         } else {
1.874     albertel 1693:             undef($uhome);
1.860     raeburn  1694:         }
                   1695:     } else {
                   1696:         if (!$uhome) {
                   1697:             if (defined(&domain($udom,'primary'))) {
                   1698:                 $uhome=&domain($udom,'primary');
                   1699:             }
                   1700:         }
                   1701:     }
                   1702:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1703:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1704:         my %returnhash;
1.875     albertel 1705:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1706:             return %returnhash;
                   1707:         }
1.806     raeburn  1708:         my @pairs=split(/\&/,$rep);
                   1709:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1710:             return @pairs;
                   1711:         }
                   1712:         my $i=0;
                   1713:         foreach my $item (@$storearr) {
                   1714:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1715:             $i++;
                   1716:         }
                   1717:         return %returnhash;
                   1718:     } else {
1.880     banghart 1719:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1720:     }
                   1721: }
                   1722: 
                   1723: # -------------------------------------------- put items in domain db files 
                   1724: 
                   1725: sub put_dom {
1.860     raeburn  1726:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1727:     if (!$udom) {
                   1728:         $udom=$env{'user.domain'};
                   1729:         if (defined(&domain($udom,'primary'))) {
                   1730:             $uhome=&domain($udom,'primary');
                   1731:         } else {
1.874     albertel 1732:             undef($uhome);
1.860     raeburn  1733:         }
                   1734:     } else {
                   1735:         if (!$uhome) {
                   1736:             if (defined(&domain($udom,'primary'))) {
                   1737:                 $uhome=&domain($udom,'primary');
                   1738:             }
                   1739:         }
                   1740:     } 
                   1741:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1742:         my $items='';
                   1743:         foreach my $item (keys(%$storehash)) {
                   1744:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1745:         }
                   1746:         $items=~s/\&$//;
                   1747:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1748:     } else {
1.860     raeburn  1749:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1750:     }
                   1751: }
                   1752: 
1.1023    raeburn  1753: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1754: sub newput_dom {
1.1023    raeburn  1755:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1756:     my $result;
                   1757:     if (!$udom) {
                   1758:         $udom=$env{'user.domain'};
                   1759:     }
1.1023    raeburn  1760:     if ($udom) {
                   1761:         my $uname = &get_domainconfiguser($udom);
                   1762:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1763:     }
                   1764:     return $result;
                   1765: }
                   1766: 
1.1023    raeburn  1767: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1768: sub del_dom {
1.1023    raeburn  1769:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1770:     if (ref($storearr) eq 'ARRAY') {
                   1771:         if (!$udom) {
                   1772:             $udom=$env{'user.domain'};
                   1773:         }
1.1023    raeburn  1774:         if ($udom) {
                   1775:             my $uname = &get_domainconfiguser($udom); 
                   1776:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1777:         }
                   1778:     }
                   1779: }
                   1780: 
1.1023    raeburn  1781: # ----------------------------------construct domainconfig user for a domain 
                   1782: sub get_domainconfiguser {
                   1783:     my ($udom) = @_;
                   1784:     return $udom.'-domainconfig';
                   1785: }
                   1786: 
1.837     raeburn  1787: sub retrieve_inst_usertypes {
                   1788:     my ($udom) = @_;
                   1789:     my (%returnhash,@order);
1.989     raeburn  1790:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1791:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1792:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  1793:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1794:     } else {
                   1795:         if (defined(&domain($udom,'primary'))) {
                   1796:             my $uhome=&domain($udom,'primary');
                   1797:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1798:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  1799:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1800:                 return (\%returnhash,\@order);
                   1801:             }
                   1802:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1803:             my @pairs=split(/\&/,$hashitems);
                   1804:             foreach my $item (@pairs) {
                   1805:                 my ($key,$value)=split(/=/,$item,2);
                   1806:                 $key = &unescape($key);
                   1807:                 next if ($key =~ /^error: 2 /);
                   1808:                 $returnhash{$key}=&thaw_unescape($value);
                   1809:             }
                   1810:             my @esc_order = split(/\&/,$orderitems);
                   1811:             foreach my $item (@esc_order) {
                   1812:                 push(@order,&unescape($item));
                   1813:             }
                   1814:         } else {
1.1172.2.44  raeburn  1815:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1816:         }
1.1172.2.44  raeburn  1817:         return (\%returnhash,\@order);
1.837     raeburn  1818:     }
                   1819: }
                   1820: 
1.868     raeburn  1821: sub is_domainimage {
                   1822:     my ($url) = @_;
1.1172.2.74  raeburn  1823:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  1824:         if (&domain($1) ne '') {
                   1825:             return '1';
                   1826:         }
                   1827:     }
                   1828:     return;
                   1829: }
                   1830: 
1.899     raeburn  1831: sub inst_directory_query {
                   1832:     my ($srch) = @_;
                   1833:     my $udom = $srch->{'srchdomain'};
                   1834:     my %results;
                   1835:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1836:     my $outcome;
1.899     raeburn  1837:     if ($homeserver ne '') {
1.904     albertel 1838: 	my $queryid=&reply("querysend:instdirsearch:".
                   1839: 			   &escape($srch->{'srchby'}).':'.
                   1840: 			   &escape($srch->{'srchterm'}).':'.
                   1841: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1842: 	my $host=&hostname($homeserver);
                   1843: 	if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96  raeburn  1844: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 1845: 	    return;
                   1846: 	}
                   1847: 	my $response = &get_query_reply($queryid);
                   1848: 	my $maxtries = 5;
                   1849: 	my $tries = 1;
                   1850: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1851: 	    $response = &get_query_reply($queryid);
                   1852: 	    $tries ++;
                   1853: 	}
                   1854: 
                   1855:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1856:             if ($response eq 'unavailable') {
                   1857:                 $outcome = $response;
                   1858:             } else {
                   1859:                 $outcome = 'ok';
                   1860:                 my @matches = split(/\n/,$response);
                   1861:                 foreach my $match (@matches) {
                   1862:                     my ($key,$value) = split(/=/,$match);
                   1863:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1864:                 }
1.899     raeburn  1865:             }
                   1866:         }
                   1867:     }
1.909     raeburn  1868:     return ($outcome,%results);
1.899     raeburn  1869: }
                   1870: 
                   1871: sub usersearch {
                   1872:     my ($srch) = @_;
                   1873:     my $dom = $srch->{'srchdomain'};
                   1874:     my %results;
                   1875:     my %libserv = &all_library();
                   1876:     my $query = 'usersearch';
                   1877:     foreach my $tryserver (keys(%libserv)) {
                   1878:         if (&host_domain($tryserver) eq $dom) {
                   1879:             my $host=&hostname($tryserver);
                   1880:             my $queryid=
1.911     raeburn  1881:                 &reply("querysend:".&escape($query).':'.
                   1882:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1883:                        &escape($srch->{'srchtype'}).':'.
                   1884:                        &escape($srch->{'srchterm'}),$tryserver);
                   1885:             if ($queryid !~/^\Q$host\E\_/) {
                   1886:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1887:                 next;
1.899     raeburn  1888:             }
                   1889:             my $reply = &get_query_reply($queryid);
                   1890:             my $maxtries = 1;
                   1891:             my $tries = 1;
                   1892:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1893:                 $reply = &get_query_reply($queryid);
                   1894:                 $tries ++;
                   1895:             }
                   1896:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1897:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1898:             } else {
1.911     raeburn  1899:                 my @matches;
                   1900:                 if ($reply =~ /\n/) {
                   1901:                     @matches = split(/\n/,$reply);
                   1902:                 } else {
                   1903:                     @matches = split(/\&/,$reply);
                   1904:                 }
1.899     raeburn  1905:                 foreach my $match (@matches) {
                   1906:                     my ($uname,$udom,%userhash);
1.911     raeburn  1907:                     foreach my $entry (split(/:/,$match)) {
                   1908:                         my ($key,$value) =
                   1909:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1910:                         $userhash{$key} = $value;
                   1911:                         if ($key eq 'username') {
                   1912:                             $uname = $value;
                   1913:                         } elsif ($key eq 'domain') {
                   1914:                             $udom = $value;
1.911     raeburn  1915:                         }
1.899     raeburn  1916:                     }
                   1917:                     $results{$uname.':'.$udom} = \%userhash;
                   1918:                 }
                   1919:             }
                   1920:         }
                   1921:     }
                   1922:     return %results;
                   1923: }
                   1924: 
1.912     raeburn  1925: sub get_instuser {
                   1926:     my ($udom,$uname,$id) = @_;
                   1927:     my $homeserver = &domain($udom,'primary');
                   1928:     my ($outcome,%results);
                   1929:     if ($homeserver ne '') {
                   1930:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1931:                            &escape($id).':'.&escape($udom),$homeserver);
                   1932:         my $host=&hostname($homeserver);
                   1933:         if ($queryid !~/^\Q$host\E\_/) {
                   1934:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1935:             return;
                   1936:         }
                   1937:         my $response = &get_query_reply($queryid);
                   1938:         my $maxtries = 5;
                   1939:         my $tries = 1;
                   1940:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1941:             $response = &get_query_reply($queryid);
                   1942:             $tries ++;
                   1943:         }
                   1944:         if (!&error($response) && $response ne 'refused') {
                   1945:             if ($response eq 'unavailable') {
                   1946:                 $outcome = $response;
                   1947:             } else {
                   1948:                 $outcome = 'ok';
                   1949:                 my @matches = split(/\n/,$response);
                   1950:                 foreach my $match (@matches) {
                   1951:                     my ($key,$value) = split(/=/,$match);
                   1952:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1953:                 }
                   1954:             }
                   1955:         }
                   1956:     }
                   1957:     my %userinfo;
                   1958:     if (ref($results{$uname}) eq 'HASH') {
                   1959:         %userinfo = %{$results{$uname}};
                   1960:     } 
                   1961:     return ($outcome,%userinfo);
                   1962: }
                   1963: 
1.1172.2.69  raeburn  1964: sub get_multiple_instusers {
                   1965:     my ($udom,$users,$caller) = @_;
                   1966:     my ($outcome,$results);
                   1967:     if (ref($users) eq 'HASH') {
                   1968:         my $count = keys(%{$users});
                   1969:         my $requested = &freeze_escape($users);
                   1970:         my $homeserver = &domain($udom,'primary');
                   1971:         if ($homeserver ne '') {
                   1972:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   1973:             my $host=&hostname($homeserver);
                   1974:             if ($queryid !~/^\Q$host\E\_/) {
                   1975:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   1976:                          ' for host: '.$homeserver.'in domain '.$udom);
                   1977:                 return ($outcome,$results);
                   1978:             }
                   1979:             my $response = &get_query_reply($queryid);
                   1980:             my $maxtries = 5;
                   1981:             if ($count > 100) {
                   1982:                 $maxtries = 1+int($count/20);
                   1983:             }
                   1984:             my $tries = 1;
                   1985:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   1986:                 $response = &get_query_reply($queryid);
                   1987:                 $tries ++;
                   1988:             }
                   1989:             if ($response eq '') {
                   1990:                 $results = {};
                   1991:                 foreach my $key (keys(%{$users})) {
                   1992:                     my ($uname,$id);
                   1993:                     if ($caller eq 'id') {
                   1994:                         $id = $key;
                   1995:                     } else {
                   1996:                         $uname = $key;
                   1997:                     }
                   1998:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
                   1999:                     $outcome = $resp;
                   2000:                     if ($resp eq 'ok') {
                   2001:                         %{$results} = (%{$results}, %info);
                   2002:                     } else {
                   2003:                         last;
                   2004:                     }
                   2005:                 }
                   2006:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2007:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2008:                     $outcome = $response;
                   2009:                 } else {
                   2010:                     ($outcome,my $userdata) = split(/=/,$response,2);
                   2011:                     if ($outcome eq 'ok') {
                   2012:                         $results = &thaw_unescape($userdata);
                   2013:                     }
                   2014:                 }
                   2015:             }
                   2016:         }
                   2017:     }
                   2018:     return ($outcome,$results);
                   2019: }
                   2020: 
1.912     raeburn  2021: sub inst_rulecheck {
1.923     raeburn  2022:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2023:     my %returnhash;
                   2024:     if ($udom ne '') {
                   2025:         if (ref($rules) eq 'ARRAY') {
                   2026:             @{$rules} = map {&escape($_);} (@{$rules});
                   2027:             my $rulestr = join(':',@{$rules});
                   2028:             my $homeserver=&domain($udom,'primary');
                   2029:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2030:                 my $response;
                   2031:                 if ($item eq 'username') {                
                   2032:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2033:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2034:                                               $homeserver));
1.923     raeburn  2035:                 } elsif ($item eq 'id') {
                   2036:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2037:                                               ':'.&escape($id).':'.$rulestr,
                   2038:                                               $homeserver));
1.945     raeburn  2039:                 } elsif ($item eq 'selfcreate') {
                   2040:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2041:                                                &escape($udom).':'.&escape($uname).
                   2042:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2043:                 }
1.912     raeburn  2044:                 if ($response ne 'refused') {
                   2045:                     my @pairs=split(/\&/,$response);
                   2046:                     foreach my $item (@pairs) {
                   2047:                         my ($key,$value)=split(/=/,$item,2);
                   2048:                         $key = &unescape($key);
                   2049:                         next if ($key =~ /^error: 2 /);
                   2050:                         $returnhash{$key}=&thaw_unescape($value);
                   2051:                     }
                   2052:                 }
                   2053:             }
                   2054:         }
                   2055:     }
                   2056:     return %returnhash;
                   2057: }
                   2058: 
                   2059: sub inst_userrules {
1.923     raeburn  2060:     my ($udom,$check) = @_;
1.912     raeburn  2061:     my (%ruleshash,@ruleorder);
                   2062:     if ($udom ne '') {
                   2063:         my $homeserver=&domain($udom,'primary');
                   2064:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2065:             my $response;
                   2066:             if ($check eq 'id') {
                   2067:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2068:                                  $homeserver);
1.943     raeburn  2069:             } elsif ($check eq 'email') {
                   2070:                 $response=&reply('instemailrules:'.&escape($udom),
                   2071:                                  $homeserver);
1.923     raeburn  2072:             } else {
                   2073:                 $response=&reply('instuserrules:'.&escape($udom),
                   2074:                                  $homeserver);
                   2075:             }
1.912     raeburn  2076:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2077:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2078:                 ($response ne 'no_such_host')) {
                   2079:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2080:                 my @pairs=split(/\&/,$hashitems);
                   2081:                 foreach my $item (@pairs) {
                   2082:                     my ($key,$value)=split(/=/,$item,2);
                   2083:                     $key = &unescape($key);
                   2084:                     next if ($key =~ /^error: 2 /);
                   2085:                     $ruleshash{$key}=&thaw_unescape($value);
                   2086:                 }
                   2087:                 my @esc_order = split(/\&/,$orderitems);
                   2088:                 foreach my $item (@esc_order) {
                   2089:                     push(@ruleorder,&unescape($item));
                   2090:                 }
                   2091:             }
                   2092:         }
                   2093:     }
                   2094:     return (\%ruleshash,\@ruleorder);
                   2095: }
                   2096: 
1.976     raeburn  2097: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2098: 
                   2099: sub get_domain_defaults {
1.1172.2.35  raeburn  2100:     my ($domain,$ignore_cache) = @_;
                   2101:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2102:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2103:     unless ($ignore_cache) {
                   2104:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2105:         if (defined($cached)) {
                   2106:             if (ref($result) eq 'HASH') {
                   2107:                 return %{$result};
                   2108:             }
1.943     raeburn  2109:         }
                   2110:     }
                   2111:     my %domdefaults;
                   2112:     my %domconfig =
1.989     raeburn  2113:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2114:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2115:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2116:                                   'requestauthor','selfenrollment',
1.1172.2.89  raeburn  2117:                                   'coursecategories','autoenroll',
                   2118:                                   'helpsettings'],$domain);
1.1172.2.41  raeburn  2119:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2120:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2121:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2122:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2123:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2124:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2125:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2126:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91  raeburn  2127:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2128:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2129:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2130:     } else {
                   2131:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2132:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2133:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2134:     }
1.976     raeburn  2135:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2136:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2137:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2138:         } else {
                   2139:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2140:         }
1.1172.2.6  raeburn  2141:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2142:         foreach my $item (@usertools) {
                   2143:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2144:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2145:             }
                   2146:         }
1.1172.2.29  raeburn  2147:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2148:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2149:         }
1.976     raeburn  2150:     }
1.985     raeburn  2151:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2152:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2153:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2154:         }
                   2155:     }
1.1172.2.9  raeburn  2156:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2157:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2158:     }
1.989     raeburn  2159:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2160:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2161:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2162:         }
                   2163:     }
1.1047    raeburn  2164:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2165:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2166:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2167:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2168:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2169:         }
1.1172.2.41  raeburn  2170:         foreach my $type (@coursetypes) {
                   2171:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2172:                 unless ($type eq 'community') {
                   2173:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2174:                 }
                   2175:             }
                   2176:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2177:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2178:             }
1.1172.2.60  raeburn  2179:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2180:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2181:                     $domdefaults{$type.'postsubtimeout'} =
                   2182:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2183:                 }
                   2184:             }
1.1172.2.30  raeburn  2185:         }
1.1172.2.67  raeburn  2186:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2187:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2188:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2189:                 if (@clonecodes) {
                   2190:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2191:                 }
                   2192:             }
                   2193:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2194:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2195:         }
1.1172.2.103  raeburn  2196:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2197:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2198:         }
1.1047    raeburn  2199:     }
1.1073    raeburn  2200:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2201:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2202:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2203:         }
                   2204:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2205:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2206:         }
1.1172.2.62  raeburn  2207:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2208:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2209:         }
1.1073    raeburn  2210:     }
1.1172.2.41  raeburn  2211:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2212:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2213:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2214:                             'approval','limit');
                   2215:             foreach my $type (@coursetypes) {
                   2216:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2217:                     my @mgrdc = ();
                   2218:                     foreach my $item (@settings) {
                   2219:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2220:                             push(@mgrdc,$item);
                   2221:                         }
                   2222:                     }
                   2223:                     if (@mgrdc) {
                   2224:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2225:                     }
                   2226:                 }
                   2227:             }
                   2228:         }
                   2229:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2230:             foreach my $type (@coursetypes) {
                   2231:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2232:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2233:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2234:                     }
                   2235:                 }
                   2236:             }
                   2237:         }
                   2238:     }
1.1172.2.46  raeburn  2239:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2240:         $domdefaults{'catauth'} = 'std';
                   2241:         $domdefaults{'catunauth'} = 'std';
                   2242:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2243:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2244:         }
                   2245:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2246:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2247:         }
                   2248:     }
1.1172.2.76  raeburn  2249:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2250:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2251:     }
1.1172.2.89  raeburn  2252:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2253:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2254:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2255:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2256:         }
                   2257:     }
1.1172.2.23  raeburn  2258:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2259:     return %domdefaults;
                   2260: }
                   2261: 
1.1172.2.106! raeburn  2262: sub get_dom_cats {
        !          2263:     my ($dom) = @_;
        !          2264:     return unless (&domain($dom));
        !          2265:     my ($cats,$cached)=&is_cached_new('cats',$dom);
        !          2266:     unless (defined($cached)) {
        !          2267:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
        !          2268:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
        !          2269:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
        !          2270:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
        !          2271:             } else {
        !          2272:                 $cats = {};
        !          2273:             }
        !          2274:         } else {
        !          2275:             $cats = {};
        !          2276:         }
        !          2277:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
        !          2278:     }
        !          2279:     return $cats;
        !          2280: }
        !          2281: 
        !          2282: sub get_dom_instcats {
        !          2283:     my ($dom) = @_;
        !          2284:     return unless (&domain($dom));
        !          2285:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
        !          2286:     unless (defined($cached)) {
        !          2287:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
        !          2288:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
        !          2289:         if ($totcodes > 0) {
        !          2290:             my $caller = 'global';
        !          2291:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
        !          2292:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
        !          2293:                 $instcats = {
        !          2294:                                 codes => \%codes,
        !          2295:                                 codetitles => \@codetitles,
        !          2296:                                 cat_titles => \%cat_titles,
        !          2297:                                 cat_order => \%cat_order,
        !          2298:                             };
        !          2299:                 &do_cache_new('instcats',$dom,$instcats,3600);
        !          2300:             }
        !          2301:         }
        !          2302:     }
        !          2303:     return $instcats;
        !          2304: }
        !          2305: 
        !          2306: sub retrieve_instcodes {
        !          2307:     my ($coursecodes,$dom) = @_;
        !          2308:     my $totcodes;
        !          2309:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
        !          2310:     foreach my $course (keys(%courses)) {
        !          2311:         if (ref($courses{$course}) eq 'HASH') {
        !          2312:             if ($courses{$course}{'inst_code'} ne '') {
        !          2313:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
        !          2314:                 $totcodes ++;
        !          2315:             }
        !          2316:         }
        !          2317:     }
        !          2318:     return $totcodes;
        !          2319: }
        !          2320: 
1.344     www      2321: # --------------------------------------------------- Assign a key to a student
                   2322: 
                   2323: sub assign_access_key {
1.364     www      2324: #
                   2325: # a valid key looks like uname:udom#comments
                   2326: # comments are being appended
                   2327: #
1.498     www      2328:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2329:     $kdom=
1.620     albertel 2330:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2331:     $knum=
1.620     albertel 2332:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2333:     $cdom=
1.620     albertel 2334:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2335:     $cnum=
1.620     albertel 2336:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2337:     $udom=$env{'user.name'} unless (defined($udom));
                   2338:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2339:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2340:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2341:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2342:                                                   # assigned to this person
                   2343:                                                   # - this should not happen,
1.345     www      2344:                                                   # unless something went wrong
                   2345:                                                   # the first time around
                   2346: # ready to assign
1.364     www      2347:         $logentry=$1.'; '.$logentry;
1.496     www      2348:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2349:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2350: # key now belongs to user
1.346     www      2351: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2352:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2353:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2354:                 return 'ok';
                   2355:             } else {
                   2356:                 return 
                   2357:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2358: 	    }
                   2359:         } else {
                   2360:             return 'error: Could not assign key, try again later.';
                   2361:         }
1.364     www      2362:     } elsif (!$existing{$ckey}) {
1.345     www      2363: # the key does not exist
                   2364: 	return 'error: The key does not exist';
                   2365:     } else {
                   2366: # the key is somebody else's
                   2367: 	return 'error: The key is already in use';
                   2368:     }
1.344     www      2369: }
                   2370: 
1.364     www      2371: # ------------------------------------------ put an additional comment on a key
                   2372: 
                   2373: sub comment_access_key {
                   2374: #
                   2375: # a valid key looks like uname:udom#comments
                   2376: # comments are being appended
                   2377: #
                   2378:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2379:     $cdom=
1.620     albertel 2380:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2381:     $cnum=
1.620     albertel 2382:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2383:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2384:     if ($existing{$ckey}) {
                   2385:         $existing{$ckey}.='; '.$logentry;
                   2386: # ready to assign
1.367     www      2387:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2388:                                                  $cdom,$cnum) eq 'ok') {
                   2389: 	    return 'ok';
                   2390:         } else {
                   2391: 	    return 'error: Count not store comment.';
                   2392:         }
                   2393:     } else {
                   2394: # the key does not exist
                   2395: 	return 'error: The key does not exist';
                   2396:     }
                   2397: }
                   2398: 
1.344     www      2399: # ------------------------------------------------------ Generate a set of keys
                   2400: 
                   2401: sub generate_access_keys {
1.364     www      2402:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2403:     $cdom=
1.620     albertel 2404:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2405:     $cnum=
1.620     albertel 2406:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2407:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2408:     unless (($cdom) && ($cnum)) { return 0; }
                   2409:     if ($number>10000) { return 0; }
                   2410:     sleep(2); # make sure don't get same seed twice
                   2411:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2412:     my $total=0;
                   2413:     for (my $i=1;$i<=$number;$i++) {
                   2414:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2415:                   sprintf("%lx",int(100000*rand)).'-'.
                   2416:                   sprintf("%lx",int(100000*rand));
                   2417:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2418:        $newkey=~s/0/h/g; # and also 0 and O
                   2419:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2420:        if ($existing{$newkey}) {
                   2421:            $i--;
                   2422:        } else {
1.364     www      2423: 	  if (&put('accesskeys',
                   2424:               { $newkey => '# generated '.localtime().
1.620     albertel 2425:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2426:                            '; '.$logentry },
                   2427: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2428:               $total++;
                   2429: 	  }
                   2430:        }
                   2431:     }
1.620     albertel 2432:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2433:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2434:     return $total;
                   2435: }
                   2436: 
                   2437: # ------------------------------------------------------- Validate an accesskey
                   2438: 
                   2439: sub validate_access_key {
                   2440:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2441:     $cdom=
1.620     albertel 2442:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2443:     $cnum=
1.620     albertel 2444:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2445:     $udom=$env{'user.domain'} unless (defined($udom));
                   2446:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2447:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2448:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2449: }
                   2450: 
                   2451: # ------------------------------------- Find the section of student in a course
1.652     albertel 2452: sub devalidate_getsection_cache {
                   2453:     my ($udom,$unam,$courseid)=@_;
                   2454:     my $hashid="$udom:$unam:$courseid";
                   2455:     &devalidate_cache_new('getsection',$hashid);
                   2456: }
1.298     matthew  2457: 
1.815     albertel 2458: sub courseid_to_courseurl {
                   2459:     my ($courseid) = @_;
                   2460:     #already url style courseid
                   2461:     return $courseid if ($courseid =~ m{^/});
                   2462: 
                   2463:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2464: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2465: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2466: 	return "/$cdom/$cnum";
                   2467:     }
                   2468: 
                   2469:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2470:     if (exists($courseinfo{'num'})) {
                   2471: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2472:     }
                   2473: 
                   2474:     return undef;
                   2475: }
                   2476: 
1.298     matthew  2477: sub getsection {
                   2478:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2479:     my $cachetime=1800;
1.551     albertel 2480: 
                   2481:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2482:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2483:     if (defined($cached)) { return $result; }
                   2484: 
1.298     matthew  2485:     my %Pending; 
                   2486:     my %Expired;
                   2487:     #
                   2488:     # Each role can either have not started yet (pending), be active, 
                   2489:     #    or have expired.
                   2490:     #
                   2491:     # If there is an active role, we are done.
                   2492:     #
                   2493:     # If there is more than one role which has not started yet, 
                   2494:     #     choose the one which will start sooner
                   2495:     # If there is one role which has not started yet, return it.
                   2496:     #
                   2497:     # If there is more than one expired role, choose the one which ended last.
                   2498:     # If there is a role which has expired, return it.
                   2499:     #
1.815     albertel 2500:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2501:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2502:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2503:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2504:         my $section=$1;
                   2505:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2506:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2507:         my $now=time;
1.548     albertel 2508:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2509:             $Expired{$end}=$section;
                   2510:             next;
                   2511:         }
1.548     albertel 2512:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2513:             $Pending{$start}=$section;
                   2514:             next;
                   2515:         }
1.599     albertel 2516:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2517:     }
                   2518:     #
                   2519:     # Presumedly there will be few matching roles from the above
                   2520:     # loop and the sorting time will be negligible.
                   2521:     if (scalar(keys(%Pending))) {
                   2522:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2523:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2524:     } 
                   2525:     if (scalar(keys(%Expired))) {
                   2526:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2527:         my $time = pop(@sorted);
1.599     albertel 2528:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2529:     }
1.599     albertel 2530:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2531: }
1.70      www      2532: 
1.599     albertel 2533: sub save_cache {
                   2534:     &purge_remembered();
1.722     albertel 2535:     #&Apache::loncommon::validate_page();
1.620     albertel 2536:     undef(%env);
1.780     albertel 2537:     undef($env_loaded);
1.599     albertel 2538: }
1.452     albertel 2539: 
1.599     albertel 2540: my $to_remember=-1;
                   2541: my %remembered;
                   2542: my %accessed;
                   2543: my $kicks=0;
                   2544: my $hits=0;
1.849     albertel 2545: sub make_key {
                   2546:     my ($name,$id) = @_;
1.872     albertel 2547:     if (length($id) > 65 
                   2548: 	&& length(&escape($id)) > 200) {
                   2549: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2550:     }
1.849     albertel 2551:     return &escape($name.':'.$id);
                   2552: }
                   2553: 
1.599     albertel 2554: sub devalidate_cache_new {
                   2555:     my ($name,$id,$debug) = @_;
                   2556:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  2557:     my $remembered_id=$name.':'.$id;
1.849     albertel 2558:     $id=&make_key($name,$id);
1.599     albertel 2559:     $memcache->delete($id);
1.1172.2.81  raeburn  2560:     delete($remembered{$remembered_id});
                   2561:     delete($accessed{$remembered_id});
1.599     albertel 2562: }
                   2563: 
                   2564: sub is_cached_new {
                   2565:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  2566:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   2567:                                      # keys in %remembered hash, which persists for
                   2568:                                      # duration of request (no restriction on key length).
                   2569:     if (exists($remembered{$remembered_id})) {
                   2570: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2571: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2572: 	$hits++;
1.1172.2.81  raeburn  2573: 	return ($remembered{$remembered_id},1);
1.599     albertel 2574:     }
1.1172.2.81  raeburn  2575:     $id=&make_key($name,$id);
1.599     albertel 2576:     my $value = $memcache->get($id);
                   2577:     if (!(defined($value))) {
                   2578: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2579: 	return (undef,undef);
1.416     albertel 2580:     }
1.599     albertel 2581:     if ($value eq '__undef__') {
                   2582: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2583: 	$value=undef;
                   2584:     }
1.1172.2.81  raeburn  2585:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2586:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2587:     return ($value,1);
                   2588: }
                   2589: 
                   2590: sub do_cache_new {
                   2591:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  2592:     my $remembered_id=$name.':'.$id;
1.849     albertel 2593:     $id=&make_key($name,$id);
1.599     albertel 2594:     my $setvalue=$value;
                   2595:     if (!defined($setvalue)) {
                   2596: 	$setvalue='__undef__';
                   2597:     }
1.623     albertel 2598:     if (!defined($time) ) {
                   2599: 	$time=600;
                   2600:     }
1.599     albertel 2601:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2602:     my $result = $memcache->set($id,$setvalue,$time);
                   2603:     if (! $result) {
1.872     albertel 2604: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2605: 	$memcache->disconnect_all();
1.872     albertel 2606:     }
1.600     albertel 2607:     # need to make a copy of $value
1.1172.2.81  raeburn  2608:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2609:     return $value;
                   2610: }
                   2611: 
                   2612: sub make_room {
1.1172.2.81  raeburn  2613:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2614: 
1.1172.2.81  raeburn  2615:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2616:                                     : $value;
1.599     albertel 2617:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  2618:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2619:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2620:     my $to_kick;
                   2621:     my $max_time=0;
                   2622:     foreach my $other (keys(%accessed)) {
                   2623: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2624: 	    $to_kick=$other;
                   2625: 	    $max_time=&tv_interval($accessed{$other});
                   2626: 	}
                   2627:     }
                   2628:     delete($remembered{$to_kick});
                   2629:     delete($accessed{$to_kick});
                   2630:     $kicks++;
                   2631:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2632:     return;
                   2633: }
                   2634: 
1.599     albertel 2635: sub purge_remembered {
1.604     albertel 2636:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2637:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2638:     undef(%remembered);
                   2639:     undef(%accessed);
1.428     albertel 2640: }
1.70      www      2641: # ------------------------------------- Read an entry from a user's environment
                   2642: 
                   2643: sub userenvironment {
                   2644:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2645:     my $items;
                   2646:     foreach my $item (@what) {
                   2647:         $items.=&escape($item).'&';
                   2648:     }
                   2649:     $items=~s/\&$//;
1.70      www      2650:     my %returnhash=();
1.1009    raeburn  2651:     my $uhome = &homeserver($unam,$udom);
                   2652:     unless ($uhome eq 'no_host') {
                   2653:         my @answer=split(/\&/, 
                   2654:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2655:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2656:             return %returnhash;
                   2657:         }
1.1009    raeburn  2658:         my $i;
                   2659:         for ($i=0;$i<=$#what;$i++) {
                   2660: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2661:         }
1.70      www      2662:     }
                   2663:     return %returnhash;
1.1       albertel 2664: }
                   2665: 
1.617     albertel 2666: # ---------------------------------------------------------- Get a studentphoto
                   2667: sub studentphoto {
                   2668:     my ($udom,$unam,$ext) = @_;
                   2669:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2670:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2671:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2672:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2673:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2674:             } else {
                   2675:                 my ($result,$perm_reqd)=
1.707     albertel 2676: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2677:                 if ($result eq 'ok') {
                   2678:                     if (!($perm_reqd eq 'yes')) {
                   2679:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2680:                     }
                   2681:                 }
                   2682:             }
                   2683:         }
                   2684:     } else {
                   2685:         my ($result,$perm_reqd) = 
1.707     albertel 2686: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2687:         if ($result eq 'ok') {
                   2688:             if (!($perm_reqd eq 'yes')) {
                   2689:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2690:             }
                   2691:         }
                   2692:     }
                   2693:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2694: }
                   2695: 
                   2696: sub retrievestudentphoto {
                   2697:     my ($udom,$unam,$ext,$type) = @_;
                   2698:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2699:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2700:     if ($ret eq 'ok') {
                   2701:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2702:         if ($type eq 'thumbnail') {
                   2703:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2704:         }
                   2705:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2706:         return $tokenurl;
                   2707:     } else {
                   2708:         if ($type eq 'thumbnail') {
                   2709:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2710:         } else { 
                   2711:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2712:         }
1.617     albertel 2713:     }
                   2714: }
                   2715: 
1.263     www      2716: # -------------------------------------------------------------------- New chat
                   2717: 
                   2718: sub chatsend {
1.724     raeburn  2719:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2720:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2721:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2722:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2723:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2724: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2725: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2726: }
                   2727: 
                   2728: # ------------------------------------------ Find current version of a resource
                   2729: 
                   2730: sub getversion {
                   2731:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2732:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2733:     return &currentversion(&filelocation('',$fname));
                   2734: }
                   2735: 
                   2736: sub currentversion {
                   2737:     my $fname=shift;
                   2738:     my $author=$fname;
                   2739:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2740:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2741:     my $home=&homeserver($uname,$udom);
1.292     www      2742:     if ($home eq 'no_host') { 
                   2743:         return -1; 
                   2744:     }
1.1112    www      2745:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2746:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2747: 	return -1;
                   2748:     }
1.1112    www      2749:     return $answer;
1.263     www      2750: }
                   2751: 
1.1111    www      2752: #
                   2753: # Return special version number of resource if set by override, empty otherwise
                   2754: #
                   2755: sub usedversion {
                   2756:     my $fname=shift;
                   2757:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2758:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2759:     if ($urlversion) { return $urlversion; }
                   2760:     return '';
                   2761: }
                   2762: 
1.1       albertel 2763: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2764: 
1.1       albertel 2765: sub subscribe {
                   2766:     my $fname=shift;
1.761     raeburn  2767:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2768:     $fname=~s/[\n\r]//g;
1.1       albertel 2769:     my $author=$fname;
                   2770:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2771:     my ($udom,$uname)=split(/\//,$author);
                   2772:     my $home=homeserver($uname,$udom);
1.335     albertel 2773:     if ($home eq 'no_host') {
                   2774:         return 'not_found';
1.1       albertel 2775:     }
                   2776:     my $answer=reply("sub:$fname",$home);
1.64      www      2777:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2778: 	$answer.=' by '.$home;
                   2779:     }
1.1       albertel 2780:     return $answer;
                   2781: }
                   2782:     
1.8       www      2783: # -------------------------------------------------------------- Replicate file
                   2784: 
                   2785: sub repcopy {
                   2786:     my $filename=shift;
1.23      www      2787:     $filename=~s/\/+/\//g;
1.1142    raeburn  2788:     my $londocroot = $perlvar{'lonDocRoot'};
                   2789:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2790:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2791:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2792: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2793: 	return &repcopy_userfile($filename);
                   2794:     }
1.532     albertel 2795:     $filename=~s/[\n\r]//g;
1.8       www      2796:     my $transname="$filename.in.transfer";
1.828     www      2797: # FIXME: this should flock
1.607     raeburn  2798:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2799:     my $remoteurl=subscribe($filename);
1.64      www      2800:     if ($remoteurl =~ /^con_lost by/) {
                   2801: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2802:            return 'unavailable';
1.8       www      2803:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2804: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2805: 	   return 'not_found';
1.64      www      2806:     } elsif ($remoteurl =~ /^rejected by/) {
                   2807: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2808:            return 'forbidden';
1.20      www      2809:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2810:            return 'ok';
1.8       www      2811:     } else {
1.290     www      2812:         my $author=$filename;
                   2813:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2814:         my ($udom,$uname)=split(/\//,$author);
                   2815:         my $home=homeserver($uname,$udom);
                   2816:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2817:            my @parts=split(/\//,$filename);
                   2818:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2819:            if ($path ne "$londocroot/res") {
1.8       www      2820:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2821: 	       return 'bad_request';
1.8       www      2822:            }
                   2823:            my $count;
                   2824:            for ($count=5;$count<$#parts;$count++) {
                   2825:                $path.="/$parts[$count]";
                   2826:                if ((-e $path)!=1) {
                   2827: 		   mkdir($path,0777);
                   2828:                }
                   2829:            }
                   2830:            my $ua=new LWP::UserAgent;
                   2831:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2832:            my $response=$ua->request($request,$transname);
                   2833:            if ($response->is_error()) {
                   2834: 	       unlink($transname);
                   2835:                my $message=$response->status_line;
1.672     albertel 2836:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2837:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2838:                return 'unavailable';
1.8       www      2839:            } else {
1.16      www      2840: 	       if ($remoteurl!~/\.meta$/) {
                   2841:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2842:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2843:                   if ($mresponse->is_error()) {
                   2844: 		      unlink($filename.'.meta');
                   2845:                       &logthis(
1.672     albertel 2846:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2847:                   }
                   2848: 	       }
1.8       www      2849:                rename($transname,$filename);
1.607     raeburn  2850:                return 'ok';
1.8       www      2851:            }
1.290     www      2852:        }
1.8       www      2853:     }
1.330     www      2854: }
                   2855: 
                   2856: # ------------------------------------------------ Get server side include body
                   2857: sub ssi_body {
1.381     albertel 2858:     my ($filelink,%form)=@_;
1.606     matthew  2859:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2860:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2861:     }
1.953     www      2862:     my $output='';
                   2863:     my $response;
1.980     raeburn  2864:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2865:        ($output,$response)=&externalssi($filelink);
1.953     www      2866:     } else {
1.1004    droeschl 2867:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2868:        $filelink .= 'inhibitmenu=yes';
1.953     www      2869:        ($output,$response)=&ssi($filelink,%form);
                   2870:     }
1.778     albertel 2871:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2872:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2873:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2874:     if (wantarray) {
                   2875:         return ($output, $response);
                   2876:     } else {
                   2877:         return $output;
                   2878:     }
1.8       www      2879: }
                   2880: 
1.15      www      2881: # --------------------------------------------------------- Server Side Include
                   2882: 
1.782     albertel 2883: sub absolute_url {
                   2884:     my ($host_name) = @_;
                   2885:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2886:     if ($host_name eq '') {
                   2887: 	$host_name = $ENV{'SERVER_NAME'};
                   2888:     }
                   2889:     return $protocol.$host_name;
                   2890: }
                   2891: 
1.942     foxr     2892: #
                   2893: #   Server side include.
                   2894: # Parameters:
                   2895: #  fn     Possibly encrypted resource name/id.
                   2896: #  form   Hash that describes how the rendering should be done
                   2897: #         and other things.
1.944     foxr     2898: # Returns:
1.950     raeburn  2899: #   Scalar context: The content of the response.
                   2900: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2901: #     
1.15      www      2902: sub ssi {
                   2903: 
1.944     foxr     2904:     my ($fn,%form)=@_;
1.1172.2.100  raeburn  2905:     my ($request,$response);
1.711     albertel 2906: 
                   2907:     $form{'no_update_last_known'}=1;
1.895     albertel 2908:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2909:     if (%form) {
1.782     albertel 2910:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58  raeburn  2911:       $request->content(join('&',map {
                   2912:             my $name = escape($_);
                   2913:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   2914:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   2915:             : &escape($form{$_}) );
                   2916:         } keys(%form)));
1.23      www      2917:     } else {
1.782     albertel 2918:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2919:     }
                   2920: 
1.15      www      2921:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100  raeburn  2922: 
1.1172.2.101  raeburn  2923:     if (($env{'request.course.id'}) &&
                   2924:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   2925:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   2926:         ($form{'grade_symb'} ne '') &&
                   2927:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   2928:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100  raeburn  2929:         if (LWP::UserAgent->VERSION >= 5.834) {
                   2930:             my $ua=new LWP::UserAgent;
                   2931:             $ua->local_address('127.0.0.1');
                   2932:             $response = $ua->request($request);
                   2933:         } else {
                   2934:             {
                   2935:                 require LWP::Protocol::http;
                   2936:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
                   2937:                 my $ua=new LWP::UserAgent;
                   2938:                 $response = $ua->request($request);
                   2939:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
                   2940:             }
                   2941:         }
                   2942:     } else {
                   2943:         my $ua=new LWP::UserAgent;
                   2944:         $response = $ua->request($request);
                   2945:     }
1.944     foxr     2946:     if (wantarray) {
1.1172.2.3  raeburn  2947: 	return ($response->content, $response);
1.944     foxr     2948:     } else {
1.1172.2.3  raeburn  2949: 	return $response->content;
1.942     foxr     2950:     }
1.324     www      2951: }
                   2952: 
                   2953: sub externalssi {
                   2954:     my ($url)=@_;
                   2955:     my $ua=new LWP::UserAgent;
                   2956:     my $request=new HTTP::Request('GET',$url);
                   2957:     my $response=$ua->request($request);
1.954     raeburn  2958:     if (wantarray) {
                   2959:         return ($response->content, $response);
                   2960:     } else {
                   2961:         return $response->content;
                   2962:     }
1.15      www      2963: }
1.254     www      2964: 
1.1172.2.98  raeburn  2965: # If the local copy of a replicated resource is outdated, trigger a
                   2966: # connection from the homeserver to flush the delayed queue. If no update
                   2967: # happens, remove local copies of outdated resource (and corresponding
                   2968: # metadata file).
                   2969: 
                   2970: sub remove_stale_resfile {
                   2971:     my ($url) = @_;
                   2972:     my $removed;
                   2973:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   2974:         my $audom = $1;
                   2975:         my $auname = $2;
                   2976:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
                   2977:             my $homeserver = &homeserver($auname,$audom);
                   2978:             unless (($homeserver eq 'no_host') ||
                   2979:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   2980:                 my $fname = &filelocation('',$url);
                   2981:                 if (-e $fname) {
                   2982:                     my $ua=new LWP::UserAgent;
                   2983:                     $ua->timeout(5);
                   2984:                     my $protocol = $protocol{$homeserver};
                   2985:                     $protocol = 'http' if ($protocol ne 'https');
                   2986:                     my $hostname = &hostname($homeserver);
                   2987:                     if ($hostname) {
                   2988:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
                   2989:                         my $request=new HTTP::Request('HEAD',$uri);
                   2990:                         my $response=$ua->request($request);
                   2991:                         if ($response->is_success()) {
                   2992:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   2993:                             my $locmodtime = (stat($fname))[9];
                   2994:                             if ($locmodtime < $remmodtime) {
                   2995:                                 my $stale;
                   2996:                                 my $answer = &reply('pong',$homeserver);
                   2997:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   2998:                                     sleep(0.2);
                   2999:                                     $locmodtime = (stat($fname))[9];
                   3000:                                     if ($locmodtime < $remmodtime) {
                   3001:                                         my $posstransfer = $fname.'.in.transfer';
                   3002:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3003:                                             $removed = 1;
                   3004:                                         } else {
                   3005:                                             $stale = 1;
                   3006:                                         }
                   3007:                                     } else {
                   3008:                                         $removed = 1;
                   3009:                                     }
                   3010:                                 } else {
                   3011:                                     $stale = 1;
                   3012:                                 }
                   3013:                                 if ($stale) {
                   3014:                                     unlink($fname);
                   3015:                                     if ($uri!~/\.meta$/) {
                   3016:                                         unlink($fname.'.meta');
                   3017:                                     }
                   3018:                                     &reply("unsub:$fname",$homeserver);
                   3019:                                     $removed = 1;
                   3020:                                 }
                   3021:                             }
                   3022:                         }
                   3023:                     }
                   3024:                 }
                   3025:             }
                   3026:         }
                   3027:     }
                   3028:     return $removed;
                   3029: }
                   3030: 
1.492     albertel 3031: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3032: 
                   3033: sub allowuploaded {
                   3034:     my ($srcurl,$url)=@_;
                   3035:     $url=&clutter(&declutter($url));
                   3036:     my $dir=$url;
                   3037:     $dir=~s/\/[^\/]+$//;
                   3038:     my %httpref=();
                   3039:     my $httpurl=&hreflocation('',$url);
                   3040:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3041:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3042: }
1.477     raeburn  3043: 
1.1172.2.13  raeburn  3044: #
                   3045: # Determine if the current user should be able to edit a particular resource,
                   3046: # when viewing in course context.
                   3047: # (a) When viewing resource used to determine if "Edit" item is included in
                   3048: #     Functions.
                   3049: # (b) When displaying folder contents in course editor, used to determine if
                   3050: #     "Edit" link will be displayed alongside resource.
                   3051: #
                   3052: #  input: six args -- filename (decluttered), course number, course domain,
                   3053: #                   url, symb (if registered) and group (if this is a group
                   3054: #                   item -- e.g., bulletin board, group page etc.).
                   3055: #  output: array of five scalars --
                   3056: #          $cfile -- url for file editing if editable on current server
                   3057: #          $home -- homeserver of resource (i.e., for author if published,
                   3058: #                                           or course if uploaded.).
                   3059: #          $switchserver --  1 if server switch will be needed.
                   3060: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   3061: #          $forceview -- 1 if icon/link should be to go to view mode
                   3062: #
                   3063: 
                   3064: sub can_edit_resource {
                   3065:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3066:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3067: #
                   3068: # For aboutme pages user can only edit his/her own.
                   3069: #
                   3070:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   3071:         my ($sdom,$sname) = ($1,$2);
                   3072:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3073:             $home = $env{'user.home'};
                   3074:             $cfile = $resurl;
                   3075:             if ($env{'form.forceedit'}) {
                   3076:                 $forceview = 1;
                   3077:             } else {
                   3078:                 $forceedit = 1;
                   3079:             }
                   3080:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3081:         } else {
                   3082:             return;
                   3083:         }
                   3084:     }
                   3085: 
                   3086:     if ($env{'request.course.id'}) {
                   3087:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3088:         if ($group ne '') {
                   3089: # if this is a group homepage or group bulletin board, check group privs
                   3090:             my $allowed = 0;
                   3091:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3092:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   3093:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3094:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3095:                     $allowed = 1;
                   3096:                 }
                   3097:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3098:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3099:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3100:                     $allowed = 1;
                   3101:                 }
                   3102:             }
                   3103:             if ($allowed) {
                   3104:                 $home=&homeserver($cnum,$cdom);
                   3105:                 if ($env{'form.forceedit'}) {
                   3106:                     $forceview = 1;
                   3107:                 } else {
                   3108:                     $forceedit = 1;
                   3109:                 }
                   3110:                 $cfile = $resurl;
                   3111:             } else {
                   3112:                 return;
                   3113:             }
                   3114:         } else {
1.1172.2.15  raeburn  3115:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3116:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3117:                     return;
                   3118:                 }
                   3119:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  3120: #
                   3121: # No edit allowed where CC has switched to student role.
                   3122: #
                   3123:                 return;
                   3124:             }
                   3125:         }
                   3126:     }
                   3127: 
                   3128:     if ($file ne '') {
                   3129:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   3130:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3131:                 $uploaded = 1;
                   3132:                 $incourse = 1;
                   3133:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3134:                     $cfile = &hreflocation('',$file);
                   3135:                     if ($env{'form.forceedit'}) {
                   3136:                         $forceview = 1;
                   3137:                     } else {
                   3138:                         $forceedit = 1;
                   3139:                     }
                   3140:                 }
                   3141:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3142:                 $incourse = 1;
                   3143:                 if ($env{'form.forceedit'}) {
                   3144:                     $forceview = 1;
                   3145:                 } else {
                   3146:                     $forceedit = 1;
                   3147:                 }
                   3148:                 $cfile = $resurl;
                   3149:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3150:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3151:                     $incourse = 1;
                   3152:                     if ($env{'form.forceedit'}) {
                   3153:                         $forceview = 1;
                   3154:                     } else {
                   3155:                         $forceedit = 1;
                   3156:                     }
                   3157:                     $cfile = $resurl;
                   3158:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3159:                     $incourse = 1;
                   3160:                     $cfile = $resurl.'/smpedit';
                   3161:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3162:                     $incourse = 1;
                   3163:                     if ($env{'form.forceedit'}) {
                   3164:                         $forceview = 1;
                   3165:                     } else {
                   3166:                         $forceedit = 1;
                   3167:                     }
                   3168:                     $cfile = $resurl;
1.1172.2.15  raeburn  3169:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3170:                     $incourse = 1;
                   3171:                     if ($env{'form.forceedit'}) {
                   3172:                         $forceview = 1;
                   3173:                     } else {
                   3174:                         $forceedit = 1;
                   3175:                     }
                   3176:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3177:                 }
                   3178:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3179:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3180:                 if (&is_on_map($template)) {
                   3181:                     $incourse = 1;
                   3182:                     $forceview = 1;
                   3183:                     $cfile = $template;
                   3184:                 }
                   3185:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3186:                     $incourse = 1;
                   3187:                     if ($env{'form.forceedit'}) {
                   3188:                         $forceview = 1;
                   3189:                     } else {
                   3190:                         $forceedit = 1;
                   3191:                     }
                   3192:                     $cfile = $resurl;
                   3193:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3194:                 $incourse = 1;
                   3195:                 $forceview = 1;
                   3196:                 if ($symb) {
                   3197:                     my ($map,$id,$res)=&decode_symb($symb);
                   3198:                     $env{'request.symb'} = $symb;
                   3199:                     $cfile = &clutter($res);
                   3200:                 } else {
                   3201:                     $cfile = $env{'form.suppurl'};
                   3202:                     $cfile =~ s{^http://}{};
                   3203:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   3204:                 }
1.1172.2.31  raeburn  3205:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3206:                 if ($env{'form.forceedit'}) {
                   3207:                     $forceview = 1;
                   3208:                 } else {
                   3209:                     $forceedit = 1;
                   3210:                 }
                   3211:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3212:             }
                   3213:         }
                   3214:         if ($uploaded || $incourse) {
                   3215:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3216:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3217:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3218:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3219:             # Check that the user has permission to edit this resource
                   3220:             my $setpriv = 1;
                   3221:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3222:             if (defined($cfudom)) {
                   3223:                 $home=&homeserver($cfuname,$cfudom);
                   3224:                 $cfile=$file;
                   3225:             }
                   3226:         }
                   3227:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3228:             (($home ne '') && ($home ne 'no_host'))) {
                   3229:             my @ids=&current_machine_ids();
                   3230:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3231:                 $switchserver=1;
                   3232:             }
                   3233:         }
                   3234:     }
                   3235:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3236: }
                   3237: 
                   3238: sub is_course_upload {
                   3239:     my ($file,$cnum,$cdom) = @_;
                   3240:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3241:     $uploadpath =~ s{^\/}{};
                   3242:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3243:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3244:         return 1;
                   3245:     }
                   3246:     return;
                   3247: }
                   3248: 
                   3249: sub in_course {
                   3250:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3251:     if ($hideprivileged) {
                   3252:         my $skipuser;
1.1172.2.23  raeburn  3253:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3254:         my @possdoms = ($cdom);
                   3255:         if ($coursehash{'checkforpriv'}) {
                   3256:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3257:         }
                   3258:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3259:             $skipuser = 1;
                   3260:             if ($coursehash{'nothideprivileged'}) {
                   3261:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3262:                     my $user;
                   3263:                     if ($item =~ /:/) {
                   3264:                         $user = $item;
                   3265:                     } else {
                   3266:                         $user = join(':',split(/[\@]/,$item));
                   3267:                     }
                   3268:                     if ($user eq $uname.':'.$udom) {
                   3269:                         undef($skipuser);
                   3270:                         last;
                   3271:                     }
                   3272:                 }
                   3273:             }
                   3274:             if ($skipuser) {
                   3275:                 return 0;
                   3276:             }
                   3277:         }
                   3278:     }
                   3279:     $type ||= 'any';
                   3280:     if (!defined($cdom) || !defined($cnum)) {
                   3281:         my $cid  = $env{'request.course.id'};
                   3282:         $cdom = $env{'course.'.$cid.'.domain'};
                   3283:         $cnum = $env{'course.'.$cid.'.num'};
                   3284:     }
                   3285:     my $typesref;
                   3286:     if (($type eq 'any') || ($type eq 'all')) {
                   3287:         $typesref = ['active','previous','future'];
                   3288:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3289:         $typesref = [$type];
                   3290:     }
                   3291:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3292:                               $typesref,undef,[$cdom]);
                   3293:     my ($tmp) = keys(%roles);
                   3294:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3295:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3296:     if (@course_roles > 0) {
                   3297:         return 1;
                   3298:     }
                   3299:     return 0;
                   3300: }
                   3301: 
1.478     albertel 3302: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3303: # input: action, courseID, current domain, intended
1.637     raeburn  3304: #        path to file, source of file, instruction to parse file for objects,
                   3305: #        ref to hash for embedded objects,
                   3306: #        ref to hash for codebase of java objects.
1.1095    raeburn  3307: #        reference to scalar to accommodate mime type determined
                   3308: #          from File::MMagic if $parser = parse.
1.637     raeburn  3309: #
1.485     raeburn  3310: # output: url to file (if action was uploaddoc), 
                   3311: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3312: #
1.478     albertel 3313: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3314: # course.
1.477     raeburn  3315: #
1.478     albertel 3316: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3317: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3318: #          course's home server.
1.477     raeburn  3319: #
1.478     albertel 3320: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3321: #          be copied from $source (current location) to 
                   3322: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3323: #         and will then be copied to
                   3324: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3325: #         course's home server.
1.485     raeburn  3326: #
1.481     raeburn  3327: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3328: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3329: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3330: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3331: #         in course's home server.
1.637     raeburn  3332: #
1.477     raeburn  3333: 
                   3334: sub process_coursefile {
1.1095    raeburn  3335:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3336:         $mimetype)=@_;
1.477     raeburn  3337:     my $fetchresult;
1.638     albertel 3338:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3339:     if ($action eq 'propagate') {
1.638     albertel 3340:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3341: 			     $home);
1.481     raeburn  3342:     } else {
1.477     raeburn  3343:         my $fpath = '';
                   3344:         my $fname = $file;
1.478     albertel 3345:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3346:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3347:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3348:         if ($action eq 'copy') {
                   3349:             if ($source eq '') {
                   3350:                 $fetchresult = 'no source file';
                   3351:                 return $fetchresult;
                   3352:             } else {
                   3353:                 my $destination = $filepath.'/'.$fname;
                   3354:                 rename($source,$destination);
                   3355:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3356:                                  $home);
1.481     raeburn  3357:             }
                   3358:         } elsif ($action eq 'uploaddoc') {
1.1172.2.96  raeburn  3359:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3360:             print $fh $env{'form.'.$source};
1.481     raeburn  3361:             close($fh);
1.637     raeburn  3362:             if ($parser eq 'parse') {
1.1024    raeburn  3363:                 my $mm = new File::MMagic;
1.1095    raeburn  3364:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3365:                 if ($type eq 'text/html') {
1.1024    raeburn  3366:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3367:                     unless ($parse_result eq 'ok') {
                   3368:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3369:                     }
1.637     raeburn  3370:                 }
1.1095    raeburn  3371:                 if (ref($mimetype)) {
                   3372:                     $$mimetype = $type;
                   3373:                 } 
1.637     raeburn  3374:             }
1.477     raeburn  3375:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3376:                                  $home);
1.481     raeburn  3377:             if ($fetchresult eq 'ok') {
                   3378:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3379:             } else {
                   3380:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3381:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3382:                 return '/adm/notfound.html';
                   3383:             }
1.477     raeburn  3384:         }
                   3385:     }
1.485     raeburn  3386:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3387:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3388:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3389:     }
                   3390:     return $fetchresult;
                   3391: }
                   3392: 
1.637     raeburn  3393: sub build_filepath {
                   3394:     my ($fpath) = @_;
                   3395:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3396:     unless ($fpath eq '') {
                   3397:         my @parts=split('/',$fpath);
                   3398:         foreach my $part (@parts) {
                   3399:             $filepath.= '/'.$part;
                   3400:             if ((-e $filepath)!=1) {
                   3401:                 mkdir($filepath,0777);
                   3402:             }
                   3403:         }
                   3404:     }
                   3405:     return $filepath;
                   3406: }
                   3407: 
                   3408: sub store_edited_file {
1.638     albertel 3409:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3410:     my $file = $primary_url;
                   3411:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3412:     my $fpath = '';
                   3413:     my $fname = $file;
                   3414:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3415:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3416:     my $filepath = &build_filepath($fpath);
1.1172.2.96  raeburn  3417:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3418:     print $fh $content;
                   3419:     close($fh);
1.638     albertel 3420:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3421:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3422: 			  $home);
1.637     raeburn  3423:     if ($$fetchresult eq 'ok') {
                   3424:         return '/uploaded/'.$fpath.'/'.$fname;
                   3425:     } else {
1.638     albertel 3426:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3427: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3428:         return '/adm/notfound.html';
                   3429:     }
                   3430: }
                   3431: 
1.531     albertel 3432: sub clean_filename {
1.831     albertel 3433:     my ($fname,$args)=@_;
1.315     www      3434: # Replace Windows backslashes by forward slashes
1.257     www      3435:     $fname=~s/\\/\//g;
1.831     albertel 3436:     if (!$args->{'keep_path'}) {
                   3437:         # Get rid of everything but the actual filename
                   3438: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3439:     }
1.315     www      3440: # Replace spaces by underscores
                   3441:     $fname=~s/\s+/\_/g;
                   3442: # Replace all other weird characters by nothing
1.831     albertel 3443:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3444: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3445: # numbers
                   3446:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3447:     return $fname;
                   3448: }
1.1051    raeburn  3449: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3450: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3451: # image with the same aspect ratio as the original, but with dimensions which do 
                   3452: # not exceed $resizewidth and $resizeheight.
                   3453:  
1.984     neumanie 3454: sub resizeImage {
1.1051    raeburn  3455:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3456:     my $ima = Image::Magick->new;
                   3457:     my $resized;
                   3458:     if (-e $img_path) {
                   3459:         $ima->Read($img_path);
                   3460:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3461:             my $width = $ima->Get('width');
                   3462:             my $height = $ima->Get('height');
                   3463:             if ($width > $resizewidth) {
                   3464: 	        my $factor = $width/$resizewidth;
                   3465:                 my $newheight = $height/$factor;
                   3466:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3467:                 $resized = 1;
                   3468:             }
                   3469:         }
                   3470:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3471:             my $width = $ima->Get('width');
                   3472:             my $height = $ima->Get('height');
                   3473:             if ($height > $resizeheight) {
                   3474:                 my $factor = $height/$resizeheight;
                   3475:                 my $newwidth = $width/$factor;
                   3476:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3477:                 $resized = 1;
                   3478:             }
                   3479:         }
                   3480:         if ($resized) {
                   3481:             $ima->Write($img_path);
                   3482:         }
                   3483:     }
                   3484:     return;
1.977     amueller 3485: }
                   3486: 
1.608     albertel 3487: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3488: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3489: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3490: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3491: #                                    canceloverwrite, or ''. 
                   3492: #                   if 'coursedoc': upload to the current course
                   3493: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3494: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3495: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3496: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3497: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3498: #        $allfiles - reference to hash for embedded objects
                   3499: #        $codebase - reference to hash for codebase of java objects
                   3500: #        $desuname - username for permanent storage of uploaded file
                   3501: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3502: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3503: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3504: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3505: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3506: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3507: #                    from File::MMagic.
1.858     raeburn  3508: # 
1.686     albertel 3509: # output: url of file in userspace, or error: <message> 
                   3510: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3511: 
1.531     albertel 3512: sub userfileupload {
1.1090    raeburn  3513:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3514:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3515:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3516:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3517:     $fname=&clean_filename($fname);
1.1090    raeburn  3518:     # See if there is anything left
1.257     www      3519:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3520:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3521:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3522:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3523:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3524:         my $now = time;
1.1090    raeburn  3525:         my $filepath;
1.1095    raeburn  3526:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3527:              $filepath = 'tmp/helprequests/'.$now;
                   3528:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3529:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3530:                          '_'.$env{'user.domain'}.'/pending';
                   3531:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3532:             my ($docuname,$docudom);
1.1172.2.96  raeburn  3533:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3534:                 $docudom = $destudom;
                   3535:             } else {
                   3536:                 $docudom = $env{'user.domain'};
                   3537:             }
1.1172.2.96  raeburn  3538:             if ($destuname =~ /^$match_username$/) { 
1.1090    raeburn  3539:                 $docuname = $destuname;
                   3540:             } else {
                   3541:                 $docuname = $env{'user.name'};
                   3542:             }
                   3543:             if (exists($env{'form.group'})) {
                   3544:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3545:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3546:             }
                   3547:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3548:             if ($context eq 'canceloverwrite') {
                   3549:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3550:                 if (-e  $tempfile) {
                   3551:                     my @info = stat($tempfile);
                   3552:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3553:                         unlink($tempfile);
                   3554:                     }
                   3555:                 }
                   3556:                 return;
1.523     raeburn  3557:             }
                   3558:         }
1.1090    raeburn  3559:         # Create the directory if not present
1.741     raeburn  3560:         my @parts=split(/\//,$filepath);
                   3561:         my $fullpath = $perlvar{'lonDaemons'};
                   3562:         for (my $i=0;$i<@parts;$i++) {
                   3563:             $fullpath .= '/'.$parts[$i];
                   3564:             if ((-e $fullpath)!=1) {
                   3565:                 mkdir($fullpath,0777);
                   3566:             }
                   3567:         }
1.1172.2.96  raeburn  3568:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3569:         print $fh $env{'form.'.$formname};
                   3570:         close($fh);
1.1090    raeburn  3571:         if ($context eq 'existingfile') {
                   3572:             my @info = stat($fullpath.'/'.$fname);
                   3573:             return ($fullpath.'/'.$fname,$info[9]);
                   3574:         } else {
                   3575:             return $fullpath.'/'.$fname;
                   3576:         }
1.523     raeburn  3577:     }
1.995     raeburn  3578:     if ($subdir eq 'scantron') {
                   3579:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3580:     } else {
1.995     raeburn  3581:         $fname="$subdir/$fname";
                   3582:     }
1.1090    raeburn  3583:     if ($context eq 'coursedoc') {
1.638     albertel 3584: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3585: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3586:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3587:             return &finishuserfileupload($docuname,$docudom,
                   3588: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3589: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3590:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3591:         } else {
1.1172.2.21  raeburn  3592:             if ($env{'form.folder'}) {
                   3593:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3594:             }
1.638     albertel 3595:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3596: 				       $fname,$formname,$parser,
1.1095    raeburn  3597: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3598:         }
1.719     banghart 3599:     } elsif (defined($destuname)) {
                   3600:         my $docuname=$destuname;
                   3601:         my $docudom=$destudom;
1.860     raeburn  3602: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3603: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3604:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3605:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3606:     } else {
1.638     albertel 3607:         my $docuname=$env{'user.name'};
                   3608:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3609:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3610:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3611:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3612:         }
1.860     raeburn  3613: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3614: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3615:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3616:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3617:     }
1.271     www      3618: }
                   3619: 
                   3620: sub finishuserfileupload {
1.860     raeburn  3621:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3622:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3623:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3624:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3625:   
1.860     raeburn  3626:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3627:     $file=$fname;
                   3628:     if ($fname=~m|/|) {
                   3629:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3630: 	$path.=$fnamepath.'/';
                   3631:     }
1.259     www      3632:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3633:     my $count;
                   3634:     for ($count=4;$count<=$#parts;$count++) {
                   3635:         $filepath.="/$parts[$count]";
                   3636:         if ((-e $filepath)!=1) {
                   3637: 	    mkdir($filepath,0777);
                   3638:         }
                   3639:     }
1.984     neumanie 3640: 
1.258     www      3641: # Save the file
                   3642:     {
1.1172.2.96  raeburn  3643: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 3644: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3645: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3646: 	    return '/adm/notfound.html';
                   3647: 	}
1.1090    raeburn  3648:         if ($context eq 'overwrite') {
1.1117    foxr     3649:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3650:             my $target = $filepath.'/'.$file;
                   3651:             if (-e $source) {
                   3652:                 my @info = stat($source);
                   3653:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3654:                     unless (&File::Copy::move($source,$target)) {
                   3655:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3656:                         return "Moving from $source failed";
                   3657:                     }
                   3658:                 } else {
                   3659:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3660:                 }
                   3661:             } else {
                   3662:                 return "Temporary file: $source missing";
                   3663:             }
                   3664:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3665: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3666: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3667: 	    return '/adm/notfound.html';
                   3668: 	}
1.570     albertel 3669: 	close(FH);
1.1051    raeburn  3670:         if ($resizewidth && $resizeheight) {
                   3671:             my $mm = new File::MMagic;
                   3672:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3673:             if ($mime_type =~ m{^image/}) {
                   3674: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3675:             }  
1.977     amueller 3676: 	}
1.258     www      3677:     }
1.1152    raeburn  3678:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3679:         if (ref($mimetype)) {
                   3680:             if ($$mimetype eq '') {
                   3681:                 my $mm = new File::MMagic;
                   3682:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3683:                 $$mimetype = $type;
                   3684:             }
                   3685:         }
                   3686:     }
1.637     raeburn  3687:     if ($parser eq 'parse') {
1.1152    raeburn  3688:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3689:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3690:                                                        $allfiles,$codebase);
                   3691:             unless ($parse_result eq 'ok') {
                   3692:                 &logthis('Failed to parse '.$filepath.$file.
                   3693: 	   	         ' for embedded media: '.$parse_result); 
                   3694:             }
1.637     raeburn  3695:         }
                   3696:     }
1.860     raeburn  3697:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3698:         my $input = $filepath.'/'.$file;
                   3699:         my $output = $filepath.'/'.'tn-'.$file;
                   3700:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96  raeburn  3701:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   3702:         system({$args[0]} @args);
1.860     raeburn  3703:         if (-e $filepath.'/'.'tn-'.$file) {
                   3704:             $fetchthumb  = 1; 
                   3705:         }
                   3706:     }
1.858     raeburn  3707:  
1.259     www      3708: # Notify homeserver to grep it
                   3709: #
1.984     neumanie 3710:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3711:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3712:     if ($fetchresult eq 'ok') {
1.860     raeburn  3713:         if ($fetchthumb) {
                   3714:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3715:             if ($thumbresult ne 'ok') {
                   3716:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3717:                          $docuhome.': '.$thumbresult);
                   3718:             }
                   3719:         }
1.259     www      3720: #
1.258     www      3721: # Return the URL to it
1.494     albertel 3722:         return '/uploaded/'.$path.$file;
1.263     www      3723:     } else {
1.494     albertel 3724:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3725: 		 ': '.$fetchresult);
1.263     www      3726:         return '/adm/notfound.html';
1.858     raeburn  3727:     }
1.493     albertel 3728: }
                   3729: 
1.637     raeburn  3730: sub extract_embedded_items {
1.961     raeburn  3731:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3732:     my @state = ();
1.1164    raeburn  3733:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3734:     my %javafiles = (
                   3735:                       codebase => '',
                   3736:                       code => '',
                   3737:                       archive => ''
                   3738:                     );
                   3739:     my %mediafiles = (
                   3740:                       src => '',
                   3741:                       movie => '',
                   3742:                      );
1.648     raeburn  3743:     my $p;
                   3744:     if ($content) {
                   3745:         $p = HTML::LCParser->new($content);
                   3746:     } else {
1.961     raeburn  3747:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3748:     }
1.641     albertel 3749:     while (my $t=$p->get_token()) {
1.640     albertel 3750: 	if ($t->[0] eq 'S') {
                   3751: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3752: 	    push(@state, $tagname);
1.648     raeburn  3753:             if (lc($tagname) eq 'allow') {
                   3754:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3755:             }
1.640     albertel 3756: 	    if (lc($tagname) eq 'img') {
                   3757: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3758: 	    }
1.886     albertel 3759: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  3760:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   3761: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   3762:                 }
1.886     albertel 3763: 	    }
1.645     raeburn  3764:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3765:                 my $src;
1.645     raeburn  3766:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3767:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3768:                 } else {
1.1164    raeburn  3769:                     if ($attr->{'src'} ne '') {
                   3770:                         $src = $attr->{'src'};
                   3771:                         &add_filetype($allfiles,$src,'src');
                   3772:                     }
                   3773:                 }
                   3774:                 my $text = $p->get_trimmed_text();
                   3775:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3776:                     my @swfargs = split(/,/,$1);
                   3777:                     foreach my $item (@swfargs) {
                   3778:                         $item =~ s/["']//g;
                   3779:                         $item =~ s/^\s+//;
                   3780:                         $item =~ s/\s+$//;
                   3781:                     }
                   3782:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3783:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3784:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3785:                         } else {
                   3786:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3787:                         }
                   3788:                     }
1.645     raeburn  3789:                 }
                   3790:             }
                   3791:             if (lc($tagname) eq 'link') {
                   3792:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3793:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3794:                 }
                   3795:             }
1.640     albertel 3796: 	    if (lc($tagname) eq 'object' ||
                   3797: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3798: 		foreach my $item (keys(%javafiles)) {
                   3799: 		    $javafiles{$item} = '';
                   3800: 		}
1.1164    raeburn  3801:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3802:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3803:                 }
1.640     albertel 3804: 	    }
                   3805: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3806: 		my $name = lc($attr->{'name'});
                   3807: 		foreach my $item (keys(%javafiles)) {
                   3808: 		    if ($name eq $item) {
                   3809: 			$javafiles{$item} = $attr->{'value'};
                   3810: 			last;
                   3811: 		    }
                   3812: 		}
1.1164    raeburn  3813:                 my $pathfrom;
1.640     albertel 3814: 		foreach my $item (keys(%mediafiles)) {
                   3815: 		    if ($name eq $item) {
1.1164    raeburn  3816:                         $pathfrom = $attr->{'value'};
                   3817:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3818: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3819: 			last;
                   3820: 		    }
                   3821: 		}
1.1164    raeburn  3822:                 if ($name eq 'flashvars') {
                   3823:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3824:                 }
                   3825:                 if ($pathfrom ne '') {
                   3826:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3827:                                          $pathfrom);
                   3828:                 }
1.640     albertel 3829: 	    }
                   3830: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3831: 		foreach my $item (keys(%javafiles)) {
                   3832: 		    if ($attr->{$item}) {
                   3833: 			$javafiles{$item} = $attr->{$item};
                   3834: 			last;
                   3835: 		    }
                   3836: 		}
                   3837: 		foreach my $item (keys(%mediafiles)) {
                   3838: 		    if ($attr->{$item}) {
                   3839: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3840: 			last;
                   3841: 		    }
                   3842: 		}
1.1164    raeburn  3843:                 if (lc($tagname) eq 'embed') {
                   3844:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3845:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3846:                                              $attr->{'src'});
                   3847:                     }
                   3848:                 }
1.640     albertel 3849: 	    }
1.1172.2.35  raeburn  3850:             if (lc($tagname) eq 'iframe') {
                   3851:                 my $src = $attr->{'src'} ;
                   3852:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   3853:                     &add_filetype($allfiles,$src,'src');
                   3854:                 } elsif ($src =~ m{^/}) {
                   3855:                     if ($env{'request.course.id'}) {
                   3856:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3857:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3858:                         my $url = &hreflocation('',$fullpath);
                   3859:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   3860:                             my $relpath = $1;
                   3861:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   3862:                                 &add_filetype($allfiles,$1,'src');
                   3863:                             }
                   3864:                         }
                   3865:                     }
                   3866:                 }
                   3867:             }
1.1164    raeburn  3868:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  3869:                 pop(@state);
1.1164    raeburn  3870:             }
1.640     albertel 3871: 	} elsif ($t->[0] eq 'E') {
                   3872: 	    my ($tagname) = ($t->[1]);
                   3873: 	    if ($javafiles{'codebase'} ne '') {
                   3874: 		$javafiles{'codebase'} .= '/';
                   3875: 	    }  
                   3876: 	    if (lc($tagname) eq 'applet' ||
                   3877: 		lc($tagname) eq 'object' ||
                   3878: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3879: 		) {
                   3880: 		foreach my $item (keys(%javafiles)) {
                   3881: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3882: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3883: 			&add_filetype($allfiles,$file,$item);
                   3884: 		    }
                   3885: 		}
                   3886: 	    } 
                   3887: 	    pop @state;
                   3888: 	}
                   3889:     }
1.1164    raeburn  3890:     foreach my $id (sort(keys(%flashvars))) {
                   3891:         if ($shockwave{$id} ne '') {
                   3892:             my @pairs = split(/\&/,$flashvars{$id});
                   3893:             foreach my $pair (@pairs) {
                   3894:                 my ($key,$value) = split(/\=/,$pair);
                   3895:                 if ($key eq 'thumb') {
                   3896:                     &add_filetype($allfiles,$value,$key);
                   3897:                 } elsif ($key eq 'content') {
                   3898:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3899:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3900:                     if ($ext ne '') {
                   3901:                         &add_filetype($allfiles,$path.$value,$ext);
                   3902:                     }
                   3903:                 }
                   3904:             }
                   3905:         }
                   3906:     }
1.637     raeburn  3907:     return 'ok';
                   3908: }
                   3909: 
1.639     albertel 3910: sub add_filetype {
                   3911:     my ($allfiles,$file,$type)=@_;
                   3912:     if (exists($allfiles->{$file})) {
                   3913: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3914: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3915: 	}
                   3916:     } else {
                   3917: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3918:     }
                   3919: }
                   3920: 
1.1164    raeburn  3921: sub embedded_dependency {
                   3922:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3923:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3924:         if (($identifier ne '') &&
                   3925:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3926:             ($pathfrom ne '')) {
                   3927:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3928:             foreach my $dep (@{$related->{$identifier}}) {
                   3929:                 &add_filetype($allfiles,$path.$dep,'object');
                   3930:             }
                   3931:         }
                   3932:     }
                   3933:     return;
                   3934: }
                   3935: 
1.493     albertel 3936: sub removeuploadedurl {
1.984     neumanie 3937:     my ($url)=@_;	
                   3938:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3939:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3940: }
                   3941: 
                   3942: sub removeuserfile {
                   3943:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3944:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3945:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3946:     if ($result eq 'ok') {	
1.798     raeburn  3947:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3948:             my $metafile = $fname.'.meta';
                   3949:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3950: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3951:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3952:             my $sqlresult = 
1.823     albertel 3953:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3954:                                         'portfolio_metadata',$group,
                   3955:                                         'delete');
1.798     raeburn  3956:         }
                   3957:     }
                   3958:     return $result;
1.257     www      3959: }
1.15      www      3960: 
1.530     albertel 3961: sub mkdiruserfile {
                   3962:     my ($docuname,$docudom,$dir)=@_;
                   3963:     my $home=&homeserver($docuname,$docudom);
                   3964:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3965: }
                   3966: 
1.531     albertel 3967: sub renameuserfile {
                   3968:     my ($docuname,$docudom,$old,$new)=@_;
                   3969:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3970:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3971:                         &escape("$old").':'.&escape("$new"),$home);
                   3972:     if ($result eq 'ok') {
                   3973:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3974:             my $oldmeta = $old.'.meta';
                   3975:             my $newmeta = $new.'.meta';
                   3976:             my $metaresult = 
                   3977:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3978: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3979:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3980:             my $sqlresult = 
1.823     albertel 3981:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3982:                                         'portfolio_metadata',$group,
                   3983:                                         'delete');
1.798     raeburn  3984:         }
                   3985:     }
                   3986:     return $result;
1.531     albertel 3987: }
                   3988: 
1.14      www      3989: # ------------------------------------------------------------------------- Log
                   3990: 
                   3991: sub log {
                   3992:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3993:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3994: }
                   3995: 
                   3996: # ------------------------------------------------------------------ Course Log
1.352     www      3997: #
                   3998: # This routine flushes several buffers of non-mission-critical nature
                   3999: #
1.157     www      4000: 
                   4001: sub flushcourselogs {
1.352     www      4002:     &logthis('Flushing log buffers');
                   4003: #
                   4004: # course logs
                   4005: # This is a log of all transactions in a course, which can be used
                   4006: # for data mining purposes
                   4007: #
                   4008: # It also collects the courseid database, which lists last transaction
                   4009: # times and course titles for all courseids
                   4010: #
                   4011:     my %courseidbuffer=();
1.921     raeburn  4012:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4013:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4014: 		          &escape($courselogs{$crsid}),
                   4015: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4016: 	    delete $courselogs{$crsid};
                   4017:         } else {
                   4018:             &logthis('Failed to flush log buffer for '.$crsid);
                   4019:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4020:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4021:                         " exceeded maximum size, deleting.</font>");
                   4022:                delete $courselogs{$crsid};
                   4023:             }
1.352     www      4024:         }
1.920     raeburn  4025:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4026:             'description' => $coursedescrbuf{$crsid},
                   4027:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4028:             'type'        => $coursetypebuf{$crsid},
                   4029:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4030:         };
1.191     harris41 4031:     }
1.352     www      4032: #
                   4033: # Write course id database (reverse lookup) to homeserver of courses 
                   4034: # Is used in pickcourse
                   4035: #
1.840     albertel 4036:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4037:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4038:                                     $courseidbuffer{$crs_home},
                   4039:                                     $crs_home,'timeonly');
1.352     www      4040:     }
                   4041: #
                   4042: # File accesses
                   4043: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4044: #
1.449     matthew  4045:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4046:         if ($entry =~ /___count$/) {
                   4047:             my ($dom,$name);
1.807     albertel 4048:             ($dom,$name,undef)=
1.811     albertel 4049: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4050:             if (! defined($dom) || $dom eq '' || 
                   4051:                 ! defined($name) || $name eq '') {
1.620     albertel 4052:                 my $cid = $env{'request.course.id'};
                   4053:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4054:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4055:             }
1.450     matthew  4056:             my $value = $accesshash{$entry};
                   4057:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4058:             my %temphash=($url => $value);
1.449     matthew  4059:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4060:             if ($result eq 'ok') {
                   4061:                 delete $accesshash{$entry};
                   4062:             }
                   4063:         } else {
1.811     albertel 4064:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4065:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4066:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4067:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4068:                 delete $accesshash{$entry};
                   4069:             }
1.185     www      4070:         }
1.191     harris41 4071:     }
1.352     www      4072: #
                   4073: # Roles
                   4074: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4075: #
1.800     albertel 4076:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4077:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4078: 	    split(/\:/,$entry);
                   4079:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4080:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4081:                 $rudom,$runame) eq 'ok') {
                   4082: 	    delete $userrolehash{$entry};
                   4083:         }
                   4084:     }
1.662     raeburn  4085: #
1.1172.2.90  raeburn  4086: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4087: #
                   4088:     my %domrolebuffer = ();
1.1000    raeburn  4089:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4090:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4091:         if ($domrolebuffer{$rudom}) {
                   4092:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4093:                       '='.&escape($domainrolehash{$entry});
                   4094:         } else {
                   4095:             $domrolebuffer{$rudom}.=&escape($entry).
                   4096:                       '='.&escape($domainrolehash{$entry});
                   4097:         }
                   4098:         delete $domainrolehash{$entry};
                   4099:     }
                   4100:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  4101:         my %servers;
                   4102:         if (defined(&domain($dom,'primary'))) {
                   4103:             my $primary=&domain($dom,'primary');
                   4104:             my $hostname=&hostname($primary);
                   4105:             $servers{$primary} = $hostname;
                   4106:         } else {
                   4107:             %servers = &get_servers($dom,'library');
                   4108:         }
1.841     albertel 4109: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  4110: 	    if (&reply('domroleput:'.$dom.':'.
                   4111: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4112: 	        last;
                   4113: 	    } else {
1.841     albertel 4114: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4115: 	    }
1.662     raeburn  4116:         }
                   4117:     }
1.186     www      4118:     $dumpcount++;
1.157     www      4119: }
                   4120: 
                   4121: sub courselog {
                   4122:     my $what=shift;
1.158     www      4123:     $what=time.':'.$what;
1.620     albertel 4124:     unless ($env{'request.course.id'}) { return ''; }
                   4125:     $coursedombuf{$env{'request.course.id'}}=
                   4126:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4127:     $coursenumbuf{$env{'request.course.id'}}=
                   4128:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4129:     $coursehombuf{$env{'request.course.id'}}=
                   4130:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4131:     $coursedescrbuf{$env{'request.course.id'}}=
                   4132:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4133:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4134:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4135:     $courseownerbuf{$env{'request.course.id'}}=
                   4136:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4137:     $coursetypebuf{$env{'request.course.id'}}=
                   4138:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4139:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4140: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4141:     } else {
1.620     albertel 4142: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4143:     }
1.620     albertel 4144:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4145: 	&flushcourselogs();
                   4146:     }
1.158     www      4147: }
                   4148: 
                   4149: sub courseacclog {
                   4150:     my $fnsymb=shift;
1.620     albertel 4151:     unless ($env{'request.course.id'}) { return ''; }
                   4152:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4153:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4154:         $what.=':POST';
1.583     matthew  4155:         # FIXME: Probably ought to escape things....
1.800     albertel 4156: 	foreach my $key (keys(%env)) {
                   4157:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4158:                 my $formitem = $1;
                   4159:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4160:                     $what.=':'.$formitem.'='.$env{$key};
                   4161:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4162:                     $what.=':'.$formitem.'='.$env{$key};
                   4163:                 }
1.158     www      4164:             }
1.191     harris41 4165:         }
1.583     matthew  4166:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4167:         # FIXME: We should not be depending on a form parameter that someone
                   4168:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4169:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4170:             $what.= ':POST';
                   4171:             # FIXME: Probably ought to escape things....
                   4172:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4173:                                  'crsdiscuss') {
1.620     albertel 4174:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4175:             }
                   4176:         }
1.158     www      4177:     }
                   4178:     &courselog($what);
1.149     www      4179: }
                   4180: 
1.185     www      4181: sub countacc {
                   4182:     my $url=&declutter(shift);
1.458     matthew  4183:     return if (! defined($url) || $url eq '');
1.620     albertel 4184:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4185: #
                   4186: # Mark that this url was used in this course
                   4187: #
1.620     albertel 4188:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4189: #
                   4190: # Increase the access count for this resource in this child process
                   4191: #
1.281     www      4192:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4193:     $accesshash{$key}++;
1.185     www      4194: }
1.349     www      4195: 
1.361     www      4196: sub linklog {
                   4197:     my ($from,$to)=@_;
                   4198:     $from=&declutter($from);
                   4199:     $to=&declutter($to);
                   4200:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4201:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4202: }
1.1160    www      4203: 
                   4204: sub statslog {
                   4205:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4206:     if ($users<2) { return; }
                   4207:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4208:             'course'       => $env{'request.course.id'},
                   4209:             'sections'     => '"all"',
                   4210:             'num_students' => $users,
                   4211:             'part'         => $part,
                   4212:             'symb'         => $symb,
                   4213:             'mean_tries'   => $av_attempts,
                   4214:             'deg_of_diff'  => $degdiff});
                   4215:     foreach my $key (keys(%dynstore)) {
                   4216:         $accesshash{$key}=$dynstore{$key};
                   4217:     }
                   4218: }
1.361     www      4219:   
1.349     www      4220: sub userrolelog {
                   4221:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4222:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4223:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4224:        $userrolehash
                   4225:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4226:                     =$tend.':'.$tstart;
1.662     raeburn  4227:     }
1.1169    droeschl 4228:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4229:        $userrolehash
                   4230:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4231:                     =$tend.':'.$tstart;
                   4232:     }
1.1172.2.90  raeburn  4233:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4234:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4235:        $domainrolehash
                   4236:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4237:                     = $tend.':'.$tstart;
                   4238:     }
1.351     www      4239: }
                   4240: 
1.957     raeburn  4241: sub courserolelog {
                   4242:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4243:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4244:         my $cdom = $1;
                   4245:         my $cnum = $2;
                   4246:         my $sec = $3;
                   4247:         my $namespace = 'rolelog';
                   4248:         my %storehash = (
                   4249:                            role    => $trole,
                   4250:                            start   => $tstart,
                   4251:                            end     => $tend,
                   4252:                            selfenroll => $selfenroll,
                   4253:                            context    => $context,
                   4254:                         );
                   4255:         if ($trole eq 'gr') {
                   4256:             $namespace = 'groupslog';
                   4257:             $storehash{'group'} = $sec;
                   4258:         } else {
                   4259:             $storehash{'section'} = $sec;
                   4260:         }
                   4261:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4262:                    $domain,$cnum,$cdom);
                   4263:         if (($trole ne 'st') || ($sec ne '')) {
                   4264:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4265:         }
                   4266:     }
                   4267:     return;
                   4268: }
                   4269: 
1.1172.2.9  raeburn  4270: sub domainrolelog {
                   4271:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4272:     if ($area =~ m{^/($match_domain)/$}) {
                   4273:         my $cdom = $1;
                   4274:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4275:         my $namespace = 'rolelog';
                   4276:         my %storehash = (
                   4277:                            role    => $trole,
                   4278:                            start   => $tstart,
                   4279:                            end     => $tend,
                   4280:                            context => $context,
                   4281:                         );
                   4282:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4283:                    $domain,$domconfiguser,$cdom);
                   4284:     }
                   4285:     return;
                   4286: 
                   4287: }
                   4288: 
                   4289: sub coauthorrolelog {
                   4290:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4291:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4292:         my $audom = $1;
                   4293:         my $auname = $2;
                   4294:         my $namespace = 'rolelog';
                   4295:         my %storehash = (
                   4296:                            role    => $trole,
                   4297:                            start   => $tstart,
                   4298:                            end     => $tend,
                   4299:                            context => $context,
                   4300:                         );
                   4301:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4302:                    $domain,$auname,$audom);
                   4303:     }
                   4304:     return;
                   4305: }
                   4306: 
1.351     www      4307: sub get_course_adv_roles {
1.948     raeburn  4308:     my ($cid,$codes) = @_;
1.620     albertel 4309:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4310:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4311:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4312:     my %nothide=();
1.800     albertel 4313:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4314:         if ($user !~ /:/) {
                   4315: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4316:         } else {
                   4317:             $nothide{$user}=1;
                   4318:         }
1.470     www      4319:     }
1.1172.2.23  raeburn  4320:     my @possdoms = ($coursehash{'domain'});
                   4321:     if ($coursehash{'checkforpriv'}) {
                   4322:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4323:     }
1.351     www      4324:     my %returnhash=();
                   4325:     my %dumphash=
                   4326:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4327:     my $now=time;
1.997     raeburn  4328:     my %privileged;
1.1000    raeburn  4329:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4330: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4331:         if (($tstart) && ($tstart<0)) { next; }
                   4332:         if (($tend) && ($tend<$now)) { next; }
                   4333:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4334:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4335: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4336:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4337:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4338: 	if ($role eq 'cr') { next; }
1.948     raeburn  4339:         if ($codes) {
                   4340:             if ($section) { $role .= ':'.$section; }
                   4341:             if ($returnhash{$role}) {
                   4342:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4343:             } else {
                   4344:                 $returnhash{$role}=$username.':'.$domain;
                   4345:             }
1.351     www      4346:         } else {
1.988     raeburn  4347:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4348:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4349:             if ($returnhash{$key}) {
                   4350: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4351:             } else {
                   4352:                 $returnhash{$key}=$username.':'.$domain;
                   4353:             }
1.351     www      4354:         }
1.948     raeburn  4355:     }
1.400     www      4356:     return %returnhash;
                   4357: }
                   4358: 
                   4359: sub get_my_roles {
1.937     raeburn  4360:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4361:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4362:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4363:     my (%dumphash,%nothide);
1.1086    raeburn  4364:     if ($context eq 'userroles') {
1.1166    raeburn  4365:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4366:     } else {
1.1172.2.23  raeburn  4367:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4368:         if ($hidepriv) {
                   4369:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4370:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4371:                 if ($user !~ /:/) {
                   4372:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4373:                 } else {
                   4374:                     $nothide{$user} = 1;
                   4375:                 }
                   4376:             }
                   4377:         }
1.858     raeburn  4378:     }
1.400     www      4379:     my %returnhash=();
                   4380:     my $now=time;
1.999     raeburn  4381:     my %privileged;
1.800     albertel 4382:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4383:         my ($role,$tend,$tstart);
                   4384:         if ($context eq 'userroles') {
1.1149    raeburn  4385:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4386: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4387:         } else {
                   4388:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4389:         }
1.400     www      4390:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4391:         my $status = 'active';
1.939     raeburn  4392:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4393:             $status = 'previous';
                   4394:         } 
                   4395:         if (($tstart) && ($now<$tstart)) {
                   4396:             $status = 'future';
                   4397:         }
                   4398:         if (ref($types) eq 'ARRAY') {
                   4399:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4400:                 next;
                   4401:             } 
                   4402:         } else {
                   4403:             if ($status ne 'active') {
                   4404:                 next;
                   4405:             }
                   4406:         }
1.867     raeburn  4407:         my ($rolecode,$username,$domain,$section,$area);
                   4408:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  4409:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4410:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4411:         } else {
                   4412:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4413:         }
1.832     raeburn  4414:         if (ref($roledoms) eq 'ARRAY') {
                   4415:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4416:                 next;
                   4417:             }
                   4418:         }
                   4419:         if (ref($roles) eq 'ARRAY') {
                   4420:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4421:                 if ($role =~ /^cr\//) {
                   4422:                     if (!grep(/^cr$/,@{$roles})) {
                   4423:                         next;
                   4424:                     }
1.1104    raeburn  4425:                 } elsif ($role =~ /^gr\//) {
                   4426:                     if (!grep(/^gr$/,@{$roles})) {
                   4427:                         next;
                   4428:                     }
1.922     raeburn  4429:                 } else {
                   4430:                     next;
                   4431:                 }
1.832     raeburn  4432:             }
1.867     raeburn  4433:         }
1.937     raeburn  4434:         if ($hidepriv) {
1.1172.2.23  raeburn  4435:             my @privroles = ('dc','su');
1.999     raeburn  4436:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  4437:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4438:             } else {
1.1172.2.23  raeburn  4439:                 my $possdoms = [$domain];
                   4440:                 if (ref($roledoms) eq 'ARRAY') {
                   4441:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  4442:                 }
1.1172.2.23  raeburn  4443:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4444:                     if (!$nothide{$username.':'.$domain}) {
                   4445:                         next;
                   4446:                     }
                   4447:                 }
1.937     raeburn  4448:             }
                   4449:         }
1.933     raeburn  4450:         if ($withsec) {
                   4451:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4452:                 $tstart.':'.$tend;
                   4453:         } else {
                   4454:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4455:         }
1.832     raeburn  4456:     }
1.373     www      4457:     return %returnhash;
1.399     www      4458: }
                   4459: 
1.1172.2.89  raeburn  4460: sub get_all_adhocroles {
                   4461:     my ($dom) = @_;
                   4462:     my @roles_by_num = ();
                   4463:     my %domdefaults = &get_domain_defaults($dom);
                   4464:     my (%description,%access_in_dom,%access_info);
                   4465:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   4466:         my $count = 0;
                   4467:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   4468:         my %ordered;
                   4469:         foreach my $role (sort(keys(%domcurrent))) {
                   4470:             my ($order,$desc,$access_in_dom);
                   4471:             if (ref($domcurrent{$role}) eq 'HASH') {
                   4472:                 $order = $domcurrent{$role}{'order'};
                   4473:                 $desc = $domcurrent{$role}{'desc'};
                   4474:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   4475:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   4476:             }
                   4477:             if ($order eq '') {
                   4478:                 $order = $count;
                   4479:             }
                   4480:             $ordered{$order} = $role;
                   4481:             if ($desc ne '') {
                   4482:                 $description{$role} = $desc;
                   4483:             } else {
                   4484:                 $description{$role}= $role;
                   4485:             }
                   4486:             $count++;
                   4487:         }
                   4488:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   4489:             push(@roles_by_num,$ordered{$item});
                   4490:         }
                   4491:     }
                   4492:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   4493: }
                   4494: 
                   4495: sub get_my_adhocroles {
                   4496:     my ($cid,$checkreg) = @_;
                   4497:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   4498:     if ($env{'request.course.id'} eq $cid) {
                   4499:         $cdom = $env{'course.'.$cid.'.domain'};
                   4500:         $cnum = $env{'course.'.$cid.'.num'};
                   4501:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   4502:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   4503:         $cdom = $1;
                   4504:         $cnum = $2;
                   4505:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   4506:                                      $cdom,$cnum);
                   4507:     }
                   4508:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   4509:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4510:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   4511:         if ($rosterhash{$user} ne '') {
                   4512:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   4513:             return ([],{}) if ($type eq 'auto');
                   4514:         }
                   4515:     }
                   4516:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  4517:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  4518:             my $then=$env{'user.login.time'};
                   4519:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  4520:             if (!$update) {
                   4521:                 $update = $then;
                   4522:             }
                   4523:             my @liveroles;
                   4524:             foreach my $role ('dh','da') {
                   4525:                 if ($env{"user.role.$role./$cdom/"}) {
                   4526:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   4527:                     my $limit = $update;
                   4528:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   4529:                         $limit = $then;
                   4530:                     }
                   4531:                     my $activerole = 1;
                   4532:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   4533:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   4534:                     if ($activerole) {
                   4535:                         push(@liveroles,$role);
                   4536:                     }
                   4537:                 }
                   4538:             }
                   4539:             if (@liveroles) {
1.1172.2.89  raeburn  4540:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   4541:                     my ($accessref,$accessinfo,%access_in_dom);
                   4542:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   4543:                     if (ref($roles_by_num) eq 'ARRAY') {
                   4544:                         if (@{$roles_by_num}) {
                   4545:                             my %settings;
                   4546:                             if ($env{'request.course.id'} eq $cid) {
                   4547:                                 foreach my $envkey (keys(%env)) {
                   4548:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   4549:                                         $settings{$1} = $env{$envkey};
                   4550:                                     }
                   4551:                                 }
                   4552:                             } else {
                   4553:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   4554:                             }
                   4555:                             my %setincrs;
                   4556:                             if ($settings{'internal.adhocaccess'}) {
                   4557:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   4558:                             }
                   4559:                             my @statuses;
                   4560:                             if ($env{'environment.inststatus'}) {
                   4561:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   4562:                             }
                   4563:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4564:                             if (ref($accessref) eq 'HASH') {
                   4565:                                 %access_in_dom = %{$accessref};
                   4566:                             }
                   4567:                             foreach my $role (@{$roles_by_num}) {
                   4568:                                 my ($curraccess,@okstatus,@personnel);
                   4569:                                 if ($setincrs{$role}) {
                   4570:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   4571:                                     if ($curraccess eq 'status') {
                   4572:                                         @okstatus = split(/\&/,$rest);
                   4573:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4574:                                         @personnel = split(/\&/,$rest);
                   4575:                                     }
                   4576:                                 } else {
                   4577:                                     $curraccess = $access_in_dom{$role};
                   4578:                                     if (ref($accessinfo) eq 'HASH') {
                   4579:                                         if ($curraccess eq 'status') {
                   4580:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4581:                                                 @okstatus = @{$accessinfo->{$role}};
                   4582:                                             }
                   4583:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4584:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4585:                                                 @personnel = @{$accessinfo->{$role}};
                   4586:                                             }
                   4587:                                         }
                   4588:                                     }
                   4589:                                 }
                   4590:                                 if ($curraccess eq 'none') {
                   4591:                                     next;
                   4592:                                 } elsif ($curraccess eq 'all') {
                   4593:                                     push(@possroles,$role);
1.1172.2.90  raeburn  4594:                                 } elsif ($curraccess eq 'dh') {
                   4595:                                     if (grep(/^dh$/,@liveroles)) {
                   4596:                                         push(@possroles,$role);
                   4597:                                     } else {
                   4598:                                         next;
                   4599:                                     }
                   4600:                                 } elsif ($curraccess eq 'da') {
                   4601:                                     if (grep(/^da$/,@liveroles)) {
                   4602:                                         push(@possroles,$role);
                   4603:                                     } else {
                   4604:                                         next;
                   4605:                                     }
1.1172.2.89  raeburn  4606:                                 } elsif ($curraccess eq 'status') {
                   4607:                                     if (@okstatus) {
                   4608:                                         if (!@statuses) {
                   4609:                                             if (grep(/^default$/,@okstatus)) {
                   4610:                                                 push(@possroles,$role);
                   4611:                                             }
                   4612:                                         } else {
                   4613:                                             foreach my $status (@okstatus) {
                   4614:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   4615:                                                     push(@possroles,$role);
                   4616:                                                     last;
                   4617:                                                 }
                   4618:                                             }
                   4619:                                         }
                   4620:                                     }
                   4621:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4622:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   4623:                                         if ($curraccess eq 'exc') {
                   4624:                                             push(@possroles,$role);
                   4625:                                         }
                   4626:                                     } elsif ($curraccess eq 'inc') {
                   4627:                                         push(@possroles,$role);
                   4628:                                     }
                   4629:                                 }
                   4630:                             }
                   4631:                         }
                   4632:                     }
                   4633:                 }
                   4634:             }
                   4635:         }
                   4636:     }
                   4637:     unless (ref($description) eq 'HASH') {
                   4638:         if (ref($roles_by_num) eq 'ARRAY') {
                   4639:             my %desc;
                   4640:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   4641:             $description = \%desc;
                   4642:         } else {
                   4643:             $description = {};
                   4644:         }
                   4645:     }
                   4646:     return (\@possroles,$description);
                   4647: }
                   4648: 
1.399     www      4649: # ----------------------------------------------------- Frontpage Announcements
                   4650: #
                   4651: #
                   4652: 
                   4653: sub postannounce {
                   4654:     my ($server,$text)=@_;
1.844     albertel 4655:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4656:     unless ($text=~/\w/) { $text=''; }
                   4657:     return &reply('setannounce:'.&escape($text),$server);
                   4658: }
                   4659: 
                   4660: sub getannounce {
1.448     albertel 4661: 
1.1172.2.96  raeburn  4662:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4663: 	my $announcement='';
1.800     albertel 4664: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4665: 	close($fh);
1.399     www      4666: 	if ($announcement=~/\w/) { 
                   4667: 	    return 
                   4668:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4669:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4670: 	} else {
                   4671: 	    return '';
                   4672: 	}
                   4673:     } else {
                   4674: 	return '';
                   4675:     }
1.351     www      4676: }
1.353     www      4677: 
                   4678: # ---------------------------------------------------------- Course ID routines
                   4679: # Deal with domain's nohist_courseid.db files
                   4680: #
                   4681: 
                   4682: sub courseidput {
1.921     raeburn  4683:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4684:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4685:     my $outcome;
                   4686:     if ($caller eq 'timeonly') {
                   4687:         my $cids = '';
                   4688:         foreach my $item (keys(%$storehash)) {
                   4689:             $cids.=&escape($item).'&';
                   4690:         }
                   4691:         $cids=~s/\&$//;
                   4692:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4693:                           $coursehome);       
                   4694:     } else {
                   4695:         my $items = '';
                   4696:         foreach my $item (keys(%$storehash)) {
                   4697:             $items.= &escape($item).'='.
                   4698:                      &freeze_escape($$storehash{$item}).'&';
                   4699:         }
                   4700:         $items=~s/\&$//;
                   4701:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4702:                           $coursehome);
1.918     raeburn  4703:     }
                   4704:     if ($outcome eq 'unknown_cmd') {
                   4705:         my $what;
                   4706:         foreach my $cid (keys(%$storehash)) {
                   4707:             $what .= &escape($cid).'=';
1.921     raeburn  4708:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4709:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4710:             }
                   4711:             $what =~ s/\:$/&/;
                   4712:         }
                   4713:         $what =~ s/\&$//;  
                   4714:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4715:     } else {
                   4716:         return $outcome;
                   4717:     }
1.353     www      4718: }
                   4719: 
                   4720: sub courseiddump {
1.921     raeburn  4721:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4722:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4723:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  4724:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  4725:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  4726:     my $as_hash = 1;
                   4727:     my %returnhash;
                   4728:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4729:     my %libserv = &all_library();
                   4730:     foreach my $tryserver (keys(%libserv)) {
                   4731:         if ( (  $hostidflag == 1 
                   4732: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4733: 	     || (!defined($hostidflag)) ) {
                   4734: 
1.918     raeburn  4735: 	    if (($domfilter eq '') ||
                   4736: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  4737:                 my $rep;
                   4738:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   4739:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   4740:                         join(":", (&host_domain($tryserver), $sincefilter,
                   4741:                                 &escape($descfilter), &escape($instcodefilter),
                   4742:                                 &escape($ownerfilter), &escape($coursefilter),
                   4743:                                 &escape($typefilter), &escape($regexp_ok),
                   4744:                                 $as_hash, &escape($selfenrollonly),
                   4745:                                 &escape($catfilter), $showhidden, $caller,
                   4746:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   4747:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  4748:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   4749:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  4750:                 } else {
                   4751:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4752:                              $sincefilter.':'.&escape($descfilter).':'.
                   4753:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4754:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4755:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4756:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4757:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4758:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4759:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  4760:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   4761:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  4762:                 }
                   4763: 
1.918     raeburn  4764:                 my @pairs=split(/\&/,$rep);
                   4765:                 foreach my $item (@pairs) {
                   4766:                     my ($key,$value)=split(/\=/,$item,2);
                   4767:                     $key = &unescape($key);
                   4768:                     next if ($key =~ /^error: 2 /);
                   4769:                     my $result = &thaw_unescape($value);
                   4770:                     if (ref($result) eq 'HASH') {
                   4771:                         $returnhash{$key}=$result;
                   4772:                     } else {
1.921     raeburn  4773:                         my @responses = split(/:/,$value);
                   4774:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4775:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4776:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4777:                         }
1.1008    raeburn  4778:                     }
1.353     www      4779:                 }
                   4780:             }
                   4781:         }
                   4782:     }
                   4783:     return %returnhash;
                   4784: }
                   4785: 
1.1055    raeburn  4786: sub courselastaccess {
                   4787:     my ($cdom,$cnum,$hostidref) = @_;
                   4788:     my %returnhash;
                   4789:     if ($cdom && $cnum) {
                   4790:         my $chome = &homeserver($cnum,$cdom);
                   4791:         if ($chome ne 'no_host') {
                   4792:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4793:             &extract_lastaccess(\%returnhash,$rep);
                   4794:         }
                   4795:     } else {
                   4796:         if (!$cdom) { $cdom=''; }
                   4797:         my %libserv = &all_library();
                   4798:         foreach my $tryserver (keys(%libserv)) {
                   4799:             if (ref($hostidref) eq 'ARRAY') {
                   4800:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4801:             } 
                   4802:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4803:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4804:                 &extract_lastaccess(\%returnhash,$rep);
                   4805:             }
                   4806:         }
                   4807:     }
                   4808:     return %returnhash;
                   4809: }
                   4810: 
                   4811: sub extract_lastaccess {
                   4812:     my ($returnhash,$rep) = @_;
                   4813:     if (ref($returnhash) eq 'HASH') {
                   4814:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4815:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4816:                  $rep eq '') {
                   4817:             my @pairs=split(/\&/,$rep);
                   4818:             foreach my $item (@pairs) {
                   4819:                 my ($key,$value)=split(/\=/,$item,2);
                   4820:                 $key = &unescape($key);
                   4821:                 next if ($key =~ /^error: 2 /);
                   4822:                 $returnhash->{$key} = &thaw_unescape($value);
                   4823:             }
                   4824:         }
                   4825:     }
                   4826:     return;
                   4827: }
                   4828: 
1.658     raeburn  4829: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4830: 
                   4831: sub dcmailput {
1.685     raeburn  4832:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4833:     my $status = &Apache::lonnet::critical(
1.740     www      4834:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4835:        &escape($message),$server);
1.662     raeburn  4836:     return $status;
                   4837: }
                   4838: 
1.658     raeburn  4839: sub dcmaildump {
                   4840:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4841:     my %returnhash=();
1.846     albertel 4842: 
                   4843:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4844:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4845:                                                          &escape($enddate).':';
                   4846: 	my @esc_senders=map { &escape($_)} @$senders;
                   4847: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4848: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4849:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4850:             if (($key) && ($value)) {
                   4851:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4852:             }
                   4853:         }
                   4854:     }
                   4855:     return %returnhash;
                   4856: }
1.662     raeburn  4857: # ---------------------------------------------------------- Domain roles
                   4858: 
                   4859: sub get_domain_roles {
                   4860:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4861:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4862:         $startdate = '.';
                   4863:     }
1.1018    raeburn  4864:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4865:         $enddate = '.';
                   4866:     }
1.922     raeburn  4867:     my $rolelist;
                   4868:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  4869:         $rolelist = join('&',@{$roles});
1.922     raeburn  4870:     }
1.662     raeburn  4871:     my %personnel = ();
1.841     albertel 4872: 
                   4873:     my %servers = &get_servers($dom,'library');
                   4874:     foreach my $tryserver (keys(%servers)) {
                   4875: 	%{$personnel{$tryserver}}=();
                   4876: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4877: 					    &escape($startdate).':'.
                   4878: 					    &escape($enddate).':'.
                   4879: 					    &escape($rolelist), $tryserver))) {
                   4880: 	    my ($key,$value) = split(/\=/,$line,2);
                   4881: 	    if (($key) && ($value)) {
                   4882: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4883: 	    }
                   4884: 	}
1.662     raeburn  4885:     }
                   4886:     return %personnel;
                   4887: }
1.658     raeburn  4888: 
1.1172.2.89  raeburn  4889: sub get_active_domroles {
                   4890:     my ($dom,$roles) = @_;
                   4891:     return () unless (ref($roles) eq 'ARRAY');
                   4892:     my $now = time;
                   4893:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   4894:     my %domroles;
                   4895:     foreach my $server (keys(%dompersonnel)) {
                   4896:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   4897:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   4898:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   4899:         }
                   4900:     }
                   4901:     return %domroles;
                   4902: }
                   4903: 
1.1057    www      4904: # ----------------------------------------------------------- Interval timing 
1.149     www      4905: 
1.1153    www      4906: {
                   4907: # Caches needed for speedup of navmaps
                   4908: # We don't want to cache this for very long at all (5 seconds at most)
                   4909: # 
                   4910: # The user for whom we cache
                   4911: my $cachedkey='';
                   4912: # The cached times for this user
                   4913: my %cachedtimes=();
                   4914: # When this was last done
1.1172.2.66  raeburn  4915: my $cachedtime='';
1.1153    www      4916: 
                   4917: sub load_all_first_access {
1.1154    raeburn  4918:     my ($uname,$udom)=@_;
1.1156    www      4919:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  4920:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4921:         return;
                   4922:     }
                   4923:     $cachedtime=time;
                   4924:     $cachedkey=$uname.':'.$udom;
                   4925:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4926: }
                   4927: 
1.504     albertel 4928: sub get_first_access {
1.1162    raeburn  4929:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4930:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4931:     if ($argsymb) { $symb=$argsymb; }
                   4932:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4933:     if ($argmap) { $map = $argmap; }
1.926     albertel 4934:     if ($type eq 'course') {
                   4935: 	$res='course';
                   4936:     } elsif ($type eq 'map') {
1.588     albertel 4937: 	$res=&symbread($map);
                   4938:     } else {
                   4939: 	$res=$symb;
                   4940:     }
1.1153    www      4941:     &load_all_first_access($uname,$udom);
                   4942:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4943: }
                   4944: 
                   4945: sub set_first_access {
1.1162    raeburn  4946:     my ($type,$interval)=@_;
1.790     albertel 4947:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4948:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4949:     if ($type eq 'course') {
                   4950: 	$res='course';
                   4951:     } elsif ($type eq 'map') {
1.588     albertel 4952: 	$res=&symbread($map);
                   4953:     } else {
                   4954: 	$res=$symb;
                   4955:     }
1.1153    www      4956:     $cachedkey='';
1.1162    raeburn  4957:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102  raeburn  4958:     if ($firstaccess) {
                   4959:         &logthis("First access time already set ($firstaccess) when attempting ".
                   4960:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   4961:                  "in $courseid");
                   4962:         return 'already_set';
                   4963:     } else {
1.1162    raeburn  4964:         my $start = time;
                   4965: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4966:                           $udom,$uname);
                   4967:         if ($putres eq 'ok') {
                   4968:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4969:                  $udom,$uname); 
                   4970:             &appenv(
                   4971:                      {
                   4972:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4973:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4974:                      }
                   4975:                   );
1.1172.2.97  raeburn  4976:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   4977:                 $cachedtimes{"$courseid\0$res"} = $start;
                   4978:             }
1.1172.2.102  raeburn  4979:         } elsif ($putres ne 'refused') {
                   4980:             &logthis("Result: $putres when attempting to set first access time ".
                   4981:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  4982:         }
                   4983:         return $putres;
1.505     albertel 4984:     }
                   4985:     return 'already_set';
1.504     albertel 4986: }
1.1153    www      4987: }
1.1172.2.32  raeburn  4988: 
                   4989: sub checkout {
                   4990:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   4991:     my $now=time;
                   4992:     my $lonhost=$perlvar{'lonHostID'};
                   4993:     my $infostr=&escape(
                   4994:                  'CHECKOUTTOKEN&'.
                   4995:                  $tuname.'&'.
                   4996:                  $tudom.'&'.
                   4997:                  $tcrsid.'&'.
                   4998:                  $symb.'&'.
                   4999:                  $now.'&'.$ENV{'REMOTE_ADDR'});
                   5000:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5001:     if ($token=~/^error\:/) {
                   5002:         &logthis("<font color=\"blue\">WARNING: ".
                   5003:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5004:                  "</font>");
                   5005:         return '';
                   5006:     }
                   5007: 
                   5008:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5009:     $token=~tr/a-z/A-Z/;
                   5010: 
                   5011:     my %infohash=('resource.0.outtoken' => $token,
                   5012:                   'resource.0.checkouttime' => $now,
                   5013:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
                   5014: 
                   5015:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5016:        return '';
                   5017:     } else {
                   5018:         &logthis("<font color=\"blue\">WARNING: ".
                   5019:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5020:                  "</font>");
                   5021:     }
                   5022: 
                   5023:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5024:                          &escape('Checkout '.$infostr.' - '.
                   5025:                                                  $token)) ne 'ok') {
                   5026:         return '';
                   5027:     } else {
                   5028:         &logthis("<font color=\"blue\">WARNING: ".
                   5029:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5030:                  "</font>");
                   5031:     }
                   5032:     return $token;
                   5033: }
                   5034: 
                   5035: # ------------------------------------------------------------ Check in an item
                   5036: 
                   5037: sub checkin {
                   5038:     my $token=shift;
                   5039:     my $now=time;
                   5040:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   5041:     $lonhost=~tr/A-Z/a-z/;
                   5042:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   5043:     $dtoken=~s/\W/\_/g;
                   5044:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   5045:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   5046: 
                   5047:     unless (($tuname) && ($tudom)) {
                   5048:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   5049:         return '';
                   5050:     }
                   5051: 
                   5052:     unless (&allowed('mgr',$tcrsid)) {
                   5053:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   5054:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   5055:         return '';
                   5056:     }
                   5057: 
                   5058:     my %infohash=('resource.0.intoken' => $token,
                   5059:                   'resource.0.checkintime' => $now,
                   5060:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
                   5061: 
                   5062:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5063:        return '';
                   5064:     }
                   5065: 
                   5066:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5067:                          &escape('Checkin - '.$token)) ne 'ok') {
                   5068:         return '';
                   5069:     }
                   5070: 
                   5071:     return ($symb,$tuname,$tudom,$tcrsid);
                   5072: }
                   5073: 
1.110     www      5074: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5075: 
                   5076: sub expirespread {
                   5077:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5078:     my $cid=$env{'request.course.id'}; 
1.110     www      5079:     if ($cid) {
                   5080:        my $now=time;
                   5081:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5082:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5083:                             $env{'course.'.$cid.'.num'}.
1.110     www      5084: 	        	    ':nohist_expirationdates:'.
                   5085:                             &escape($key).'='.$now,
1.620     albertel 5086:                             $env{'course.'.$cid.'.home'})
1.110     www      5087:     }
                   5088:     return 'ok';
1.14      www      5089: }
                   5090: 
1.109     www      5091: # ----------------------------------------------------- Devalidate Spreadsheets
                   5092: 
                   5093: sub devalidate {
1.325     www      5094:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5095:     my $cid=$env{'request.course.id'}; 
1.109     www      5096:     if ($cid) {
1.391     matthew  5097:         # delete the stored spreadsheets for
                   5098:         # - the student level sheet of this user in course's homespace
                   5099:         # - the assessment level sheet for this resource 
                   5100:         #   for this user in user's homespace
1.553     albertel 5101: 	# - current conditional state info
1.325     www      5102: 	my $key=$uname.':'.$udom.':';
1.109     www      5103:         my $status=
1.299     matthew  5104: 	    &del('nohist_calculatedsheets',
1.391     matthew  5105: 		 [$key.'studentcalc:'],
1.620     albertel 5106: 		 $env{'course.'.$cid.'.domain'},
                   5107: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5108: 		.' '.
                   5109: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5110: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5111:         unless ($status eq 'ok ok') {
                   5112:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5113:                     $uname.' at '.$udom.' for '.
1.109     www      5114: 		    $symb.': '.$status);
1.133     albertel 5115:         }
1.553     albertel 5116: 	&delenv('user.state.'.$cid);
1.109     www      5117:     }
                   5118: }
                   5119: 
1.265     albertel 5120: sub get_scalar {
                   5121:     my ($string,$end) = @_;
                   5122:     my $value;
                   5123:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5124: 	$value = $1;
                   5125:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5126: 	$value = $1;
                   5127:     }
                   5128:     return &unescape($value);
                   5129: }
                   5130: 
                   5131: sub array2str {
                   5132:   my (@array) = @_;
                   5133:   my $result=&arrayref2str(\@array);
                   5134:   $result=~s/^__ARRAY_REF__//;
                   5135:   $result=~s/__END_ARRAY_REF__$//;
                   5136:   return $result;
                   5137: }
                   5138: 
1.204     albertel 5139: sub arrayref2str {
                   5140:   my ($arrayref) = @_;
1.265     albertel 5141:   my $result='__ARRAY_REF__';
1.204     albertel 5142:   foreach my $elem (@$arrayref) {
1.265     albertel 5143:     if(ref($elem) eq 'ARRAY') {
                   5144:       $result.=&arrayref2str($elem).'&';
                   5145:     } elsif(ref($elem) eq 'HASH') {
                   5146:       $result.=&hashref2str($elem).'&';
                   5147:     } elsif(ref($elem)) {
                   5148:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5149:     } else {
                   5150:       $result.=&escape($elem).'&';
                   5151:     }
                   5152:   }
                   5153:   $result=~s/\&$//;
1.265     albertel 5154:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5155:   return $result;
                   5156: }
                   5157: 
1.168     albertel 5158: sub hash2str {
1.204     albertel 5159:   my (%hash) = @_;
                   5160:   my $result=&hashref2str(\%hash);
1.265     albertel 5161:   $result=~s/^__HASH_REF__//;
                   5162:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5163:   return $result;
                   5164: }
                   5165: 
                   5166: sub hashref2str {
                   5167:   my ($hashref)=@_;
1.265     albertel 5168:   my $result='__HASH_REF__';
1.800     albertel 5169:   foreach my $key (sort(keys(%$hashref))) {
                   5170:     if (ref($key) eq 'ARRAY') {
                   5171:       $result.=&arrayref2str($key).'=';
                   5172:     } elsif (ref($key) eq 'HASH') {
                   5173:       $result.=&hashref2str($key).'=';
                   5174:     } elsif (ref($key)) {
1.265     albertel 5175:       $result.='=';
1.800     albertel 5176:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5177:     } else {
1.1132    raeburn  5178: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5179:     }
                   5180: 
1.800     albertel 5181:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5182:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5183:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5184:       $result.=&hashref2str($hashref->{$key}).'&';
                   5185:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5186:        $result.='&';
1.800     albertel 5187:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5188:     } else {
1.800     albertel 5189:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5190:     }
                   5191:   }
1.168     albertel 5192:   $result=~s/\&$//;
1.265     albertel 5193:   $result .= '__END_HASH_REF__';
1.168     albertel 5194:   return $result;
                   5195: }
                   5196: 
                   5197: sub str2hash {
1.265     albertel 5198:     my ($string)=@_;
                   5199:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5200:     return %$hash;
                   5201: }
                   5202: 
                   5203: sub str2hashref {
1.168     albertel 5204:   my ($string) = @_;
1.265     albertel 5205: 
                   5206:   my %hash;
                   5207: 
                   5208:   if($string !~ /^__HASH_REF__/) {
                   5209:       if (! ($string eq '' || !defined($string))) {
                   5210: 	  $hash{'error'}='Not hash reference';
                   5211:       }
                   5212:       return (\%hash, $string);
                   5213:   }
                   5214: 
                   5215:   $string =~ s/^__HASH_REF__//;
                   5216: 
                   5217:   while($string !~ /^__END_HASH_REF__/) {
                   5218:       #key
                   5219:       my $key='';
                   5220:       if($string =~ /^__HASH_REF__/) {
                   5221:           ($key, $string)=&str2hashref($string);
                   5222:           if(defined($key->{'error'})) {
                   5223:               $hash{'error'}='Bad data';
                   5224:               return (\%hash, $string);
                   5225:           }
                   5226:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5227:           ($key, $string)=&str2arrayref($string);
                   5228:           if($key->[0] eq 'Array reference error') {
                   5229:               $hash{'error'}='Bad data';
                   5230:               return (\%hash, $string);
                   5231:           }
                   5232:       } else {
                   5233:           $string =~ s/^(.*?)=//;
1.267     albertel 5234: 	  $key=&unescape($1);
1.265     albertel 5235:       }
                   5236:       $string =~ s/^=//;
                   5237: 
                   5238:       #value
                   5239:       my $value='';
                   5240:       if($string =~ /^__HASH_REF__/) {
                   5241:           ($value, $string)=&str2hashref($string);
                   5242:           if(defined($value->{'error'})) {
                   5243:               $hash{'error'}='Bad data';
                   5244:               return (\%hash, $string);
                   5245:           }
                   5246:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5247:           ($value, $string)=&str2arrayref($string);
                   5248:           if($value->[0] eq 'Array reference error') {
                   5249:               $hash{'error'}='Bad data';
                   5250:               return (\%hash, $string);
                   5251:           }
                   5252:       } else {
                   5253: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5254:       }
                   5255:       $string =~ s/^&//;
                   5256: 
                   5257:       $hash{$key}=$value;
1.204     albertel 5258:   }
1.265     albertel 5259: 
                   5260:   $string =~ s/^__END_HASH_REF__//;
                   5261: 
                   5262:   return (\%hash, $string);
1.204     albertel 5263: }
                   5264: 
                   5265: sub str2array {
1.265     albertel 5266:     my ($string)=@_;
                   5267:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5268:     return @$array;
                   5269: }
                   5270: 
                   5271: sub str2arrayref {
1.204     albertel 5272:   my ($string) = @_;
1.265     albertel 5273:   my @array;
                   5274: 
                   5275:   if($string !~ /^__ARRAY_REF__/) {
                   5276:       if (! ($string eq '' || !defined($string))) {
                   5277: 	  $array[0]='Array reference error';
                   5278:       }
                   5279:       return (\@array, $string);
                   5280:   }
                   5281: 
                   5282:   $string =~ s/^__ARRAY_REF__//;
                   5283: 
                   5284:   while($string !~ /^__END_ARRAY_REF__/) {
                   5285:       my $value='';
                   5286:       if($string =~ /^__HASH_REF__/) {
                   5287:           ($value, $string)=&str2hashref($string);
                   5288:           if(defined($value->{'error'})) {
                   5289:               $array[0] ='Array reference error';
                   5290:               return (\@array, $string);
                   5291:           }
                   5292:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5293:           ($value, $string)=&str2arrayref($string);
                   5294:           if($value->[0] eq 'Array reference error') {
                   5295:               $array[0] ='Array reference error';
                   5296:               return (\@array, $string);
                   5297:           }
                   5298:       } else {
                   5299: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5300:       }
                   5301:       $string =~ s/^&//;
                   5302: 
                   5303:       push(@array, $value);
1.191     harris41 5304:   }
1.265     albertel 5305: 
                   5306:   $string =~ s/^__END_ARRAY_REF__//;
                   5307: 
                   5308:   return (\@array, $string);
1.168     albertel 5309: }
                   5310: 
1.167     albertel 5311: # -------------------------------------------------------------------Temp Store
                   5312: 
1.168     albertel 5313: sub tmpreset {
                   5314:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5315:   if (!$symb) {
                   5316:     $symb=&symbread();
1.620     albertel 5317:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5318:   }
                   5319:   $symb=escape($symb);
                   5320: 
1.620     albertel 5321:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5322:   $namespace=~s/\//\_/g;
                   5323:   $namespace=~s/\W//g;
                   5324: 
1.620     albertel 5325:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5326:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5327:   if ($domain eq 'public' && $stuname eq 'public') {
                   5328:       $stuname=$ENV{'REMOTE_ADDR'};
                   5329:   }
1.1117    foxr     5330:   my $path=LONCAPA::tempdir();
1.168     albertel 5331:   my %hash;
                   5332:   if (tie(%hash,'GDBM_File',
                   5333: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5334: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5335:     foreach my $key (keys(%hash)) {
1.180     albertel 5336:       if ($key=~ /:$symb/) {
1.168     albertel 5337: 	delete($hash{$key});
                   5338:       }
                   5339:     }
                   5340:   }
                   5341: }
                   5342: 
1.167     albertel 5343: sub tmpstore {
1.168     albertel 5344:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5345: 
                   5346:   if (!$symb) {
                   5347:     $symb=&symbread();
1.620     albertel 5348:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5349:   }
                   5350:   $symb=escape($symb);
                   5351: 
                   5352:   if (!$namespace) {
                   5353:     # I don't think we would ever want to store this for a course.
                   5354:     # it seems this will only be used if we don't have a course.
1.620     albertel 5355:     #$namespace=$env{'request.course.id'};
1.168     albertel 5356:     #if (!$namespace) {
1.620     albertel 5357:       $namespace=$env{'request.state'};
1.168     albertel 5358:     #}
                   5359:   }
                   5360:   $namespace=~s/\//\_/g;
                   5361:   $namespace=~s/\W//g;
1.620     albertel 5362:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5363:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5364:   if ($domain eq 'public' && $stuname eq 'public') {
                   5365:       $stuname=$ENV{'REMOTE_ADDR'};
                   5366:   }
1.168     albertel 5367:   my $now=time;
                   5368:   my %hash;
1.1117    foxr     5369:   my $path=LONCAPA::tempdir();
1.168     albertel 5370:   if (tie(%hash,'GDBM_File',
                   5371: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5372: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5373:     $hash{"version:$symb"}++;
                   5374:     my $version=$hash{"version:$symb"};
                   5375:     my $allkeys=''; 
                   5376:     foreach my $key (keys(%$storehash)) {
                   5377:       $allkeys.=$key.':';
1.591     albertel 5378:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5379:     }
                   5380:     $hash{"$version:$symb:timestamp"}=$now;
                   5381:     $allkeys.='timestamp';
                   5382:     $hash{"$version:keys:$symb"}=$allkeys;
                   5383:     if (untie(%hash)) {
                   5384:       return 'ok';
                   5385:     } else {
                   5386:       return "error:$!";
                   5387:     }
                   5388:   } else {
                   5389:     return "error:$!";
                   5390:   }
                   5391: }
1.167     albertel 5392: 
1.168     albertel 5393: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5394: 
1.168     albertel 5395: sub tmprestore {
                   5396:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5397: 
1.168     albertel 5398:   if (!$symb) {
                   5399:     $symb=&symbread();
1.620     albertel 5400:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5401:   }
                   5402:   $symb=escape($symb);
                   5403: 
1.620     albertel 5404:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5405: 
1.620     albertel 5406:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5407:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5408:   if ($domain eq 'public' && $stuname eq 'public') {
                   5409:       $stuname=$ENV{'REMOTE_ADDR'};
                   5410:   }
1.168     albertel 5411:   my %returnhash;
                   5412:   $namespace=~s/\//\_/g;
                   5413:   $namespace=~s/\W//g;
                   5414:   my %hash;
1.1117    foxr     5415:   my $path=LONCAPA::tempdir();
1.168     albertel 5416:   if (tie(%hash,'GDBM_File',
                   5417: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5418: 	  &GDBM_READER(),0640)) {
1.168     albertel 5419:     my $version=$hash{"version:$symb"};
                   5420:     $returnhash{'version'}=$version;
                   5421:     my $scope;
                   5422:     for ($scope=1;$scope<=$version;$scope++) {
                   5423:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5424:       my @keys=split(/:/,$vkeys);
                   5425:       my $key;
                   5426:       $returnhash{"$scope:keys"}=$vkeys;
                   5427:       foreach $key (@keys) {
1.591     albertel 5428: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5429: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5430:       }
                   5431:     }
1.168     albertel 5432:     if (!(untie(%hash))) {
                   5433:       return "error:$!";
                   5434:     }
                   5435:   } else {
                   5436:     return "error:$!";
                   5437:   }
                   5438:   return %returnhash;
1.167     albertel 5439: }
                   5440: 
1.9       www      5441: # ----------------------------------------------------------------------- Store
                   5442: 
                   5443: sub store {
1.1172.2.64  raeburn  5444:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5445:     my $home='';
                   5446: 
1.168     albertel 5447:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5448: 
1.213     www      5449:     $symb=&symbclean($symb);
1.122     albertel 5450:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5451: 
1.620     albertel 5452:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5453:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5454: 
                   5455:     &devalidate($symb,$stuname,$domain);
1.109     www      5456: 
                   5457:     $symb=escape($symb);
1.187     www      5458:     if (!$namespace) { 
1.620     albertel 5459:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5460:           return ''; 
                   5461:        } 
                   5462:     }
1.620     albertel 5463:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5464: 
                   5465:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5466:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5467: 
1.12      www      5468:     my $namevalue='';
1.800     albertel 5469:     foreach my $key (keys(%$storehash)) {
                   5470:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5471:     }
1.12      www      5472:     $namevalue=~s/\&$//;
1.187     www      5473:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  5474:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5475: }
                   5476: 
1.47      www      5477: # -------------------------------------------------------------- Critical Store
                   5478: 
                   5479: sub cstore {
1.1172.2.64  raeburn  5480:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5481:     my $home='';
                   5482: 
1.168     albertel 5483:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5484: 
1.213     www      5485:     $symb=&symbclean($symb);
1.122     albertel 5486:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5487: 
1.620     albertel 5488:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5489:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5490: 
                   5491:     &devalidate($symb,$stuname,$domain);
1.109     www      5492: 
                   5493:     $symb=escape($symb);
1.187     www      5494:     if (!$namespace) { 
1.620     albertel 5495:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5496:           return ''; 
                   5497:        } 
                   5498:     }
1.620     albertel 5499:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5500: 
                   5501:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5502:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5503: 
1.47      www      5504:     my $namevalue='';
1.800     albertel 5505:     foreach my $key (keys(%$storehash)) {
                   5506:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5507:     }
1.47      www      5508:     $namevalue=~s/\&$//;
1.187     www      5509:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5510:     return critical
1.1172.2.64  raeburn  5511:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5512: }
                   5513: 
1.9       www      5514: # --------------------------------------------------------------------- Restore
                   5515: 
                   5516: sub restore {
1.124     www      5517:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5518:     my $home='';
                   5519: 
1.168     albertel 5520:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5521: 
1.122     albertel 5522:     if (!$symb) {
1.1172.2.26  raeburn  5523:         return if ($namespace eq 'courserequests');
                   5524:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5525:     } else {
1.1172.2.26  raeburn  5526:         unless ($namespace eq 'courserequests') {
                   5527:             $symb=&escape(&symbclean($symb));
                   5528:         }
1.122     albertel 5529:     }
1.188     www      5530:     if (!$namespace) { 
1.620     albertel 5531:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5532:           return ''; 
                   5533:        } 
                   5534:     }
1.620     albertel 5535:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5536:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5537:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5538:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5539: 
1.12      www      5540:     my %returnhash=();
1.800     albertel 5541:     foreach my $line (split(/\&/,$answer)) {
                   5542: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5543:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5544:     }
1.75      www      5545:     my $version;
                   5546:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5547:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5548:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5549:        }
1.75      www      5550:     }
1.13      www      5551:     return %returnhash;
1.34      www      5552: }
                   5553: 
                   5554: # ---------------------------------------------------------- Course Description
1.1118    foxr     5555: #
                   5556: #  
1.34      www      5557: 
                   5558: sub coursedescription {
1.731     albertel 5559:     my ($courseid,$args)=@_;
1.34      www      5560:     $courseid=~s/^\///;
1.49      www      5561:     $courseid=~s/\_/\//g;
1.34      www      5562:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5563:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5564:     my $normalid=$cdomain.'_'.$cnum;
                   5565:     # need to always cache even if we get errors otherwise we keep 
                   5566:     # trying and trying and trying to get the course description.
                   5567:     my %envhash=();
                   5568:     my %returnhash=();
1.731     albertel 5569:     
                   5570:     my $expiretime=600;
                   5571:     if ($env{'request.course.id'} eq $normalid) {
                   5572: 	$expiretime=120;
                   5573:     }
                   5574: 
                   5575:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5576:     if (!$args->{'freshen_cache'}
                   5577: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5578: 	foreach my $key (keys(%env)) {
                   5579: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5580: 	    my ($setting) = $1;
                   5581: 	    $returnhash{$setting} = $env{$key};
                   5582: 	}
                   5583: 	return %returnhash;
                   5584:     }
                   5585: 
1.1118    foxr     5586:     # get the data again
                   5587: 
1.731     albertel 5588:     if (!$args->{'one_time'}) {
                   5589: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5590:     }
1.811     albertel 5591: 
1.34      www      5592:     if ($chome ne 'no_host') {
1.302     albertel 5593:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5594:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5595: 	   my $username = $env{'user.name'}; # Defult username
                   5596: 	   if(defined $args->{'user'}) {
                   5597: 	       $username = $args->{'user'};
                   5598: 	   }
1.129     albertel 5599:            $returnhash{'home'}= $chome;
                   5600: 	   $returnhash{'domain'} = $cdomain;
                   5601: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5602:            if (!defined($returnhash{'type'})) {
                   5603:                $returnhash{'type'} = 'Course';
                   5604:            }
1.130     albertel 5605:            while (my ($name,$value) = each %returnhash) {
1.53      www      5606:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5607:            }
1.270     www      5608:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5609:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5610: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5611:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5612:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5613:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5614:        }
                   5615:     }
1.731     albertel 5616:     if (!$args->{'one_time'}) {
1.949     raeburn  5617: 	&appenv(\%envhash);
1.731     albertel 5618:     }
1.302     albertel 5619:     return %returnhash;
1.461     www      5620: }
                   5621: 
1.1080    raeburn  5622: sub update_released_required {
                   5623:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5624:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5625:         $cid = $env{'request.course.id'};
                   5626:         $cdom = $env{'course.'.$cid.'.domain'};
                   5627:         $cnum = $env{'course.'.$cid.'.num'};
                   5628:         $chome = $env{'course.'.$cid.'.home'};
                   5629:     }
                   5630:     if ($needsrelease) {
                   5631:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5632:         my $needsupdate;
                   5633:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5634:             $needsupdate = 1;
                   5635:         } else {
                   5636:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5637:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5638:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5639:                 $needsupdate = 1;
                   5640:             }
                   5641:         }
                   5642:         if ($needsupdate) {
                   5643:             my %needshash = (
                   5644:                              'internal.releaserequired' => $needsrelease,
                   5645:                             );
                   5646:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5647:             if ($putresult eq 'ok') {
                   5648:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5649:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5650:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5651:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5652:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5653:                 }
                   5654:             }
                   5655:         }
                   5656:     }
                   5657:     return;
                   5658: }
                   5659: 
1.461     www      5660: # -------------------------------------------------See if a user is privileged
                   5661: 
                   5662: sub privileged {
1.1172.2.23  raeburn  5663:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5664:     my $now = time;
1.1172.2.23  raeburn  5665:     my $roles;
                   5666:     if (ref($possroles) eq 'ARRAY') {
                   5667:         $roles = $possroles;
                   5668:     } else {
                   5669:         $roles = ['dc','su'];
                   5670:     }
                   5671:     if (ref($possdomains) eq 'ARRAY') {
                   5672:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5673:         foreach my $dom (@{$possdomains}) {
                   5674:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5675:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5676:                 foreach my $role (@{$roles}) {
                   5677:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5678:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5679:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5680:                             return 1 unless (($end && $end < $now) ||
                   5681:                                              ($start && $start > $now));
                   5682:                         }
                   5683:                     }
                   5684:                 }
                   5685:             }
                   5686:         }
                   5687:     } else {
                   5688:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5689:         my $now = time;
1.1170    droeschl 5690: 
1.1172.2.58  raeburn  5691:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5692:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  5693:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   5694:                 return 1 unless ($tend && $tend < $now)
                   5695:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5696:             }
1.1172.2.23  raeburn  5697:         }
                   5698:     }
1.461     www      5699:     return 0;
1.9       www      5700: }
1.1       albertel 5701: 
1.1172.2.23  raeburn  5702: sub privileged_by_domain {
                   5703:     my ($domains,$roles) = @_;
                   5704:     my %privileged = ();
                   5705:     my $cachetime = 60*60*24;
                   5706:     my $now = time;
                   5707:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5708:         return %privileged;
                   5709:     }
                   5710:     foreach my $dom (@{$domains}) {
                   5711:         next if (ref($privileged{$dom}) eq 'HASH');
                   5712:         my $needroles;
                   5713:         foreach my $role (@{$roles}) {
                   5714:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5715:             if (defined($cached)) {
                   5716:                 if (ref($result) eq 'HASH') {
                   5717:                     $privileged{$dom}{$role} = $result;
                   5718:                 }
                   5719:             } else {
                   5720:                 $needroles = 1;
                   5721:             }
                   5722:         }
                   5723:         if ($needroles) {
                   5724:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5725:             $privileged{$dom} = {};
                   5726:             foreach my $server (keys(%dompersonnel)) {
                   5727:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5728:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5729:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5730:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5731:                         next if ($end && $end < $now);
                   5732:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   5733:                             $dompersonnel{$server}{$item};
                   5734:                     }
                   5735:                 }
                   5736:             }
                   5737:             if (ref($privileged{$dom}) eq 'HASH') {
                   5738:                 foreach my $role (@{$roles}) {
                   5739:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5740:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5741:                     } else {
                   5742:                         my %hash = ();
                   5743:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5744:                     }
                   5745:                 }
                   5746:             }
                   5747:         }
                   5748:     }
                   5749:     return %privileged;
                   5750: }
                   5751: 
1.103     harris41 5752: # -------------------------------------------------------- Get user privileges
1.11      www      5753: 
                   5754: sub rolesinit {
1.1169    droeschl 5755:     my ($domain, $username) = @_;
                   5756:     my %userroles = ('user.login.time' => time);
                   5757:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5758: 
                   5759:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5760:     # also, blocking can be triggered by an activating timer
                   5761:     # it's saved in the user's %env.
                   5762:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5763:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5764:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5765:         %timerintchk, %timerintenv);
                   5766: 
1.1162    raeburn  5767:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5768:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5769:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5770:     }
1.1169    droeschl 5771: 
1.1162    raeburn  5772:     foreach my $key (keys(%timerinterval)) {
                   5773:         my ($cid,$rest) = split(/\0/,$key);
                   5774:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5775:     }
1.1169    droeschl 5776: 
1.11      www      5777:     my %allroles=();
1.1162    raeburn  5778:     my %allgroups=();
1.11      www      5779: 
1.1172.2.58  raeburn  5780:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5781:         my $role = $rolesdump{$area};
                   5782:         $area =~ s/\_\w\w$//;
                   5783: 
                   5784:         my ($trole, $tend, $tstart, $group_privs);
                   5785: 
                   5786:         if ($role =~ /^cr/) {
                   5787:         # Custom role, defined by a user 
                   5788:         # e.g., user.role.cr/msu/smith/mynewrole
                   5789:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5790:                 $trole = $1;
                   5791:                 ($tend, $tstart) = split('_', $2);
                   5792:             } else {
                   5793:                 $trole = $role;
                   5794:             }
                   5795:         } elsif ($role =~ m|^gr/|) {
                   5796:         # Role of member in a group, defined within a course/community
                   5797:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5798:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5799:             next if $tstart eq '-1';
                   5800:             ($trole, $group_privs) = split(/\//, $trole);
                   5801:             $group_privs = &unescape($group_privs);
                   5802:         } else {
                   5803:         # Just a normal role, defined in roles.tab
                   5804:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5805:         }
                   5806: 
                   5807:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5808:                  $username);
                   5809:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5810: 
                   5811:         # role expired or not available yet?
                   5812:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5813:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5814: 
                   5815:         next if $area eq '' or $trole eq '';
                   5816: 
                   5817:         my $spec = "$trole.$area";
                   5818:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5819: 
                   5820:         if ($trole =~ /^cr\//) {
                   5821:         # Custom role, defined by a user
                   5822:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5823:         } elsif ($trole eq 'gr') {
                   5824:         # Role of a member in a group, defined within a course/community
                   5825:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5826:             next;
                   5827:         } else {
                   5828:         # Normal role, defined in roles.tab
                   5829:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5830:         }
                   5831: 
                   5832:         my $cid = $tdomain.'_'.$trest;
                   5833:         unless ($firstaccchk{$cid}) {
                   5834:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5835:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5836:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5837:                         $coursetimerstarts{$cid}{$item}; 
                   5838:                 }
                   5839:             }
                   5840:             $firstaccchk{$cid} = 1;
                   5841:         }
                   5842:         unless ($timerintchk{$cid}) {
                   5843:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5844:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5845:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5846:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5847:                 }
1.12      www      5848:             }
1.1169    droeschl 5849:             $timerintchk{$cid} = 1;
1.191     harris41 5850:         }
1.11      www      5851:     }
1.1169    droeschl 5852: 
1.1172.2.91  raeburn  5853:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   5854:                                                           \%allroles, \%allgroups);
1.1169    droeschl 5855:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  5856:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 5857: 
1.1162    raeburn  5858:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5859: }
                   5860: 
1.567     raeburn  5861: sub set_arearole {
1.1172.2.19  raeburn  5862:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5863:     unless ($nolog) {
1.567     raeburn  5864: # log the associated role with the area
1.1172.2.19  raeburn  5865:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5866:     }
1.743     albertel 5867:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5868: }
                   5869: 
                   5870: sub custom_roleprivs {
                   5871:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5872:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  5873:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5874:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5875:         my ($rdummy,$roledef)=
                   5876:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5877:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5878:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5879:             if (defined($syspriv)) {
1.1043    raeburn  5880:                 if ($trest =~ /^$match_community$/) {
                   5881:                     $syspriv =~ s/bre\&S//; 
                   5882:                 }
1.567     raeburn  5883:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5884:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5885:             }
                   5886:             if ($tdomain ne '') {
                   5887:                 if (defined($dompriv)) {
                   5888:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5889:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5890:                 }
                   5891:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  5892:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   5893:                         my $rolename = $1;
                   5894:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   5895:                     }
1.567     raeburn  5896:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5897:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5898:                 }
                   5899:             }
                   5900:         }
                   5901:     }
                   5902: }
                   5903: 
1.1172.2.89  raeburn  5904: sub course_adhocrole_privs {
                   5905:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   5906:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   5907:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   5908:         my (%currprivs,%storeprivs);
                   5909:         foreach my $item (split(/:/,$coursepriv)) {
                   5910:             my ($priv,$restrict) = split(/\&/,$item);
                   5911:             $currprivs{$priv} = $restrict;
                   5912:         }
                   5913:         my (%possadd,%possremove,%full);
                   5914:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   5915:             my ($priv,$restrict)=split(/\&/,$item);
                   5916:             $full{$priv} = $restrict;
                   5917:         }
                   5918:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   5919:              next if ($item eq '');
                   5920:              my ($rule,$rest) = split(/=/,$item);
                   5921:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   5922:              foreach my $priv (split(/:/,$rest)) {
                   5923:                  if ($priv ne '') {
                   5924:                      if ($rule eq 'off') {
                   5925:                          $possremove{$priv} = 1;
                   5926:                      } else {
                   5927:                          $possadd{$priv} = 1;
                   5928:                      }
                   5929:                  }
                   5930:              }
                   5931:          }
                   5932:          foreach my $priv (sort(keys(%full))) {
                   5933:              if (exists($currprivs{$priv})) {
                   5934:                  unless (exists($possremove{$priv})) {
                   5935:                      $storeprivs{$priv} = $currprivs{$priv};
                   5936:                  }
                   5937:              } elsif (exists($possadd{$priv})) {
                   5938:                  $storeprivs{$priv} = $full{$priv};
                   5939:              }
                   5940:          }
                   5941:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   5942:      }
                   5943:      return $coursepriv;
                   5944: }
                   5945: 
1.678     raeburn  5946: sub group_roleprivs {
                   5947:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5948:     my $access = 1;
                   5949:     my $now = time;
                   5950:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5951:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5952:     if ($access) {
1.811     albertel 5953:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5954:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5955:     }
                   5956: }
1.567     raeburn  5957: 
                   5958: sub standard_roleprivs {
                   5959:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5960:     if (defined($pr{$trole.':s'})) {
                   5961:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5962:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5963:     }
                   5964:     if ($tdomain ne '') {
                   5965:         if (defined($pr{$trole.':d'})) {
                   5966:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5967:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5968:         }
                   5969:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5970:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5971:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5972:         }
                   5973:     }
                   5974: }
                   5975: 
                   5976: sub set_userprivs {
1.1064    raeburn  5977:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5978:     my $author=0;
                   5979:     my $adv=0;
1.1172.2.91  raeburn  5980:     my $rar=0;
1.678     raeburn  5981:     my %grouproles = ();
                   5982:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5983:         my @groupkeys; 
1.1000    raeburn  5984:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5985:             push(@groupkeys,$role);
                   5986:         }
                   5987:         if (ref($groups_roles) eq 'HASH') {
                   5988:             foreach my $key (keys(%{$groups_roles})) {
                   5989:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5990:                     push(@groupkeys,$key);
                   5991:                 }
                   5992:             }
                   5993:         }
                   5994:         if (@groupkeys > 0) {
                   5995:             foreach my $role (@groupkeys) {
                   5996:                 my ($trole,$area,$sec,$extendedarea);
                   5997:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5998:                     $trole = $1;
                   5999:                     $area = $2;
                   6000:                     $sec = $3;
                   6001:                     $extendedarea = $area.$sec;
                   6002:                     if (exists($$allgroups{$area})) {
                   6003:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6004:                             my $spec = $trole.'.'.$extendedarea;
                   6005:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6006:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6007:                         }
1.678     raeburn  6008:                     }
                   6009:                 }
                   6010:             }
                   6011:         }
                   6012:     }
1.800     albertel 6013:     foreach my $group (keys(%grouproles)) {
                   6014:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6015:     }
1.800     albertel 6016:     foreach my $role (keys(%{$allroles})) {
                   6017:         my %thesepriv;
1.941     raeburn  6018:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6019:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6020:             if ($item ne '') {
                   6021:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6022:                 if ($restrictions eq '') {
                   6023:                     $thesepriv{$privilege}='F';
                   6024:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6025:                     $thesepriv{$privilege}.=$restrictions;
                   6026:                 }
                   6027:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  6028:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6029:             }
                   6030:         }
                   6031:         my $thesestr='';
1.1104    raeburn  6032:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6033: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6034: 	}
                   6035:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6036:     }
1.1172.2.91  raeburn  6037:     return ($author,$adv,$rar);
1.567     raeburn  6038: }
                   6039: 
1.994     raeburn  6040: sub role_status {
1.1104    raeburn  6041:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6042:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  6043:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6044:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6045:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  6046:             $$where = '/'.$two;
1.994     raeburn  6047:             $$trolecode=$$role.'.'.$$where;
                   6048:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6049:             $$tstatus='is';
1.1104    raeburn  6050:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6051:                 $$tstatus='future';
1.1034    raeburn  6052:                 if ($$tstart<$now) {
                   6053:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6054:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6055:                             my (%allroles,%allgroups,$group_privs,
                   6056:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6057:                             my %userroles = (
                   6058:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6059:                             );
1.1064    raeburn  6060:                             @rolecodes = ('cm'); 
1.1002    raeburn  6061:                             my $spec=$$role.'.'.$$where;
                   6062:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6063:                             if ($$role =~ /^cr\//) {
                   6064:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6065:                                 push(@rolecodes,'cr');
1.1002    raeburn  6066:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6067:                                 push(@rolecodes,$$role);
1.1002    raeburn  6068:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6069:                                                     $env{'user.name'});
1.1064    raeburn  6070:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6071:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6072:                                 $group_privs = &unescape($group_privs);
                   6073:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6074:                                 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  6075:                                 &get_groups_roles($tdomain,$trest,
                   6076:                                                   \%course_roles,\@rolecodes,
                   6077:                                                   \%groups_roles);
1.1002    raeburn  6078:                             } else {
1.1064    raeburn  6079:                                 push(@rolecodes,$$role);
1.1002    raeburn  6080:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6081:                             }
1.1172.2.91  raeburn  6082:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6083:                                                                    \%groups_roles);
1.1064    raeburn  6084:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  6085:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6086:                         }
                   6087:                     }
1.1034    raeburn  6088:                     $$tstatus = 'is';
1.1002    raeburn  6089:                 }
1.994     raeburn  6090:             }
                   6091:             if ($$tend) {
1.1104    raeburn  6092:                 if ($$tend<$update) {
1.994     raeburn  6093:                     $$tstatus='expired';
                   6094:                 } elsif ($$tend<$now) {
                   6095:                     $$tstatus='will_not';
                   6096:                 }
                   6097:             }
                   6098:         }
                   6099:     }
                   6100: }
                   6101: 
1.1104    raeburn  6102: sub get_groups_roles {
                   6103:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6104:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6105:                   (ref($rolecodes) eq 'ARRAY') && 
                   6106:                   (ref($groups_roles) eq 'HASH')); 
                   6107:     if (keys(%{$cdom_courseroles}) > 0) {
                   6108:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6109:         if ($cdom ne '' && $cnum ne '') {
                   6110:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6111:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6112:                     my $crsrole = $1;
                   6113:                     my $crssec = $2;
                   6114:                     if ($crsrole =~ /^cr/) {
                   6115:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6116:                             push(@{$rolecodes},'cr');
                   6117:                         }
                   6118:                     } else {
                   6119:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6120:                             push(@{$rolecodes},$crsrole);
                   6121:                         }
                   6122:                     }
                   6123:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6124:                     if ($crssec ne '') {
                   6125:                         $rolekey .= "/$crssec";
                   6126:                     }
                   6127:                     $rolekey .= './';
                   6128:                     $groups_roles->{$rolekey} = $rolecodes;
                   6129:                 }
                   6130:             }
                   6131:         }
                   6132:     }
                   6133:     return;
                   6134: }
                   6135: 
                   6136: sub delete_env_groupprivs {
                   6137:     my ($where,$courseroles,$possroles) = @_;
                   6138:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6139:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6140:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6141:         %{$courseroles->{$udom}} =
                   6142:             &get_my_roles('','','userroles',['active'],
                   6143:                           $possroles,[$udom],1);
                   6144:     }
                   6145:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6146:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6147:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6148:             my $area = '/'.$cdom.'/'.$cnum;
                   6149:             my $privkey = "user.priv.$crsrole.$area";
                   6150:             if ($crssec ne '') {
                   6151:                 $privkey .= '/'.$crssec;
                   6152:             }
                   6153:             $privkey .= ".$area/$group";
                   6154:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6155:         }
                   6156:     }
                   6157:     return;
                   6158: }
                   6159: 
1.994     raeburn  6160: sub check_adhoc_privs {
1.1172.2.86  raeburn  6161:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6162:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6163:     if ($sec) {
                   6164:         $cckey .= '/'.$sec;
                   6165:     }
1.1172.2.9  raeburn  6166:     my $setprivs;
1.994     raeburn  6167:     if ($env{$cckey}) {
                   6168:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6169:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6170:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6171:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6172:             $setprivs = 1;
1.994     raeburn  6173:         }
                   6174:     } else {
1.1172.2.87  raeburn  6175:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6176:         $setprivs = 1;
1.994     raeburn  6177:     }
1.1172.2.9  raeburn  6178:     return $setprivs;
1.994     raeburn  6179: }
                   6180: 
                   6181: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6182: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6183:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6184:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6185:     if ($sec ne '') {
                   6186:         $area .= '/'.$sec;
                   6187:     }
1.994     raeburn  6188:     my $spec = $role.'.'.$area;
                   6189:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6190:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6191:     my %rolehash = ();
1.1172.2.89  raeburn  6192:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6193:         my $rolename = $1;
1.1172.2.84  raeburn  6194:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6195:         my %domdef = &get_domain_defaults($dcdom);
                   6196:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6197:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6198:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6199:             }
                   6200:         }
1.1172.2.84  raeburn  6201:     } else {
                   6202:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6203:     }
1.1172.2.91  raeburn  6204:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6205:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6206:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6207:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6208:         &appenv( {'request.role'        => $spec,
                   6209:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6210:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6211:                  }
                   6212:                );
                   6213:         my $tadv=0;
                   6214:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6215:         &appenv({'request.role.adv'    => $tadv});
                   6216:     }
1.994     raeburn  6217: }
                   6218: 
1.12      www      6219: # --------------------------------------------------------------- get interface
                   6220: 
                   6221: sub get {
1.131     albertel 6222:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6223:    my $items='';
1.800     albertel 6224:    foreach my $item (@$storearr) {
                   6225:        $items.=&escape($item).'&';
1.191     harris41 6226:    }
1.12      www      6227:    $items=~s/\&$//;
1.620     albertel 6228:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6229:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6230:    my $uhome=&homeserver($uname,$udomain);
                   6231: 
1.133     albertel 6232:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6233:    my @pairs=split(/\&/,$rep);
1.273     albertel 6234:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6235:      return @pairs;
                   6236:    }
1.15      www      6237:    my %returnhash=();
1.42      www      6238:    my $i=0;
1.800     albertel 6239:    foreach my $item (@$storearr) {
                   6240:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6241:       $i++;
1.191     harris41 6242:    }
1.15      www      6243:    return %returnhash;
1.27      www      6244: }
                   6245: 
                   6246: # --------------------------------------------------------------- del interface
                   6247: 
                   6248: sub del {
1.133     albertel 6249:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6250:    my $items='';
1.800     albertel 6251:    foreach my $item (@$storearr) {
                   6252:        $items.=&escape($item).'&';
1.191     harris41 6253:    }
1.984     neumanie 6254: 
1.27      www      6255:    $items=~s/\&$//;
1.620     albertel 6256:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6257:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6258:    my $uhome=&homeserver($uname,$udomain);
                   6259:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6260: }
                   6261: 
                   6262: # -------------------------------------------------------------- dump interface
                   6263: 
1.1172.2.22  raeburn  6264: sub unserialize {
                   6265:     my ($rep, $escapedkeys) = @_;
                   6266: 
                   6267:     return {} if $rep =~ /^error/;
                   6268: 
                   6269:     my %returnhash=();
                   6270:     foreach my $item (split(/\&/,$rep)) {
                   6271:         my ($key, $value) = split(/=/, $item, 2);
                   6272:         $key = unescape($key) unless $escapedkeys;
                   6273:         next if $key =~ /^error: 2 /;
                   6274:         $returnhash{$key} = &thaw_unescape($value);
                   6275:     }
                   6276:     return \%returnhash;
                   6277: }
                   6278: 
                   6279: # see Lond::dump_with_regexp
                   6280: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6281: sub dump {
1.1172.2.22  raeburn  6282:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6283:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6284:     if (!$uname) { $uname=$env{'user.name'}; }
                   6285:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6286: 
1.1172.2.55  raeburn  6287:     if ($regexp) {
                   6288:         $regexp=&escape($regexp);
                   6289:     } else {
                   6290:         $regexp='.';
                   6291:     }
1.1172.2.22  raeburn  6292:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   6293:         # user is hosted on this machine
1.1172.2.55  raeburn  6294:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  6295:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  6296:         return %{&unserialize($reply, $escapedkeys)};
                   6297:     }
1.1166    raeburn  6298:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6299:     my @pairs=split(/\&/,$rep);
                   6300:     my %returnhash=();
1.1098    foxr     6301:     if (!($rep =~ /^error/ )) {
                   6302: 	foreach my $item (@pairs) {
                   6303: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  6304:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     6305: 	    next if ($key =~ /^error: 2 /);
                   6306: 	    $returnhash{$key}=&thaw_unescape($value);
                   6307: 	}
1.755     albertel 6308:     }
                   6309:     return %returnhash;
1.407     www      6310: }
                   6311: 
1.1098    foxr     6312: 
1.717     albertel 6313: # --------------------------------------------------------- dumpstore interface
                   6314: 
                   6315: sub dumpstore {
                   6316:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  6317:    # same as dump but keys must be escaped. They may contain colon separated
                   6318:    # lists of values that may themself contain colons (e.g. symbs).
                   6319:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6320: }
                   6321: 
1.407     www      6322: # -------------------------------------------------------------- keys interface
                   6323: 
                   6324: sub getkeys {
                   6325:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6326:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6327:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6328:    my $uhome=&homeserver($uname,$udomain);
                   6329:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6330:    my @keyarray=();
1.800     albertel 6331:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6332:       next if ($key =~ /^error: 2 /);
1.800     albertel 6333:       push(@keyarray,&unescape($key));
1.407     www      6334:    }
                   6335:    return @keyarray;
1.318     matthew  6336: }
                   6337: 
1.319     matthew  6338: # --------------------------------------------------------------- currentdump
                   6339: sub currentdump {
1.328     matthew  6340:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6341:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6342:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6343:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6344:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  6345:    my $rep;
                   6346: 
                   6347:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6348:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   6349:                    $courseid)));
                   6350:    } else {
                   6351:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6352:    }
                   6353: 
1.318     matthew  6354:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6355:    #
1.318     matthew  6356:    my %returnhash=();
1.319     matthew  6357:    #
                   6358:    if ($rep eq "unknown_cmd") { 
                   6359:        # an old lond will not know currentdump
                   6360:        # Do a dump and make it look like a currentdump
1.822     albertel 6361:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6362:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6363:        my %hash = @tmp;
                   6364:        @tmp=();
1.424     matthew  6365:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6366:    } else {
                   6367:        my @pairs=split(/\&/,$rep);
1.800     albertel 6368:        foreach my $pair (@pairs) {
                   6369:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6370:            my ($symb,$param) = split(/:/,$key);
                   6371:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6372:                                                         &thaw_unescape($value);
1.319     matthew  6373:        }
1.191     harris41 6374:    }
1.12      www      6375:    return %returnhash;
1.424     matthew  6376: }
                   6377: 
                   6378: sub convert_dump_to_currentdump{
                   6379:     my %hash = %{shift()};
                   6380:     my %returnhash;
                   6381:     # Code ripped from lond, essentially.  The only difference
                   6382:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6383:     # we might run in to problems with parameter names =~ /^v\./
                   6384:     while (my ($key,$value) = each(%hash)) {
                   6385:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6386: 	$symb  = &unescape($symb);
                   6387: 	$param = &unescape($param);
1.424     matthew  6388:         next if ($v eq 'version' || $symb eq 'keys');
                   6389:         next if (exists($returnhash{$symb}) &&
                   6390:                  exists($returnhash{$symb}->{$param}) &&
                   6391:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6392:         $returnhash{$symb}->{$param}=$value;
                   6393:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6394:     }
                   6395:     #
                   6396:     # Remove all of the keys in the hashes which keep track of
                   6397:     # the version of the parameter.
                   6398:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6399:         # use a foreach because we are going to delete from the hash.
                   6400:         foreach my $key (keys(%$param_hash)) {
                   6401:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6402:         }
                   6403:     }
                   6404:     return \%returnhash;
1.12      www      6405: }
                   6406: 
1.627     albertel 6407: # ------------------------------------------------------ critical inc interface
                   6408: 
                   6409: sub cinc {
                   6410:     return &inc(@_,'critical');
                   6411: }
                   6412: 
1.449     matthew  6413: # --------------------------------------------------------------- inc interface
                   6414: 
                   6415: sub inc {
1.627     albertel 6416:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6417:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6418:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6419:     my $uhome=&homeserver($uname,$udomain);
                   6420:     my $items='';
                   6421:     if (! ref($store)) {
                   6422:         # got a single value, so use that instead
                   6423:         $items = &escape($store).'=&';
                   6424:     } elsif (ref($store) eq 'SCALAR') {
                   6425:         $items = &escape($$store).'=&';        
                   6426:     } elsif (ref($store) eq 'ARRAY') {
                   6427:         $items = join('=&',map {&escape($_);} @{$store});
                   6428:     } elsif (ref($store) eq 'HASH') {
                   6429:         while (my($key,$value) = each(%{$store})) {
                   6430:             $items.= &escape($key).'='.&escape($value).'&';
                   6431:         }
                   6432:     }
                   6433:     $items=~s/\&$//;
1.627     albertel 6434:     if ($critical) {
                   6435: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6436:     } else {
                   6437: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6438:     }
1.449     matthew  6439: }
                   6440: 
1.12      www      6441: # --------------------------------------------------------------- put interface
                   6442: 
                   6443: sub put {
1.134     albertel 6444:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6445:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6446:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6447:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6448:    my $items='';
1.800     albertel 6449:    foreach my $item (keys(%$storehash)) {
                   6450:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6451:    }
1.12      www      6452:    $items=~s/\&$//;
1.134     albertel 6453:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6454: }
                   6455: 
1.631     albertel 6456: # ------------------------------------------------------------ newput interface
                   6457: 
                   6458: sub newput {
                   6459:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6460:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6461:    if (!$uname) { $uname=$env{'user.name'}; }
                   6462:    my $uhome=&homeserver($uname,$udomain);
                   6463:    my $items='';
                   6464:    foreach my $key (keys(%$storehash)) {
                   6465:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6466:    }
                   6467:    $items=~s/\&$//;
                   6468:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6469: }
                   6470: 
                   6471: # ---------------------------------------------------------  putstore interface
                   6472: 
1.524     raeburn  6473: sub putstore {
1.1172.2.59  raeburn  6474:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6475:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6476:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6477:    my $uhome=&homeserver($uname,$udomain);
                   6478:    my $items='';
1.715     albertel 6479:    foreach my $key (keys(%$storehash)) {
                   6480:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6481:    }
1.715     albertel 6482:    $items=~s/\&$//;
1.716     albertel 6483:    my $esc_symb=&escape($symb);
                   6484:    my $esc_v=&escape($version);
1.715     albertel 6485:    my $reply =
1.716     albertel 6486:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6487: 	      $uhome);
1.1172.2.59  raeburn  6488:    if (($tolog) && ($reply eq 'ok')) {
                   6489:        my $namevalue='';
                   6490:        foreach my $key (keys(%{$storehash})) {
                   6491:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6492:        }
                   6493:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6494:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6495:                      '&version='.$esc_v.
                   6496:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6497:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6498:    }
1.715     albertel 6499:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6500:        # gfall back to way things use to be done
1.715     albertel 6501:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6502: 			    $uname);
1.524     raeburn  6503:    }
1.715     albertel 6504:    return $reply;
                   6505: }
                   6506: 
                   6507: sub old_putstore {
1.716     albertel 6508:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6509:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6510:     if (!$uname) { $uname=$env{'user.name'}; }
                   6511:     my $uhome=&homeserver($uname,$udomain);
                   6512:     my %newstorehash;
1.800     albertel 6513:     foreach my $item (keys(%$storehash)) {
                   6514: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6515: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6516:     }
                   6517:     my $items='';
                   6518:     my %allitems = ();
1.800     albertel 6519:     foreach my $item (keys(%newstorehash)) {
                   6520: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6521: 	    my $key = $1.':keys:'.$2;
                   6522: 	    $allitems{$key} .= $3.':';
                   6523: 	}
1.800     albertel 6524: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6525:     }
1.800     albertel 6526:     foreach my $item (keys(%allitems)) {
                   6527: 	$allitems{$item} =~ s/\:$//;
                   6528: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6529:     }
                   6530:     $items=~s/\&$//;
                   6531:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6532: }
                   6533: 
1.47      www      6534: # ------------------------------------------------------ critical put interface
                   6535: 
                   6536: sub cput {
1.134     albertel 6537:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6538:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6539:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6540:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6541:    my $items='';
1.800     albertel 6542:    foreach my $item (keys(%$storehash)) {
                   6543:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6544:    }
1.47      www      6545:    $items=~s/\&$//;
1.134     albertel 6546:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6547: }
                   6548: 
                   6549: # -------------------------------------------------------------- eget interface
                   6550: 
                   6551: sub eget {
1.133     albertel 6552:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6553:    my $items='';
1.800     albertel 6554:    foreach my $item (@$storearr) {
                   6555:        $items.=&escape($item).'&';
1.191     harris41 6556:    }
1.12      www      6557:    $items=~s/\&$//;
1.620     albertel 6558:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6559:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6560:    my $uhome=&homeserver($uname,$udomain);
                   6561:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6562:    my @pairs=split(/\&/,$rep);
                   6563:    my %returnhash=();
1.42      www      6564:    my $i=0;
1.800     albertel 6565:    foreach my $item (@$storearr) {
                   6566:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6567:       $i++;
1.191     harris41 6568:    }
1.12      www      6569:    return %returnhash;
                   6570: }
                   6571: 
1.667     albertel 6572: # ------------------------------------------------------------ tmpput interface
                   6573: sub tmpput {
1.802     raeburn  6574:     my ($storehash,$server,$context)=@_;
1.667     albertel 6575:     my $items='';
1.800     albertel 6576:     foreach my $item (keys(%$storehash)) {
                   6577: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6578:     }
                   6579:     $items=~s/\&$//;
1.802     raeburn  6580:     if (defined($context)) {
                   6581:         $items .= ':'.&escape($context);
                   6582:     }
1.667     albertel 6583:     return &reply("tmpput:$items",$server);
                   6584: }
                   6585: 
                   6586: # ------------------------------------------------------------ tmpget interface
                   6587: sub tmpget {
1.688     albertel 6588:     my ($token,$server)=@_;
                   6589:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6590:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6591:     my %returnhash;
1.1172.2.85  raeburn  6592:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   6593:         return %returnhash;
                   6594:     }
1.667     albertel 6595:     foreach my $item (split(/\&/,$rep)) {
                   6596: 	my ($key,$value)=split(/=/,$item);
                   6597: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6598:     }
                   6599:     return %returnhash;
                   6600: }
                   6601: 
1.1113    raeburn  6602: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6603: sub tmpdel {
                   6604:     my ($token,$server)=@_;
                   6605:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6606:     return &reply("tmpdel:$token",$server);
                   6607: }
                   6608: 
1.1172.2.13  raeburn  6609: # ------------------------------------------------------------ get_timebased_id
                   6610: 
                   6611: sub get_timebased_id {
                   6612:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6613:         $maxtries) = @_;
                   6614:     my ($newid,$error,$dellock);
                   6615:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   6616:         return ('','ok','invalid call to get suffix');
                   6617:     }
                   6618: 
                   6619: # set defaults for any optional args for which values were not supplied
                   6620:     if ($who eq '') {
                   6621:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6622:     }
                   6623:     if (!$locktries) {
                   6624:         $locktries = 3;
                   6625:     }
                   6626:     if (!$maxtries) {
                   6627:         $maxtries = 10;
                   6628:     }
                   6629: 
                   6630:     if (($cdom eq '') || ($cnum eq '')) {
                   6631:         if ($env{'request.course.id'}) {
                   6632:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6633:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6634:         }
                   6635:         if (($cdom eq '') || ($cnum eq '')) {
                   6636:             return ('','ok','call to get suffix not in course context');
                   6637:         }
                   6638:     }
                   6639: 
                   6640: # construct locking item
                   6641:     my $lockhash = {
                   6642:                       $prefix."\0".'locked_'.$keyid => $who,
                   6643:                    };
                   6644:     my $tries = 0;
                   6645: 
                   6646: # attempt to get lock on nohist_$namespace file
                   6647:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6648:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6649:         $tries ++;
                   6650:         sleep 1;
                   6651:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6652:     }
                   6653: 
                   6654: # attempt to get unique identifier, based on current timestamp
                   6655:     if ($gotlock eq 'ok') {
                   6656:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6657:         my $id = time;
                   6658:         $newid = $id;
1.1172.2.56  raeburn  6659:         if ($idtype eq 'addcode') {
                   6660:             $newid .= &sixnum_code();
                   6661:         }
1.1172.2.13  raeburn  6662:         my $idtries = 0;
                   6663:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6664:             if ($idtype eq 'concat') {
                   6665:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  6666:             } elsif ($idtype eq 'addcode') {
                   6667:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  6668:             } else {
                   6669:                 $newid ++;
                   6670:             }
                   6671:             $idtries ++;
                   6672:         }
                   6673:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6674:             my %new_item =  (
                   6675:                               $prefix."\0".$newid => $who,
                   6676:                             );
                   6677:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6678:                                                  $cdom,$cnum);
                   6679:             if ($putresult ne 'ok') {
                   6680:                 undef($newid);
                   6681:                 $error = 'error saving new item: '.$putresult;
                   6682:             }
                   6683:         } else {
1.1172.2.56  raeburn  6684:              undef($newid);
1.1172.2.13  raeburn  6685:              $error = ('error: no unique suffix available for the new item ');
                   6686:         }
                   6687: #  remove lock
                   6688:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6689:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6690:     } else {
                   6691:         $error = "error: could not obtain lockfile\n";
                   6692:         $dellock = 'ok';
1.1172.2.58  raeburn  6693:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6694:             $dellock = 'nolock';
                   6695:         }
1.1172.2.13  raeburn  6696:     }
                   6697:     return ($newid,$dellock,$error);
                   6698: }
                   6699: 
1.1172.2.56  raeburn  6700: sub sixnum_code {
                   6701:     my $code;
                   6702:     for (0..6) {
                   6703:         $code .= int( rand(9) );
                   6704:     }
                   6705:     return $code;
                   6706: }
                   6707: 
1.765     albertel 6708: # -------------------------------------------------- portfolio access checking
                   6709: 
                   6710: sub portfolio_access {
1.1172.2.77  raeburn  6711:     my ($requrl,$clientip) = @_;
1.765     albertel 6712:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  6713:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6714:     if ($result) {
                   6715:         my %setters;
                   6716:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6717:             my ($startblock,$endblock) =
                   6718:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6719:             if ($startblock && $endblock) {
                   6720:                 return 'B';
                   6721:             }
                   6722:         } else {
                   6723:             my ($startblock,$endblock) =
                   6724:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6725:             if ($startblock && $endblock) {
                   6726:                 return 'B';
                   6727:             }
                   6728:         }
                   6729:     }
1.765     albertel 6730:     if ($result eq 'ok') {
1.766     albertel 6731:        return 'F';
1.765     albertel 6732:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6733:        return 'A';
1.765     albertel 6734:     }
1.766     albertel 6735:     return '';
1.765     albertel 6736: }
                   6737: 
                   6738: sub get_portfolio_access {
1.1172.2.77  raeburn  6739:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 6740: 
                   6741:     if (!ref($access_hash)) {
                   6742: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6743: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6744: 						   $file_name);
                   6745: 	$access_hash = $access_controls{$file_name};
                   6746:     }
                   6747: 
1.1172.2.77  raeburn  6748:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 6749:     my $now = time;
                   6750:     if (ref($access_hash) eq 'HASH') {
                   6751:         foreach my $key (keys(%{$access_hash})) {
                   6752:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6753:             if ($start > $now) {
                   6754:                 next;
                   6755:             }
                   6756:             if ($end && $end<$now) {
                   6757:                 next;
                   6758:             }
                   6759:             if ($scope eq 'public') {
                   6760:                 $public = $key;
                   6761:                 last;
                   6762:             } elsif ($scope eq 'guest') {
                   6763:                 $guest = $key;
                   6764:             } elsif ($scope eq 'domains') {
                   6765:                 push(@domains,$key);
                   6766:             } elsif ($scope eq 'users') {
                   6767:                 push(@users,$key);
                   6768:             } elsif ($scope eq 'course') {
                   6769:                 push(@courses,$key);
                   6770:             } elsif ($scope eq 'group') {
                   6771:                 push(@groups,$key);
1.1172.2.77  raeburn  6772:             } elsif ($scope eq 'ip') {
                   6773:                 push(@ips,$key);
1.765     albertel 6774:             }
                   6775:         }
                   6776:         if ($public) {
                   6777:             return 'ok';
1.1172.2.77  raeburn  6778:         } elsif (@ips > 0) {
                   6779:             my $allowed;
                   6780:             foreach my $ipkey (@ips) {
                   6781:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   6782:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   6783:                         $allowed = 1;
                   6784:                         last;
                   6785:                     }
                   6786:                 }
                   6787:             }
                   6788:             if ($allowed) {
                   6789:                 return 'ok';
                   6790:             }
1.765     albertel 6791:         }
                   6792:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6793:             if ($guest) {
                   6794:                 return $guest;
                   6795:             }
                   6796:         } else {
                   6797:             if (@domains > 0) {
                   6798:                 foreach my $domkey (@domains) {
                   6799:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6800:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6801:                             return 'ok';
                   6802:                         }
                   6803:                     }
                   6804:                 }
                   6805:             }
                   6806:             if (@users > 0) {
                   6807:                 foreach my $userkey (@users) {
1.865     raeburn  6808:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6809:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6810:                             if (ref($item) eq 'HASH') {
                   6811:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6812:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6813:                                     return 'ok';
                   6814:                                 }
                   6815:                             }
                   6816:                         }
                   6817:                     } 
1.765     albertel 6818:                 }
                   6819:             }
                   6820:             my %roleshash;
                   6821:             my @courses_and_groups = @courses;
                   6822:             push(@courses_and_groups,@groups); 
                   6823:             if (@courses_and_groups > 0) {
                   6824:                 my (%allgroups,%allroles); 
                   6825:                 my ($start,$end,$role,$sec,$group);
                   6826:                 foreach my $envkey (%env) {
1.1060    raeburn  6827:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6828:                         my $cid = $2.'_'.$3; 
                   6829:                         if ($1 eq 'gr') {
                   6830:                             $group = $4;
                   6831:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6832:                         } else {
                   6833:                             if ($4 eq '') {
                   6834:                                 $sec = 'none';
                   6835:                             } else {
                   6836:                                 $sec = $4;
                   6837:                             }
                   6838:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6839:                         }
1.811     albertel 6840:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6841:                         my $cid = $2.'_'.$3;
                   6842:                         if ($4 eq '') {
                   6843:                             $sec = 'none';
                   6844:                         } else {
                   6845:                             $sec = $4;
                   6846:                         }
                   6847:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6848:                     }
                   6849:                 }
                   6850:                 if (keys(%allroles) == 0) {
                   6851:                     return;
                   6852:                 }
                   6853:                 foreach my $key (@courses_and_groups) {
                   6854:                     my %content = %{$$access_hash{$key}};
                   6855:                     my $cnum = $content{'number'};
                   6856:                     my $cdom = $content{'domain'};
                   6857:                     my $cid = $cdom.'_'.$cnum;
                   6858:                     if (!exists($allroles{$cid})) {
                   6859:                         next;
                   6860:                     }    
                   6861:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6862:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6863:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6864:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6865:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6866:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6867:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6868:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6869:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6870:                                         if (grep/^all$/,@sections) {
                   6871:                                             return 'ok';
                   6872:                                         } else {
                   6873:                                             if (grep/^$sec$/,@sections) {
                   6874:                                                 return 'ok';
                   6875:                                             }
                   6876:                                         }
                   6877:                                     }
                   6878:                                 }
                   6879:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6880:                                     if (grep/^none$/,@groups) {
                   6881:                                         return 'ok';
                   6882:                                     }
                   6883:                                 } else {
                   6884:                                     if (grep/^all$/,@groups) {
                   6885:                                         return 'ok';
                   6886:                                     } 
                   6887:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6888:                                         if (grep/^$group$/,@groups) {
                   6889:                                             return 'ok';
                   6890:                                         }
                   6891:                                     }
                   6892:                                 } 
                   6893:                             }
                   6894:                         }
                   6895:                     }
                   6896:                 }
                   6897:             }
                   6898:             if ($guest) {
                   6899:                 return $guest;
                   6900:             }
                   6901:         }
                   6902:     }
                   6903:     return;
                   6904: }
                   6905: 
                   6906: sub course_group_datechecker {
                   6907:     my ($dates,$now,$status) = @_;
                   6908:     my ($start,$end) = split(/\./,$dates);
                   6909:     if (!$start && !$end) {
                   6910:         return 'ok';
                   6911:     }
                   6912:     if (grep/^active$/,@{$status}) {
                   6913:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6914:             return 'ok';
                   6915:         }
                   6916:     }
                   6917:     if (grep/^previous$/,@{$status}) {
                   6918:         if ($end > $now ) {
                   6919:             return 'ok';
                   6920:         }
                   6921:     }
                   6922:     if (grep/^future$/,@{$status}) {
                   6923:         if ($start > $now) {
                   6924:             return 'ok';
                   6925:         }
                   6926:     }
                   6927:     return; 
                   6928: }
                   6929: 
                   6930: sub parse_portfolio_url {
                   6931:     my ($url) = @_;
                   6932: 
                   6933:     my ($type,$udom,$unum,$group,$file_name);
                   6934:     
1.823     albertel 6935:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6936: 	$type = 1;
                   6937:         $udom = $1;
                   6938:         $unum = $2;
                   6939:         $file_name = $3;
1.823     albertel 6940:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6941: 	$type = 2;
                   6942:         $udom = $1;
                   6943:         $unum = $2;
                   6944:         $group = $3;
                   6945:         $file_name = $3.'/'.$4;
                   6946:     }
                   6947:     if (wantarray) {
                   6948: 	return ($type,$udom,$unum,$file_name,$group);
                   6949:     }
                   6950:     return $type;
                   6951: }
                   6952: 
                   6953: sub is_portfolio_url {
                   6954:     my ($url) = @_;
                   6955:     return scalar(&parse_portfolio_url($url));
                   6956: }
                   6957: 
1.798     raeburn  6958: sub is_portfolio_file {
                   6959:     my ($file) = @_;
1.820     raeburn  6960:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6961:         return 1;
                   6962:     }
                   6963:     return;
                   6964: }
                   6965: 
1.976     raeburn  6966: sub usertools_access {
1.1084    raeburn  6967:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6968:     my ($access,%tools);
                   6969:     if ($context eq '') {
                   6970:         $context = 'tools';
                   6971:     }
                   6972:     if ($context eq 'requestcourses') {
                   6973:         %tools = (
                   6974:                       official   => 1,
                   6975:                       unofficial => 1,
1.1006    raeburn  6976:                       community  => 1,
1.1172.2.37  raeburn  6977:                       textbook   => 1,
1.985     raeburn  6978:                  );
1.1172.2.9  raeburn  6979:     } elsif ($context eq 'requestauthor') {
                   6980:         %tools = (
                   6981:                       requestauthor => 1,
                   6982:                  );
1.985     raeburn  6983:     } else {
                   6984:         %tools = (
                   6985:                       aboutme   => 1,
                   6986:                       blog      => 1,
1.1172.2.6  raeburn  6987:                       webdav    => 1,
1.985     raeburn  6988:                       portfolio => 1,
                   6989:                  );
                   6990:     }
1.976     raeburn  6991:     return if (!defined($tools{$tool}));
                   6992: 
1.1172.2.35  raeburn  6993:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6994:         $udom = $env{'user.domain'};
                   6995:         $uname = $env{'user.name'};
                   6996:     }
                   6997: 
1.978     raeburn  6998:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6999:         if ($action ne 'reload') {
1.985     raeburn  7000:             if ($context eq 'requestcourses') {
                   7001:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  7002:             } elsif ($context eq 'requestauthor') {
                   7003:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7004:             } else {
                   7005:                 return $env{'environment.availabletools.'.$tool};
                   7006:             }
                   7007:         }
1.976     raeburn  7008:     }
                   7009: 
1.1172.2.9  raeburn  7010:     my ($toolstatus,$inststatus,$envkey);
                   7011:     if ($context eq 'requestauthor') {
                   7012:         $envkey = $context;
                   7013:     } else {
                   7014:         $envkey = $context.'.'.$tool;
                   7015:     }
1.976     raeburn  7016: 
1.985     raeburn  7017:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7018:          ($action ne 'reload')) {
1.1172.2.9  raeburn  7019:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7020:         $inststatus = $env{'environment.inststatus'};
                   7021:     } else {
1.1084    raeburn  7022:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  7023:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7024:             $inststatus = $userenvref->{'inststatus'};
                   7025:         } else {
1.1172.2.9  raeburn  7026:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7027:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7028:             $inststatus = $userenv{'inststatus'};
                   7029:         }
1.976     raeburn  7030:     }
                   7031: 
                   7032:     if ($toolstatus ne '') {
                   7033:         if ($toolstatus) {
                   7034:             $access = 1;
                   7035:         } else {
                   7036:             $access = 0;
                   7037:         }
                   7038:         return $access;
                   7039:     }
                   7040: 
1.1084    raeburn  7041:     my ($is_adv,%domdef);
                   7042:     if (ref($is_advref) eq 'HASH') {
                   7043:         $is_adv = $is_advref->{'is_adv'};
                   7044:     } else {
                   7045:         $is_adv = &is_advanced_user($udom,$uname);
                   7046:     }
                   7047:     if (ref($domdefref) eq 'HASH') {
                   7048:         %domdef = %{$domdefref};
                   7049:     } else {
                   7050:         %domdef = &get_domain_defaults($udom);
                   7051:     }
1.976     raeburn  7052:     if (ref($domdef{$tool}) eq 'HASH') {
                   7053:         if ($is_adv) {
                   7054:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7055:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7056:                     $access = 1;
                   7057:                 } else {
                   7058:                     $access = 0;
                   7059:                 }
                   7060:                 return $access;
                   7061:             }
                   7062:         }
                   7063:         if ($inststatus ne '') {
                   7064:             my ($hasaccess,$hasnoaccess);
                   7065:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7066:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7067:                     if ($domdef{$tool}{$affiliation}) {
                   7068:                         $hasaccess = 1;
                   7069:                     } else {
                   7070:                         $hasnoaccess = 1;
                   7071:                     }
                   7072:                 }
                   7073:             }
                   7074:             if ($hasaccess || $hasnoaccess) {
                   7075:                 if ($hasaccess) {
                   7076:                     $access = 1;
                   7077:                 } elsif ($hasnoaccess) {
                   7078:                     $access = 0; 
                   7079:                 }
                   7080:                 return $access;
                   7081:             }
                   7082:         } else {
                   7083:             if ($domdef{$tool}{'default'} ne '') {
                   7084:                 if ($domdef{$tool}{'default'}) {
                   7085:                     $access = 1;
                   7086:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7087:                     $access = 0;
                   7088:                 }
                   7089:                 return $access;
                   7090:             }
                   7091:         }
                   7092:     } else {
1.1172.2.6  raeburn  7093:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7094:             $access = 1;
                   7095:         } else {
                   7096:             $access = 0;
                   7097:         }
1.976     raeburn  7098:         return $access;
                   7099:     }
                   7100: }
                   7101: 
1.1050    raeburn  7102: sub is_course_owner {
                   7103:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7104:     if (($udom eq '') || ($uname eq '')) {
                   7105:         $udom = $env{'user.domain'};
                   7106:         $uname = $env{'user.name'};
                   7107:     }
                   7108:     unless (($udom eq '') || ($uname eq '')) {
                   7109:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7110:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7111:                 return 1;
                   7112:             } else {
                   7113:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7114:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7115:                     return 1;
                   7116:                 }
                   7117:             }
                   7118:         }
                   7119:     }
                   7120:     return;
                   7121: }
                   7122: 
1.976     raeburn  7123: sub is_advanced_user {
                   7124:     my ($udom,$uname) = @_;
1.1085    raeburn  7125:     if ($udom ne '' && $uname ne '') {
                   7126:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7127:             if (wantarray) {
                   7128:                 return ($env{'user.adv'},$env{'user.author'});
                   7129:             } else {
                   7130:                 return $env{'user.adv'};
                   7131:             }
1.1085    raeburn  7132:         }
                   7133:     }
1.976     raeburn  7134:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7135:     my %allroles;
1.1128    raeburn  7136:     my ($is_adv,$is_author);
1.976     raeburn  7137:     foreach my $role (keys(%roleshash)) {
                   7138:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7139:         my $area = '/'.$tdomain.'/'.$trest;
                   7140:         if ($sec ne '') {
                   7141:             $area .= '/'.$sec;
                   7142:         }
                   7143:         if (($area ne '') && ($trole ne '')) {
                   7144:             my $spec=$trole.'.'.$area;
                   7145:             if ($trole =~ /^cr\//) {
                   7146:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7147:             } elsif ($trole ne 'gr') {
                   7148:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7149:             }
1.1128    raeburn  7150:             if ($trole eq 'au') {
                   7151:                 $is_author = 1;
                   7152:             }
1.976     raeburn  7153:         }
                   7154:     }
                   7155:     foreach my $role (keys(%allroles)) {
                   7156:         last if ($is_adv);
                   7157:         foreach my $item (split(/:/,$allroles{$role})) {
                   7158:             if ($item ne '') {
                   7159:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7160:                 if ($privilege eq 'adv') {
                   7161:                     $is_adv = 1;
                   7162:                     last;
                   7163:                 }
                   7164:             }
                   7165:         }
                   7166:     }
1.1128    raeburn  7167:     if (wantarray) {
                   7168:         return ($is_adv,$is_author);
                   7169:     }
1.976     raeburn  7170:     return $is_adv;
                   7171: }
1.798     raeburn  7172: 
1.1035    raeburn  7173: sub check_can_request {
1.1036    raeburn  7174:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7175:     my $canreq = 0;
                   7176:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7177:     my @options = ('approval','validate','autolimit');
                   7178:     my $optregex = join('|',@options);
                   7179:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7180:         foreach my $type (@{$types}) {
                   7181:             if (&usertools_access($env{'user.name'},
                   7182:                                   $env{'user.domain'},
                   7183:                                   $type,undef,'requestcourses')) {
                   7184:                 $canreq ++;
1.1036    raeburn  7185:                 if (ref($request_domains) eq 'HASH') {
                   7186:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7187:                 }
1.1035    raeburn  7188:                 if ($dom eq $env{'user.domain'}) {
                   7189:                     $can_request->{$type} = 1;
                   7190:                 }
                   7191:             }
                   7192:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7193:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7194:                 if (@curr > 0) {
1.1036    raeburn  7195:                     foreach my $item (@curr) {
                   7196:                         if (ref($request_domains) eq 'HASH') {
                   7197:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7198:                             if ($otherdom ne '') {
                   7199:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7200:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7201:                                         push(@{$request_domains->{$type}},$otherdom);
                   7202:                                     }
                   7203:                                 } else {
                   7204:                                     push(@{$request_domains->{$type}},$otherdom);
                   7205:                                 }
                   7206:                             }
                   7207:                         }
                   7208:                     }
                   7209:                     unless($dom eq $env{'user.domain'}) {
                   7210:                         $canreq ++;
1.1035    raeburn  7211:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7212:                             $can_request->{$type} = 1;
                   7213:                         }
                   7214:                     }
                   7215:                 }
                   7216:             }
                   7217:         }
                   7218:     }
                   7219:     return $canreq;
                   7220: }
                   7221: 
1.341     www      7222: # ---------------------------------------------- Custom access rule evaluation
                   7223: 
                   7224: sub customaccess {
                   7225:     my ($priv,$uri)=@_;
1.807     albertel 7226:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7227:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7228:     $udom = &LONCAPA::clean_domain($udom);
                   7229:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7230:     my $access=0;
1.800     albertel 7231:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7232: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7233: 	if ($type eq 'user') {
                   7234: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7235: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7236: 		if ($tdom) {
                   7237: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7238: 		}
1.896     albertel 7239: 		if ($tuname) {
                   7240: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7241: 		}
                   7242: 		$access=($effect eq 'allow');
                   7243: 		last;
                   7244: 	    }
                   7245: 	} else {
                   7246: 	    if ($role) {
                   7247: 		if ($role ne $urole) { next; }
                   7248: 	    }
                   7249: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7250: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7251: 		if ($tdom) {
                   7252: 		    if ($tdom ne $udom) { next; }
                   7253: 		}
                   7254: 		if ($tcrs) {
                   7255: 		    if ($tcrs ne $ucrs) { next; }
                   7256: 		}
                   7257: 		if ($tsec) {
                   7258: 		    if ($tsec ne $usec) { next; }
                   7259: 		}
                   7260: 		$access=($effect eq 'allow');
                   7261: 		last;
                   7262: 	    }
                   7263: 	    if ($realm eq '' && $role eq '') {
                   7264: 		$access=($effect eq 'allow');
                   7265: 	    }
1.402     bowersj2 7266: 	}
1.341     www      7267:     }
                   7268:     return $access;
                   7269: }
                   7270: 
1.103     harris41 7271: # ------------------------------------------------- Check for a user privilege
1.12      www      7272: 
                   7273: sub allowed {
1.1172.2.65  raeburn  7274:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7275:     my $ver_orguri=$uri;
1.439     www      7276:     $uri=&deversion($uri);
1.152     www      7277:     my $orguri=$uri;
1.52      www      7278:     $uri=&declutter($uri);
1.809     raeburn  7279: 
1.810     raeburn  7280:     if ($priv eq 'evb') {
                   7281: # Evade communication block restrictions for specified role in a course
                   7282:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7283:             return $1;
                   7284:         } else {
                   7285:             return;
                   7286:         }
                   7287:     }
                   7288: 
1.620     albertel 7289:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7290: # Free bre access to adm and meta resources
1.775     albertel 7291:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 7292: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7293: 	&& ($priv eq 'bre')) {
1.14      www      7294: 	return 'F';
1.159     www      7295:     }
                   7296: 
1.545     banghart 7297: # Free bre access to user's own portfolio contents
1.714     raeburn  7298:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7299:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7300: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7301:         my %setters;
                   7302:         my ($startblock,$endblock) = 
                   7303:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7304:         if ($startblock && $endblock) {
                   7305:             return 'B';
                   7306:         } else {
                   7307:             return 'F';
                   7308:         }
1.545     banghart 7309:     }
                   7310: 
1.762     raeburn  7311: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7312:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7313:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7314:         if (exists($env{'request.course.id'})) {
                   7315:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7316:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7317:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7318:                 my $courseprivid=$env{'request.course.id'};
                   7319:                 $courseprivid=~s/\_/\//;
                   7320:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7321:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7322:                     return $1; 
1.762     raeburn  7323:                 } else {
                   7324:                     if ($env{'request.course.sec'}) {
                   7325:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7326:                     }
                   7327:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7328:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7329:                         return $2;
                   7330:                     }
1.714     raeburn  7331:                 }
                   7332:             }
                   7333:         }
                   7334:     }
                   7335: 
1.159     www      7336: # Free bre to public access
                   7337: 
                   7338:     if ($priv eq 'bre') {
1.238     www      7339:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7340: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7341:            return 'F'; 
                   7342:         }
1.238     www      7343:         if ($copyright eq 'priv') {
                   7344:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7345: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7346: 		return '';
                   7347:             }
                   7348:         }
                   7349:         if ($copyright eq 'domain') {
                   7350:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7351: 	    unless (($env{'user.domain'} eq $1) ||
                   7352:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7353: 		return '';
                   7354:             }
1.262     matthew  7355:         }
1.620     albertel 7356:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7357:             # Library role, so allow browsing of resources in this domain.
                   7358:             return 'F';
1.238     www      7359:         }
1.341     www      7360:         if ($copyright eq 'custom') {
                   7361: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7362:         }
1.14      www      7363:     }
1.264     matthew  7364:     # Domain coordinator is trying to create a course
1.620     albertel 7365:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7366:         # uri is the requested domain in this case.
                   7367:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7368:         # a role of dc for the domain in question.
1.620     albertel 7369:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7370:     }
1.29      www      7371: 
1.52      www      7372:     my $thisallowed='';
                   7373:     my $statecond=0;
                   7374:     my $courseprivid='';
                   7375: 
1.1039    raeburn  7376:     my $ownaccess;
1.1043    raeburn  7377:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7378:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7379:         if ($uri eq '') {
                   7380:             $ownaccess = 1;
                   7381:         } else {
                   7382:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7383:                 my $udom = $env{'user.domain'};
                   7384:                 my $uname = $env{'user.name'};
                   7385:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7386:                     $ownaccess = 1;
1.1040    raeburn  7387:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7388:                     unless ($uri =~ m{\.\./}) {
                   7389:                         $ownaccess = 1;
                   7390:                     }
                   7391:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7392:                     my $now = time;
                   7393:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7394:                         my $adom = $1;
                   7395:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7396:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7397:                                 my ($start,$end) = split('.',$env{$key});
                   7398:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7399:                                     $ownaccess = 1;
                   7400:                                     last;
                   7401:                                 }
                   7402:                             }
                   7403:                         }
                   7404:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7405:                         my $adom = $1;
                   7406:                         my $aname = $2;
1.1042    raeburn  7407:                         foreach my $role ('ca','aa') { 
                   7408:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7409:                                 my ($start,$end) =
                   7410:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7411:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7412:                                     $ownaccess = 1;
                   7413:                                     last;
                   7414:                                 }
1.1039    raeburn  7415:                             }
                   7416:                         }
                   7417:                     }
                   7418:                 }
                   7419:             }
                   7420:         }
                   7421:     }
                   7422: 
1.52      www      7423: # Course
                   7424: 
1.620     albertel 7425:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7426:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7427:             $thisallowed.=$1;
                   7428:         }
1.52      www      7429:     }
1.29      www      7430: 
1.52      www      7431: # Domain
                   7432: 
1.620     albertel 7433:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7434:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7435:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7436:             $thisallowed.=$1;
                   7437:         }
1.12      www      7438:     }
1.52      www      7439: 
1.1141    raeburn  7440: # User who is not author or co-author might still be able to edit
                   7441: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7442:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7443:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7444:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7445:             $thisallowed.=$1;
                   7446:         }
                   7447:     }
                   7448: 
1.52      www      7449: # Course: uri itself is a course
1.66      www      7450:     my $courseuri=$uri;
                   7451:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7452:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7453: 
1.620     albertel 7454:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7455:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7456:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7457:             $thisallowed.=$1;
                   7458:         }
1.12      www      7459:     }
1.29      www      7460: 
1.665     albertel 7461: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7462: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7463:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7464: 	$thisallowed='';
1.671     raeburn  7465:         my ($match)=&is_on_map($uri);
                   7466:         if ($match) {
                   7467:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7468:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  7469:                 my $value = $1;
                   7470:                 if ($noblockcheck) {
                   7471:                     $thisallowed.=$value;
1.1162    raeburn  7472:                 } else {
1.1172.2.65  raeburn  7473:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7474:                     if (@blockers > 0) {
                   7475:                         $thisallowed = 'B';
                   7476:                     } else {
                   7477:                         $thisallowed.=$value;
                   7478:                     }
1.1162    raeburn  7479:                 }
1.671     raeburn  7480:             }
                   7481:         } else {
1.705     albertel 7482:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7483:             if ($refuri) {
                   7484:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7485:                     $thisallowed='F';
1.671     raeburn  7486:                 } else {
                   7487:                     $refuri=&declutter($refuri);
                   7488:                     my ($match) = &is_on_map($refuri);
                   7489:                     if ($match) {
1.1172.2.65  raeburn  7490:                         if ($noblockcheck) {
1.1162    raeburn  7491:                             $thisallowed='F';
1.1172.2.65  raeburn  7492:                         } else {
                   7493:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7494:                             if (@blockers > 0) {
                   7495:                                 $thisallowed = 'B';
                   7496:                             } else {
                   7497:                                 $thisallowed='F';
                   7498:                             }
1.1162    raeburn  7499:                         }
1.671     raeburn  7500:                     }
1.669     raeburn  7501:                 }
1.671     raeburn  7502:             }
                   7503:         }
1.314     www      7504:     }
1.492     albertel 7505: 
1.766     albertel 7506:     if ($priv eq 'bre'
                   7507: 	&& $thisallowed ne 'F' 
                   7508: 	&& $thisallowed ne '2'
                   7509: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  7510: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7511:     }
                   7512:     
1.52      www      7513: # Full access at system, domain or course-wide level? Exit.
1.29      www      7514:     if ($thisallowed=~/F/) {
                   7515: 	return 'F';
                   7516:     }
                   7517: 
1.52      www      7518: # If this is generating or modifying users, exit with special codes
1.29      www      7519: 
1.643     www      7520:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7521: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7522: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7523: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7524: 	    unless ($auname) { return $thisallowed; }
                   7525: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7526: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7527: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7528: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7529: 	}
1.52      www      7530: 	return $thisallowed;
                   7531:     }
                   7532: #
1.103     harris41 7533: # Gathered so far: system, domain and course wide privileges
1.52      www      7534: #
                   7535: # Course: See if uri or referer is an individual resource that is part of 
                   7536: # the course
                   7537: 
1.620     albertel 7538:     if ($env{'request.course.id'}) {
1.232     www      7539: 
1.620     albertel 7540:        $courseprivid=$env{'request.course.id'};
                   7541:        if ($env{'request.course.sec'}) {
                   7542:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7543:        }
                   7544:        $courseprivid=~s/\_/\//;
                   7545:        my $checkreferer=1;
1.232     www      7546:        my ($match,$cond)=&is_on_map($uri);
                   7547:        if ($match) {
                   7548:            $statecond=$cond;
1.620     albertel 7549:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7550:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7551:                my $value = $1;
                   7552:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  7553:                    if ($noblockcheck) {
1.1162    raeburn  7554:                        $thisallowed.=$value;
1.1172.2.65  raeburn  7555:                    } else {
                   7556:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7557:                        if (@blockers > 0) {
                   7558:                            $thisallowed = 'B';
                   7559:                        } else {
                   7560:                            $thisallowed.=$value;
                   7561:                        }
1.1162    raeburn  7562:                    }
                   7563:                } else {
                   7564:                    $thisallowed.=$value;
                   7565:                }
1.52      www      7566:                $checkreferer=0;
                   7567:            }
1.29      www      7568:        }
1.83      www      7569:        
1.148     www      7570:        if ($checkreferer) {
1.620     albertel 7571: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7572:             unless ($refuri) {
1.800     albertel 7573:                 foreach my $key (keys(%env)) {
                   7574: 		    if ($key=~/^httpref\..*\*/) {
                   7575: 			my $pattern=$key;
1.156     www      7576:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7577:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7578:                         $pattern=~s/\//\\\//g;
1.152     www      7579:                         if ($orguri=~/$pattern/) {
1.800     albertel 7580: 			    $refuri=$env{$key};
1.148     www      7581:                         }
                   7582:                     }
1.191     harris41 7583:                 }
1.148     www      7584:             }
1.232     www      7585: 
1.148     www      7586:          if ($refuri) { 
1.152     www      7587: 	  $refuri=&declutter($refuri);
1.232     www      7588:           my ($match,$cond)=&is_on_map($refuri);
                   7589:             if ($match) {
                   7590:               my $refstatecond=$cond;
1.620     albertel 7591:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7592:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7593:                   my $value = $1;
                   7594:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  7595:                       if ($noblockcheck) {
1.1162    raeburn  7596:                           $thisallowed.=$value;
1.1172.2.65  raeburn  7597:                       } else {
                   7598:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7599:                           if (@blockers > 0) {
                   7600:                               $thisallowed = 'B';
                   7601:                           } else {
                   7602:                               $thisallowed.=$value;
                   7603:                           }
1.1162    raeburn  7604:                       }
                   7605:                   } else {
                   7606:                       $thisallowed.=$value;
                   7607:                   }
1.53      www      7608:                   $uri=$refuri;
                   7609:                   $statecond=$refstatecond;
1.52      www      7610:               }
                   7611:           }
1.148     www      7612:         }
1.29      www      7613:        }
1.52      www      7614:    }
1.29      www      7615: 
1.52      www      7616: #
1.103     harris41 7617: # Gathered now: all privileges that could apply, and condition number
1.52      www      7618: # 
                   7619: #
                   7620: # Full or no access?
                   7621: #
1.29      www      7622: 
1.52      www      7623:     if ($thisallowed=~/F/) {
                   7624: 	return 'F';
                   7625:     }
1.29      www      7626: 
1.52      www      7627:     unless ($thisallowed) {
                   7628:         return '';
                   7629:     }
1.29      www      7630: 
1.52      www      7631: # Restrictions exist, deal with them
                   7632: #
                   7633: #   C:according to course preferences
                   7634: #   R:according to resource settings
                   7635: #   L:unless locked
                   7636: #   X:according to user session state
                   7637: #
                   7638: 
                   7639: # Possibly locked functionality, check all courses
1.54      www      7640: # Locks might take effect only after 10 minutes cache expiration for other
                   7641: # courses, and 2 minutes for current course
1.52      www      7642: 
                   7643:     my $envkey;
                   7644:     if ($thisallowed=~/L/) {
1.1000    raeburn  7645:         foreach $envkey (keys(%env)) {
1.54      www      7646:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7647:                my $courseid=$2;
                   7648:                my $roleid=$1.'.'.$2;
1.92      www      7649:                $courseid=~s/^\///;
1.54      www      7650:                my $expiretime=600;
1.620     albertel 7651:                if ($env{'request.role'} eq $roleid) {
1.54      www      7652: 		  $expiretime=120;
                   7653:                }
                   7654: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7655:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7656:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7657: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7658:                }
1.620     albertel 7659:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7660:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7661: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7662:                        &log($env{'user.domain'},$env{'user.name'},
                   7663:                             $env{'user.home'},
1.57      www      7664:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7665:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7666:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7667: 		       return '';
                   7668:                    }
                   7669:                }
1.620     albertel 7670:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7671:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7672: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7673:                        &log($env{'user.domain'},$env{'user.name'},
                   7674:                             $env{'user.home'},
1.57      www      7675:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7676:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7677:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7678: 		       return '';
                   7679:                    }
                   7680:                }
                   7681: 	   }
1.29      www      7682:        }
1.52      www      7683:     }
                   7684:    
                   7685: #
                   7686: # Rest of the restrictions depend on selected course
                   7687: #
                   7688: 
1.620     albertel 7689:     unless ($env{'request.course.id'}) {
1.766     albertel 7690: 	if ($thisallowed eq 'A') {
                   7691: 	    return 'A';
1.814     raeburn  7692:         } elsif ($thisallowed eq 'B') {
                   7693:             return 'B';
1.766     albertel 7694: 	} else {
                   7695: 	    return '1';
                   7696: 	}
1.52      www      7697:     }
1.29      www      7698: 
1.52      www      7699: #
                   7700: # Now user is definitely in a course
                   7701: #
1.53      www      7702: 
                   7703: 
                   7704: # Course preferences
                   7705: 
                   7706:    if ($thisallowed=~/C/) {
1.620     albertel 7707:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7708:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7709:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7710: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  7711: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7712: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7713: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7714: 			$env{'request.course.id'});
                   7715: 	   }
1.237     www      7716:            return '';
                   7717:        }
                   7718: 
1.620     albertel 7719:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7720: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  7721: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7722: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7723: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7724: 			$env{'request.course.id'});
                   7725: 	   }
1.54      www      7726:            return '';
                   7727:        }
1.53      www      7728:    }
                   7729: 
                   7730: # Resource preferences
                   7731: 
                   7732:    if ($thisallowed=~/R/) {
1.620     albertel 7733:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7734:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7735: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7736: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7737: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7738: 	   }
                   7739: 	   return '';
1.54      www      7740:        }
1.53      www      7741:    }
1.30      www      7742: 
1.246     www      7743: # Restricted by state or randomout?
1.30      www      7744: 
1.52      www      7745:    if ($thisallowed=~/X/) {
1.620     albertel 7746:       if ($env{'acc.randomout'}) {
1.579     albertel 7747: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7748:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7749:             return ''; 
                   7750:          }
1.247     www      7751:       }
                   7752:       if (&condval($statecond)) {
1.52      www      7753: 	 return '2';
                   7754:       } else {
                   7755:          return '';
                   7756:       }
                   7757:    }
1.30      www      7758: 
1.766     albertel 7759:     if ($thisallowed eq 'A') {
                   7760: 	return 'A';
1.814     raeburn  7761:     } elsif ($thisallowed eq 'B') {
                   7762:         return 'B';
1.766     albertel 7763:     }
1.52      www      7764:    return 'F';
1.232     www      7765: }
1.1162    raeburn  7766: 
1.1172.2.13  raeburn  7767: # ------------------------------------------- Check construction space access
                   7768: 
                   7769: sub constructaccess {
                   7770:     my ($url,$setpriv)=@_;
                   7771: 
                   7772: # We do not allow editing of previous versions of files
                   7773:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7774: 
                   7775: # Get username and domain from URL
                   7776:     my ($ownername,$ownerdomain,$ownerhome);
                   7777: 
                   7778:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  7779:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  7780: 
                   7781: # The URL does not really point to any authorspace, forget it
                   7782:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7783: 
                   7784: # Now we need to see if the user has access to the authorspace of
                   7785: # $ownername at $ownerdomain
                   7786: 
                   7787:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7788: # Real author for this?
                   7789:        $ownerhome = $env{'user.home'};
                   7790:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7791:           return ($ownername,$ownerdomain,$ownerhome);
                   7792:        }
                   7793:     } else {
                   7794: # Co-author for this?
                   7795:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7796:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7797:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7798:             return ($ownername,$ownerdomain,$ownerhome);
                   7799:         }
                   7800:     }
                   7801: 
                   7802: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7803: # we might as well leave
                   7804:    unless ($setpriv) { return ''; }
                   7805: 
                   7806: # Backdoor access?
                   7807:     my $allowed=&allowed('eco',$ownerdomain);
                   7808: # Nope
                   7809:     unless ($allowed) { return ''; }
                   7810: # Looks like we may have access, but could be locked by the owner of the construction space
                   7811:     if ($allowed eq 'U') {
                   7812:         my %blocked=&get('environment',['domcoord.author'],
                   7813:                          $ownerdomain,$ownername);
                   7814: # Is blocked by owner
                   7815:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7816:     }
                   7817:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7818: # Grant temporary access
                   7819:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  7820:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  7821:         if (!$update) { $update = $then; }
                   7822:         my $refresh=$env{'user.refresh.time'};
                   7823:         if (!$refresh) { $refresh = $update; }
                   7824:         my $now = time;
                   7825:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7826:                            $now,'ca','constructaccess');
                   7827:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7828:         return($ownername,$ownerdomain,$ownerhome);
                   7829:     }
                   7830: # No business here
                   7831:     return '';
                   7832: }
                   7833: 
1.1172.2.66  raeburn  7834: # ----------------------------------------------------------- Content Blocking
                   7835: 
                   7836: {
                   7837: # Caches for faster Course Contents display where content blocking
                   7838: # is in operation (i.e., interval param set) for timed quiz.
                   7839: #
                   7840: # User for whom data are being temporarily cached.
                   7841: my $cacheduser='';
                   7842: # Cached blockers for this user (a hash of blocking items).
                   7843: my %cachedblockers=();
                   7844: # When the data were last cached.
                   7845: my $cachedlast='';
                   7846: 
                   7847: sub load_all_blockers {
                   7848:     my ($uname,$udom,$blocks)=@_;
                   7849:     if (($uname ne '') && ($udom ne '')) {
                   7850:         if (($cacheduser eq $uname.':'.$udom) &&
                   7851:             (abs($cachedlast-time)<5)) {
                   7852:             return;
                   7853:         }
                   7854:     }
                   7855:     $cachedlast=time;
                   7856:     $cacheduser=$uname.':'.$udom;
                   7857:     %cachedblockers = &get_commblock_resources($blocks);
                   7858: }
                   7859: 
1.1162    raeburn  7860: sub get_comm_blocks {
                   7861:     my ($cdom,$cnum) = @_;
                   7862:     if ($cdom eq '' || $cnum eq '') {
                   7863:         return unless ($env{'request.course.id'});
                   7864:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7865:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7866:     }
                   7867:     my %commblocks;
                   7868:     my $hashid=$cdom.'_'.$cnum;
                   7869:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7870:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7871:         %commblocks = %{$blocksref};
                   7872:     } else {
                   7873:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7874:         my $cachetime = 600;
                   7875:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7876:     }
                   7877:     return %commblocks;
                   7878: }
                   7879: 
1.1172.2.66  raeburn  7880: sub get_commblock_resources {
                   7881:     my ($blocks) = @_;
                   7882:     my %blockers = ();
                   7883:     return %blockers unless ($env{'request.course.id'});
                   7884:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  7885:     my %commblocks;
                   7886:     if (ref($blocks) eq 'HASH') {
                   7887:         %commblocks = %{$blocks};
                   7888:     } else {
                   7889:         %commblocks = &get_comm_blocks();
                   7890:     }
1.1172.2.66  raeburn  7891:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  7892:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  7893:     return %blockers unless (ref($navmap));
                   7894:     my $now = time;
1.1162    raeburn  7895:     foreach my $block (keys(%commblocks)) {
                   7896:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7897:             my ($start,$end) = ($1,$2);
                   7898:             if ($start <= $now && $end >= $now) {
                   7899:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7900:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7901:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  7902:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7903:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  7904:                             }
                   7905:                         }
                   7906:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  7907:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7908:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  7909:                             }
                   7910:                         }
                   7911:                     }
                   7912:                 }
                   7913:             }
                   7914:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7915:             my $item = $1;
1.1163    raeburn  7916:             my @to_test;
1.1162    raeburn  7917:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7918:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66  raeburn  7919:                     my @interval;
                   7920:                     my $type = 'map';
                   7921:                     if ($item eq 'course') {
                   7922:                         $type = 'course';
                   7923:                         @interval=&EXT("resource.0.interval");
                   7924:                     } else {
                   7925:                         if ($item =~ /___\d+___/) {
                   7926:                             $type = 'resource';
                   7927:                             @interval=&EXT("resource.0.interval",$item);
                   7928:                             if (ref($navmap)) {
                   7929:                                 my $res = $navmap->getBySymb($item);
                   7930:                                 push(@to_test,$res);
                   7931:                             }
1.1162    raeburn  7932:                         } else {
1.1172.2.66  raeburn  7933:                             my $mapsymb = &symbread($item,1);
                   7934:                             if ($mapsymb) {
                   7935:                                 if (ref($navmap)) {
                   7936:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   7937:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   7938:                                     foreach my $res (@to_test) {
                   7939:                                         my $symb = $res->symb();
                   7940:                                         next if ($symb eq $mapsymb);
                   7941:                                         if ($symb ne '') {
                   7942:                                             @interval=&EXT("resource.0.interval",$symb);
                   7943:                                             if ($interval[1] eq 'map') {
                   7944:                                                 last;
1.1162    raeburn  7945:                                             }
                   7946:                                         }
                   7947:                                     }
                   7948:                                 }
                   7949:                             }
                   7950:                         }
1.1172.2.66  raeburn  7951:                     }
                   7952:                     if ($interval[0] =~ /^\d+$/) {
                   7953:                         my $first_access;
                   7954:                         if ($type eq 'resource') {
                   7955:                             $first_access=&get_first_access($interval[1],$item);
                   7956:                         } elsif ($type eq 'map') {
                   7957:                             $first_access=&get_first_access($interval[1],undef,$item);
                   7958:                         } else {
                   7959:                             $first_access=&get_first_access($interval[1]);
                   7960:                         }
                   7961:                         if ($first_access) {
                   7962:                             my $timesup = $first_access+$interval[0];
                   7963:                             if ($timesup > $now) {
                   7964:                                 my $activeblock;
                   7965:                                 foreach my $res (@to_test) {
                   7966:                                     if ($res->answerable()) {
                   7967:                                         $activeblock = 1;
                   7968:                                         last;
                   7969:                                     }
                   7970:                                 }
                   7971:                                 if ($activeblock) {
                   7972:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7973:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7974:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   7975:                                          }
                   7976:                                     }
                   7977:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7978:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7979:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  7980:                                         }
1.1162    raeburn  7981:                                     }
                   7982:                                 }
                   7983:                             }
                   7984:                         }
                   7985:                     }
                   7986:                 }
                   7987:             }
                   7988:         }
                   7989:     }
1.1172.2.66  raeburn  7990:     return %blockers;
1.1162    raeburn  7991: }
                   7992: 
1.1172.2.66  raeburn  7993: sub has_comm_blocking {
                   7994:     my ($priv,$symb,$uri,$blocks) = @_;
                   7995:     my @blockers;
                   7996:     return unless ($env{'request.course.id'});
                   7997:     return unless ($priv eq 'bre');
                   7998:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7999:     return if ($env{'request.state'} eq 'construct');
                   8000:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   8001:     return unless (keys(%cachedblockers) > 0);
                   8002:     my (%possibles,@symbs);
                   8003:     if (!$symb) {
                   8004:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  8005:     }
1.1172.2.66  raeburn  8006:     if ($symb) {
                   8007:         @symbs = ($symb);
                   8008:     } elsif (keys(%possibles)) {
                   8009:         @symbs = keys(%possibles);
                   8010:     }
                   8011:     my $noblock;
                   8012:     foreach my $symb (@symbs) {
                   8013:         last if ($noblock);
                   8014:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   8015:         foreach my $block (keys(%cachedblockers)) {
                   8016:             if ($block =~ /^firstaccess____(.+)$/) {
                   8017:                 my $item = $1;
                   8018:                 if (($item eq $map) || ($item eq $symb)) {
                   8019:                     $noblock = 1;
                   8020:                     last;
                   8021:                 }
1.1162    raeburn  8022:             }
1.1172.2.66  raeburn  8023:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   8024:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   8025:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   8026:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8027:                             push(@blockers,$block);
                   8028:                         }
                   8029:                     }
                   8030:                 }
                   8031:             }
                   8032:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   8033:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   8034:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   8035:                         push(@blockers,$block);
                   8036:                     }
                   8037:                 }
1.1162    raeburn  8038:             }
                   8039:         }
                   8040:     }
1.1172.2.66  raeburn  8041:     return if ($noblock);
                   8042:     return @blockers;
                   8043: }
1.1162    raeburn  8044: }
                   8045: 
1.1172.2.66  raeburn  8046: # -------------------------------- Deversion and split uri into path an filename
                   8047: 
1.1133    foxr     8048: #
1.1172.2.66  raeburn  8049: #   Removes the version from a URI and
1.1133    foxr     8050: #   splits it in to its filename and path to the filename.
                   8051: #   Seems like File::Basename could have done this more clearly.
                   8052: #   Parameters:
                   8053: #      $uri   - input URI
                   8054: #   Returns:
                   8055: #     Two element list consisting of 
                   8056: #     $pathname  - the URI up to and excluding the trailing /
                   8057: #     $filename  - The part of the URI following the last /
                   8058: #  NOTE:
                   8059: #    Another realization of this is simply:
                   8060: #    use File::Basename;
                   8061: #    ...
                   8062: #    $uri = shift;
                   8063: #    $filename = basename($uri);
                   8064: #    $path     = dirname($uri);
                   8065: #    return ($filename, $path);
                   8066: #
                   8067: #     The implementation below is probably faster however.
                   8068: #
1.710     albertel 8069: sub split_uri_for_cond {
                   8070:     my $uri=&deversion(&declutter(shift));
                   8071:     my @uriparts=split(/\//,$uri);
                   8072:     my $filename=pop(@uriparts);
                   8073:     my $pathname=join('/',@uriparts);
                   8074:     return ($pathname,$filename);
                   8075: }
1.232     www      8076: # --------------------------------------------------- Is a resource on the map?
                   8077: 
                   8078: sub is_on_map {
1.710     albertel 8079:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8080:     #Trying to find the conditional for the file
1.620     albertel 8081:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8082: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8083:     if ($match) {
1.289     bowersj2 8084: 	return (1,$1);
                   8085:     } else {
1.434     www      8086: 	return (0,0);
1.289     bowersj2 8087:     }
1.12      www      8088: }
                   8089: 
1.427     www      8090: # --------------------------------------------------------- Get symb from alias
                   8091: 
                   8092: sub get_symb_from_alias {
                   8093:     my $symb=shift;
                   8094:     my ($map,$resid,$url)=&decode_symb($symb);
                   8095: # Already is a symb
                   8096:     if ($url) { return $symb; }
                   8097: # Must be an alias
                   8098:     my $aliassymb='';
                   8099:     my %bighash;
1.620     albertel 8100:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8101:                             &GDBM_READER(),0640)) {
                   8102:         my $rid=$bighash{'mapalias_'.$symb};
                   8103: 	if ($rid) {
                   8104: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8105: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8106: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8107: 	}
                   8108:         untie %bighash;
                   8109:     }
                   8110:     return $aliassymb;
                   8111: }
                   8112: 
1.12      www      8113: # ----------------------------------------------------------------- Define Role
                   8114: 
                   8115: sub definerole {
                   8116:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  8117:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8118:     foreach my $role (split(':',$sysrole)) {
                   8119: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8120:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8121:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8122: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8123:                return "refused:s:$crole&$cqual"; 
                   8124:             }
                   8125:         }
1.191     harris41 8126:     }
1.800     albertel 8127:     foreach my $role (split(':',$domrole)) {
                   8128: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8129:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8130:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8131: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8132:                return "refused:d:$crole&$cqual"; 
                   8133:             }
                   8134:         }
1.191     harris41 8135:     }
1.800     albertel 8136:     foreach my $role (split(':',$courole)) {
                   8137: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8138:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8139:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8140: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8141:                return "refused:c:$crole&$cqual"; 
                   8142:             }
                   8143:         }
1.191     harris41 8144:     }
1.1172.2.84  raeburn  8145:     my $uhome;
                   8146:     if (($uname ne '') && ($udom ne '')) {
                   8147:         $uhome = &homeserver($uname,$udom);
                   8148:         return $uhome if ($uhome eq 'no_host');
                   8149:     } else {
                   8150:         $uname = $env{'user.name'};
                   8151:         $udom = $env{'user.domain'};
                   8152:         $uhome = $env{'user.home'};
                   8153:     }
1.620     albertel 8154:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  8155:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8156:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  8157:     return reply($command,$uhome);
1.12      www      8158:   } else {
                   8159:     return 'refused';
                   8160:   }
1.105     harris41 8161: }
                   8162: 
                   8163: # ---------------- Make a metadata query against the network of library servers
                   8164: 
                   8165: sub metadata_query {
1.1172.2.33  raeburn  8166:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8167:     my %rhash;
1.845     albertel 8168:     my %libserv = &all_library();
1.244     matthew  8169:     my @server_list = (defined($server_array) ? @$server_array
                   8170:                                               : keys(%libserv) );
                   8171:     for my $server (@server_list) {
1.1172.2.33  raeburn  8172:         my $domains = '';
                   8173:         if (ref($domains_hash) eq 'HASH') {
                   8174:             $domains = $domains_hash->{$server};    
                   8175:         }
1.118     harris41 8176: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  8177: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8178: 	    $rhash{$server}=$reply;
                   8179: 	}
                   8180: 	else {
                   8181: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  8182: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8183: 			     $server);
                   8184: 	    $rhash{$server}=$reply;
                   8185: 	}
1.112     harris41 8186:     }
1.118     harris41 8187:     return \%rhash;
1.240     www      8188: }
                   8189: 
                   8190: # ----------------------------------------- Send log queries and wait for reply
                   8191: 
                   8192: sub log_query {
                   8193:     my ($uname,$udom,$query,%filters)=@_;
                   8194:     my $uhome=&homeserver($uname,$udom);
                   8195:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8196:     my $uhost=&hostname($uhome);
1.800     albertel 8197:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8198:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8199:                        $uhome);
1.479     albertel 8200:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8201:     return get_query_reply($queryid);
                   8202: }
                   8203: 
1.818     raeburn  8204: # -------------------------- Update MySQL table for portfolio file
                   8205: 
                   8206: sub update_portfolio_table {
1.821     raeburn  8207:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8208:     if ($group ne '') {
                   8209:         $file_name =~s /^\Q$group\E//;
                   8210:     }
1.818     raeburn  8211:     my $homeserver = &homeserver($uname,$udom);
                   8212:     my $queryid=
1.821     raeburn  8213:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8214:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8215:     my $reply = &get_query_reply($queryid);
                   8216:     return $reply;
                   8217: }
                   8218: 
1.899     raeburn  8219: # -------------------------- Update MySQL allusers table
                   8220: 
                   8221: sub update_allusers_table {
                   8222:     my ($uname,$udom,$names) = @_;
                   8223:     my $homeserver = &homeserver($uname,$udom);
                   8224:     my $queryid=
                   8225:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8226:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8227:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8228:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8229:                'generation='.&escape($names->{'generation'}).'%%'.
                   8230:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8231:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8232:     return;
1.899     raeburn  8233: }
                   8234: 
1.508     raeburn  8235: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8236: 
                   8237: sub fetch_enrollment_query {
1.511     raeburn  8238:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  8239:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8240:     my $maxtries = 1;
1.508     raeburn  8241:     if ($context eq 'automated') {
                   8242:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  8243:         $sleep = 2;
                   8244:         $loopmax = 100;
1.547     raeburn  8245:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8246:     } else {
                   8247:         $homeserver = &homeserver($cnum,$dom);
                   8248:     }
1.838     albertel 8249:     my $host=&hostname($homeserver);
1.506     raeburn  8250:     my $cmd = '';
1.1000    raeburn  8251:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8252:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8253:     }
                   8254:     $cmd =~ s/%%$//;
                   8255:     $cmd = &escape($cmd);
                   8256:     my $query = 'fetchenrollment';
1.620     albertel 8257:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8258:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8259:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8260:         return 'error: '.$queryid;
                   8261:     }
1.1172.2.93  raeburn  8262:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8263:     my $tries = 1;
                   8264:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  8265:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8266:         $tries ++;
                   8267:     }
1.526     raeburn  8268:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8269:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8270:     } else {
1.901     albertel 8271:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  8272:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8273:             foreach my $line (@responses) {
                   8274:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8275:                 $$replyref{$key} = $value;
                   8276:             }
                   8277:         } else {
1.1117    foxr     8278:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8279:             foreach my $line (@responses) {
                   8280:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8281:                 $$replyref{$key} = $value;
                   8282:                 if ($value > 0) {
1.800     albertel 8283:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8284:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8285:                         my $destname = $pathname.'/'.$filename;
                   8286:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8287:                         if ($xml_classlist =~ /^error/) {
                   8288:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8289:                         } else {
1.1172.2.96  raeburn  8290:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8291:                                 print FILE &unescape($xml_classlist);
                   8292:                                 close(FILE);
1.526     raeburn  8293:                             } else {
                   8294:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8295:                             }
                   8296:                         }
                   8297:                     }
                   8298:                 }
                   8299:             }
                   8300:         }
                   8301:         return 'ok';
                   8302:     }
                   8303:     return 'error';
                   8304: }
                   8305: 
1.242     www      8306: sub get_query_reply {
1.1172.2.79  raeburn  8307:     my ($queryid,$sleep,$loopmax) = @_;
                   8308:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8309:         $sleep = 0.2;
                   8310:     }
                   8311:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8312:         $loopmax = 100;
                   8313:     }
1.1117    foxr     8314:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8315:     my $reply='';
1.1172.2.79  raeburn  8316:     for (1..$loopmax) {
                   8317: 	sleep($sleep);
1.240     www      8318:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  8319: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8320: 		$reply = join('',<$fh>);
                   8321: 		close($fh);
1.240     www      8322: 	   } else { return 'error: reply_file_error'; }
1.242     www      8323:            return &unescape($reply);
                   8324: 	}
1.240     www      8325:     }
1.242     www      8326:     return 'timeout:'.$queryid;
1.240     www      8327: }
                   8328: 
                   8329: sub courselog_query {
1.241     www      8330: #
                   8331: # possible filters:
                   8332: # url: url or symb
                   8333: # username
                   8334: # domain
                   8335: # action: view, submit, grade
                   8336: # start: timestamp
                   8337: # end: timestamp
                   8338: #
1.240     www      8339:     my (%filters)=@_;
1.620     albertel 8340:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8341:     if ($filters{'url'}) {
                   8342: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8343:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8344:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8345:     }
1.620     albertel 8346:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8347:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8348:     return &log_query($cname,$cdom,'courselog',%filters);
                   8349: }
                   8350: 
                   8351: sub userlog_query {
1.858     raeburn  8352: #
                   8353: # possible filters:
                   8354: # action: log check role
                   8355: # start: timestamp
                   8356: # end: timestamp
                   8357: #
1.240     www      8358:     my ($uname,$udom,%filters)=@_;
                   8359:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8360: }
                   8361: 
1.506     raeburn  8362: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8363: 
                   8364: sub auto_run {
1.508     raeburn  8365:     my ($cnum,$cdom) = @_;
1.876     raeburn  8366:     my $response = 0;
                   8367:     my $settings;
                   8368:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8369:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8370:         $settings = $domconfig{'autoenroll'};
                   8371:         if ($settings->{'run'} eq '1') {
                   8372:             $response = 1;
                   8373:         }
                   8374:     } else {
1.934     raeburn  8375:         my $homeserver;
                   8376:         if (&is_course($cdom,$cnum)) {
                   8377:             $homeserver = &homeserver($cnum,$cdom);
                   8378:         } else {
                   8379:             $homeserver = &domain($cdom,'primary');
                   8380:         }
                   8381:         if ($homeserver ne 'no_host') {
                   8382:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8383:         }
1.876     raeburn  8384:     }
1.506     raeburn  8385:     return $response;
                   8386: }
1.776     albertel 8387: 
1.506     raeburn  8388: sub auto_get_sections {
1.508     raeburn  8389:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8390:     my $homeserver;
                   8391:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8392:         $homeserver = &homeserver($cnum,$cdom);
                   8393:     }
                   8394:     if (!defined($homeserver)) { 
                   8395:         if ($cdom =~ /^$match_domain$/) {
                   8396:             $homeserver = &domain($cdom,'primary');
                   8397:         }
                   8398:     }
                   8399:     my @secs;
                   8400:     if (defined($homeserver)) {
                   8401:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8402:         unless ($response eq 'refused') {
                   8403:             @secs = split(/:/,$response);
                   8404:         }
1.506     raeburn  8405:     }
                   8406:     return @secs;
                   8407: }
1.776     albertel 8408: 
1.506     raeburn  8409: sub auto_new_course {
1.1099    raeburn  8410:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8411:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8412:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8413:     return $response;
                   8414: }
1.776     albertel 8415: 
1.506     raeburn  8416: sub auto_validate_courseID {
1.508     raeburn  8417:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8418:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8419:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8420:     return $response;
                   8421: }
1.776     albertel 8422: 
1.1007    raeburn  8423: sub auto_validate_instcode {
1.1020    raeburn  8424:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8425:     my ($homeserver,$response);
                   8426:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8427:         $homeserver = &homeserver($cnum,$cdom);
                   8428:     }
                   8429:     if (!defined($homeserver)) {
                   8430:         if ($cdom =~ /^$match_domain$/) {
                   8431:             $homeserver = &domain($cdom,'primary');
                   8432:         }
                   8433:     }
1.1065    raeburn  8434:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8435:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  8436:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8437:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8438: }
                   8439: 
1.506     raeburn  8440: sub auto_create_password {
1.873     raeburn  8441:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8442:     my ($homeserver,$response);
1.506     raeburn  8443:     my $create_passwd = 0;
                   8444:     my $authchk = '';
1.873     raeburn  8445:     if ($udom =~ /^$match_domain$/) {
                   8446:         $homeserver = &domain($udom,'primary');
                   8447:     }
                   8448:     if ($homeserver eq '') {
                   8449:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8450:             $homeserver = &homeserver($cnum,$cdom);
                   8451:         }
                   8452:     }
                   8453:     if ($homeserver eq '') {
                   8454:         $authchk = 'nodomain';
1.506     raeburn  8455:     } else {
1.873     raeburn  8456:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8457:         if ($response eq 'refused') {
                   8458:             $authchk = 'refused';
                   8459:         } else {
1.901     albertel 8460:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8461:         }
1.506     raeburn  8462:     }
                   8463:     return ($authparam,$create_passwd,$authchk);
                   8464: }
                   8465: 
1.706     raeburn  8466: sub auto_photo_permission {
                   8467:     my ($cnum,$cdom,$students) = @_;
                   8468:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8469:     my ($outcome,$perm_reqd,$conditions) = 
                   8470: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8471:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8472: 	return (undef,undef);
                   8473:     }
1.706     raeburn  8474:     return ($outcome,$perm_reqd,$conditions);
                   8475: }
                   8476: 
                   8477: sub auto_checkphotos {
                   8478:     my ($uname,$udom,$pid) = @_;
                   8479:     my $homeserver = &homeserver($uname,$udom);
                   8480:     my ($result,$resulttype);
                   8481:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8482: 				   &escape($uname).':'.&escape($pid),
                   8483: 				   $homeserver));
1.709     albertel 8484:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8485: 	return (undef,undef);
                   8486:     }
1.706     raeburn  8487:     if ($outcome) {
                   8488:         ($result,$resulttype) = split(/:/,$outcome);
                   8489:     } 
                   8490:     return ($result,$resulttype);
                   8491: }
                   8492: 
                   8493: sub auto_photochoice {
                   8494:     my ($cnum,$cdom) = @_;
                   8495:     my $homeserver = &homeserver($cnum,$cdom);
                   8496:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8497: 						       &escape($cdom),
                   8498: 						       $homeserver)));
1.709     albertel 8499:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8500: 	return (undef,undef);
                   8501:     }
1.706     raeburn  8502:     return ($update,$comment);
                   8503: }
                   8504: 
                   8505: sub auto_photoupdate {
                   8506:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8507:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8508:     my $host=&hostname($homeserver);
1.706     raeburn  8509:     my $cmd = '';
                   8510:     my $maxtries = 1;
1.800     albertel 8511:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8512:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8513:     }
                   8514:     $cmd =~ s/%%$//;
                   8515:     $cmd = &escape($cmd);
                   8516:     my $query = 'institutionalphotos';
                   8517:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8518:     unless ($queryid=~/^\Q$host\E\_/) {
                   8519:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8520:         return 'error: '.$queryid;
                   8521:     }
                   8522:     my $reply = &get_query_reply($queryid);
                   8523:     my $tries = 1;
                   8524:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8525:         $reply = &get_query_reply($queryid);
                   8526:         $tries ++;
                   8527:     }
                   8528:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8529:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8530:     } else {
                   8531:         my @responses = split(/:/,$reply);
                   8532:         my $outcome = shift(@responses); 
                   8533:         foreach my $item (@responses) {
                   8534:             my ($key,$value) = split(/=/,$item);
                   8535:             $$photo{$key} = $value;
                   8536:         }
                   8537:         return $outcome;
                   8538:     }
                   8539:     return 'error';
                   8540: }
                   8541: 
1.521     raeburn  8542: sub auto_instcode_format {
1.793     albertel 8543:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8544: 	$cat_order) = @_;
1.521     raeburn  8545:     my $courses = '';
1.772     raeburn  8546:     my @homeservers;
1.521     raeburn  8547:     if ($caller eq 'global') {
1.841     albertel 8548: 	my %servers = &get_servers($codedom,'library');
                   8549: 	foreach my $tryserver (keys(%servers)) {
                   8550: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8551: 		push(@homeservers,$tryserver);
                   8552: 	    }
1.584     raeburn  8553:         }
1.1022    raeburn  8554:     } elsif ($caller eq 'requests') {
                   8555:         if ($codedom =~ /^$match_domain$/) {
                   8556:             my $chome = &domain($codedom,'primary');
                   8557:             unless ($chome eq 'no_host') {
                   8558:                 push(@homeservers,$chome);
                   8559:             }
                   8560:         }
1.521     raeburn  8561:     } else {
1.772     raeburn  8562:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8563:     }
1.793     albertel 8564:     foreach my $code (keys(%{$instcodes})) {
                   8565:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8566:     }
                   8567:     chop($courses);
1.772     raeburn  8568:     my $ok_response = 0;
                   8569:     my $response;
                   8570:     while (@homeservers > 0 && $ok_response == 0) {
                   8571:         my $server = shift(@homeservers); 
                   8572:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8573:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8574:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8575: 		split(/:/,$response);
1.772     raeburn  8576:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8577:             push(@{$codetitles},&str2array($codetitles_str));
                   8578:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8579:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8580:             $ok_response = 1;
                   8581:         }
                   8582:     }
                   8583:     if ($ok_response) {
1.521     raeburn  8584:         return 'ok';
1.772     raeburn  8585:     } else {
                   8586:         return $response;
1.521     raeburn  8587:     }
                   8588: }
                   8589: 
1.792     raeburn  8590: sub auto_instcode_defaults {
                   8591:     my ($domain,$returnhash,$code_order) = @_;
                   8592:     my @homeservers;
1.841     albertel 8593: 
                   8594:     my %servers = &get_servers($domain,'library');
                   8595:     foreach my $tryserver (keys(%servers)) {
                   8596: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8597: 	    push(@homeservers,$tryserver);
                   8598: 	}
1.792     raeburn  8599:     }
1.841     albertel 8600: 
1.792     raeburn  8601:     my $response;
1.841     albertel 8602:     foreach my $server (@homeservers) {
1.792     raeburn  8603:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8604:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8605: 	
                   8606: 	foreach my $pair (split(/\&/,$response)) {
                   8607: 	    my ($name,$value)=split(/\=/,$pair);
                   8608: 	    if ($name eq 'code_order') {
                   8609: 		@{$code_order} = split(/\&/,&unescape($value));
                   8610: 	    } else {
                   8611: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8612: 	    }
                   8613: 	}
                   8614: 	return 'ok';
1.792     raeburn  8615:     }
1.841     albertel 8616: 
                   8617:     return $response;
1.1003    raeburn  8618: }
                   8619: 
                   8620: sub auto_possible_instcodes {
1.1007    raeburn  8621:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8622:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8623:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8624:         return;
                   8625:     }
1.1003    raeburn  8626:     my (@homeservers,$uhome);
                   8627:     if (defined(&domain($domain,'primary'))) {
                   8628:         $uhome=&domain($domain,'primary');
                   8629:         push(@homeservers,&domain($domain,'primary'));
                   8630:     } else {
                   8631:         my %servers = &get_servers($domain,'library');
                   8632:         foreach my $tryserver (keys(%servers)) {
                   8633:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8634:                 push(@homeservers,$tryserver);
                   8635:             }
                   8636:         }
                   8637:     }
                   8638:     my $response;
                   8639:     foreach my $server (@homeservers) {
                   8640:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8641:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8642:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8643:             split(':',$response);
                   8644:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8645:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8646:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8647:             my ($name,$value)=split('=',$item);
                   8648:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8649:         }
                   8650:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8651:             my ($name,$value)=split('=',$item);
                   8652:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8653:         }
                   8654:         return 'ok';
                   8655:     }
                   8656:     return $response;
                   8657: }
1.792     raeburn  8658: 
1.1010    raeburn  8659: sub auto_courserequest_checks {
                   8660:     my ($dom) = @_;
1.1020    raeburn  8661:     my ($homeserver,%validations);
                   8662:     if ($dom =~ /^$match_domain$/) {
                   8663:         $homeserver = &domain($dom,'primary');
                   8664:     }
                   8665:     unless ($homeserver eq 'no_host') {
                   8666:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8667:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8668:             my @items = split(/&/,$response);
                   8669:             foreach my $item (@items) {
                   8670:                 my ($key,$value) = split('=',$item);
                   8671:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8672:             }
                   8673:         }
                   8674:     }
1.1010    raeburn  8675:     return %validations; 
                   8676: }
                   8677: 
1.1020    raeburn  8678: sub auto_courserequest_validation {
1.1172.2.43  raeburn  8679:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8680:     my ($homeserver,$response);
                   8681:     if ($dom =~ /^$match_domain$/) {
                   8682:         $homeserver = &domain($dom,'primary');
                   8683:     }
1.1172.2.43  raeburn  8684:     unless ($homeserver eq 'no_host') {
                   8685:         my $customdata;
                   8686:         if (ref($custominfo) eq 'HASH') {
                   8687:             $customdata = &freeze_escape($custominfo);
                   8688:         }
1.1020    raeburn  8689:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8690:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  8691:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8692:                                     $customdata,$homeserver));
1.1020    raeburn  8693:     }
                   8694:     return $response;
                   8695: }
                   8696: 
1.777     albertel 8697: sub auto_validate_class_sec {
1.918     raeburn  8698:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8699:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8700:     my $ownerlist;
                   8701:     if (ref($owners) eq 'ARRAY') {
                   8702:         $ownerlist = join(',',@{$owners});
                   8703:     } else {
                   8704:         $ownerlist = $owners;
                   8705:     }
1.773     raeburn  8706:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8707:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8708:     return $response;
                   8709: }
                   8710: 
1.1172.2.94  raeburn  8711: sub auto_validate_instclasses {
                   8712:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   8713:     my ($homeserver,%validations);
                   8714:     $homeserver = &homeserver($cnum,$cdom);
                   8715:     unless ($homeserver eq 'no_host') {
                   8716:         my $ownerlist;
                   8717:         if (ref($owners) eq 'ARRAY') {
                   8718:             $ownerlist = join(',',@{$owners});
                   8719:         } else {
                   8720:             $ownerlist = $owners;
                   8721:         }
                   8722:         if (ref($classesref) eq 'HASH') {
                   8723:             my $classes = &freeze_escape($classesref);
                   8724:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   8725:                                 ':'.$cdom.':'.$classes,$homeserver);
                   8726:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8727:                 my @items = split(/&/,$response);
                   8728:                 foreach my $item (@items) {
                   8729:                     my ($key,$value) = split('=',$item);
                   8730:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   8731:                 }
                   8732:             }
                   8733:         }
                   8734:     }
                   8735:     return %validations;
                   8736: }
                   8737: 
1.1172.2.38  raeburn  8738: sub auto_crsreq_update {
                   8739:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  8740:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  8741:     my ($homeserver,%crsreqresponse);
                   8742:     if ($cdom =~ /^$match_domain$/) {
                   8743:         $homeserver = &domain($cdom,'primary');
                   8744:     }
                   8745:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8746:         my $info;
                   8747:         if (ref($inbound) eq 'HASH') {
                   8748:             $info = &freeze_escape($inbound);
                   8749:         }
                   8750:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8751:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8752:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  8753:                             &escape($title).':'.&escape($code).':'.
                   8754:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  8755:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8756:             my @items = split(/&/,$response);
                   8757:             foreach my $item (@items) {
                   8758:                 my ($key,$value) = split('=',$item);
                   8759:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8760:             }
                   8761:         }
                   8762:     }
                   8763:     return \%crsreqresponse;
                   8764: }
                   8765: 
1.1172.2.78  raeburn  8766: sub auto_export_grades {
                   8767:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   8768:     my ($homeserver,%exportresponse);
                   8769:     if ($cdom =~ /^$match_domain$/) {
                   8770:         $homeserver = &domain($cdom,'primary');
                   8771:     }
                   8772:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8773:         my $info;
                   8774:         if (ref($inforef) eq 'HASH') {
                   8775:             $info = &freeze_escape($inforef);
                   8776:         }
                   8777:         if (ref($gradesref) eq 'HASH') {
                   8778:             my $grades = &freeze_escape($gradesref);
                   8779:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   8780:                                 $info.':'.$grades,$homeserver);
                   8781:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   8782:                 my @items = split(/&/,$response);
                   8783:                 foreach my $item (@items) {
                   8784:                     my ($key,$value) = split('=',$item);
                   8785:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   8786:                 }
                   8787:             }
                   8788:         }
                   8789:     }
                   8790:     return \%exportresponse;
                   8791: }
                   8792: 
1.1172.2.68  raeburn  8793: sub check_instcode_cloning {
                   8794:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   8795:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8796:         return;
                   8797:     }
                   8798:     my $canclone;
                   8799:     if (@{$code_order} > 0) {
                   8800:         my $instcoderegexp ='^';
                   8801:         my @clonecodes = split(/\&/,$cloner);
                   8802:         foreach my $item (@{$code_order}) {
                   8803:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   8804:                 foreach my $pair (@clonecodes) {
                   8805:                     my ($key,$val) = split(/\=/,$pair,2);
                   8806:                     $val = &unescape($val);
                   8807:                     if ($key eq $item) {
                   8808:                         $instcoderegexp .= '('.$val.')';
                   8809:                         last;
                   8810:                     }
                   8811:                 }
                   8812:             } else {
                   8813:                 $instcoderegexp .= $codedefaults->{$item};
                   8814:             }
                   8815:         }
                   8816:         $instcoderegexp .= '$';
                   8817:         my (@from,@to);
                   8818:         eval {
                   8819:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8820:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8821:         };
                   8822:         if ((@from > 0) && (@to > 0)) {
                   8823:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8824:             if (!@diffs) {
                   8825:                 $canclone = 1;
                   8826:             }
                   8827:         }
                   8828:     }
                   8829:     return $canclone;
                   8830: }
                   8831: 
                   8832: sub default_instcode_cloning {
                   8833:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   8834:     my (%codedefaults,@code_order,$canclone);
                   8835:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   8836:         %codedefaults = %{$codedefaultsref};
                   8837:         @code_order = @{$codeorderref};
                   8838:     } elsif ($clonedom) {
                   8839:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   8840:     }
                   8841:     if (($domdefclone) && (@code_order)) {
                   8842:         my @clonecodes = split(/\+/,$domdefclone);
                   8843:         my $instcoderegexp ='^';
                   8844:         foreach my $item (@code_order) {
                   8845:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   8846:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   8847:             } else {
                   8848:                 $instcoderegexp .= $codedefaults{$item};
                   8849:             }
                   8850:         }
                   8851:         $instcoderegexp .= '$';
                   8852:         my (@from,@to);
                   8853:         eval {
                   8854:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8855:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8856:         };
                   8857:         if ((@from > 0) && (@to > 0)) {
                   8858:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8859:             if (!@diffs) {
                   8860:                 $canclone = 1;
                   8861:             }
                   8862:         }
                   8863:     }
                   8864:     return $canclone;
                   8865: }
                   8866: 
1.679     raeburn  8867: # ------------------------------------------------------- Course Group routines
                   8868: 
                   8869: sub get_coursegroups {
1.809     raeburn  8870:     my ($cdom,$cnum,$group,$namespace) = @_;
                   8871:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  8872: }
                   8873: 
1.679     raeburn  8874: sub modify_coursegroup {
                   8875:     my ($cdom,$cnum,$groupsettings) = @_;
                   8876:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   8877: }
                   8878: 
1.809     raeburn  8879: sub toggle_coursegroup_status {
                   8880:     my ($cdom,$cnum,$group,$action) = @_;
                   8881:     my ($from_namespace,$to_namespace);
                   8882:     if ($action eq 'delete') {
                   8883:         $from_namespace = 'coursegroups';
                   8884:         $to_namespace = 'deleted_groups';
                   8885:     } else {
                   8886:         $from_namespace = 'deleted_groups';
                   8887:         $to_namespace = 'coursegroups';
                   8888:     }
                   8889:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  8890:     if (my $tmp = &error(%curr_group)) {
                   8891:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   8892:         return ('read error',$tmp);
                   8893:     } else {
                   8894:         my %savedsettings = %curr_group; 
1.809     raeburn  8895:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  8896:         my $deloutcome;
                   8897:         if ($result eq 'ok') {
1.809     raeburn  8898:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  8899:         } else {
                   8900:             return ('write error',$result);
                   8901:         }
                   8902:         if ($deloutcome eq 'ok') {
                   8903:             return 'ok';
                   8904:         } else {
                   8905:             return ('delete error',$deloutcome);
                   8906:         }
                   8907:     }
                   8908: }
                   8909: 
1.679     raeburn  8910: sub modify_group_roles {
1.957     raeburn  8911:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  8912:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   8913:     my $role = 'gr/'.&escape($userprivs);
                   8914:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  8915:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  8916:     if ($result eq 'ok') {
                   8917:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   8918:     }
1.679     raeburn  8919:     return $result;
                   8920: }
                   8921: 
                   8922: sub modify_coursegroup_membership {
                   8923:     my ($cdom,$cnum,$membership) = @_;
                   8924:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   8925:     return $result;
                   8926: }
                   8927: 
1.682     raeburn  8928: sub get_active_groups {
                   8929:     my ($udom,$uname,$cdom,$cnum) = @_;
                   8930:     my $now = time;
                   8931:     my %groups = ();
                   8932:     foreach my $key (keys(%env)) {
1.811     albertel 8933:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  8934:             my ($start,$end) = split(/\./,$env{$key});
                   8935:             if (($end!=0) && ($end<$now)) { next; }
                   8936:             if (($start!=0) && ($start>$now)) { next; }
                   8937:             if ($1 eq $cdom && $2 eq $cnum) {
                   8938:                 $groups{$3} = $env{$key} ;
                   8939:             }
                   8940:         }
                   8941:     }
                   8942:     return %groups;
                   8943: }
                   8944: 
1.683     raeburn  8945: sub get_group_membership {
                   8946:     my ($cdom,$cnum,$group) = @_;
                   8947:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   8948: }
                   8949: 
                   8950: sub get_users_groups {
                   8951:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  8952:     my @usersgroups;
1.683     raeburn  8953:     my $cachetime=1800;
                   8954: 
                   8955:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  8956:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   8957:     if (defined($cached)) {
1.734     albertel 8958:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  8959:     } else {  
                   8960:         $grouplist = '';
1.816     raeburn  8961:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  8962:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  8963:         my $access_end = $env{'course.'.$courseid.
                   8964:                               '.default_enrollment_end_date'};
                   8965:         my $now = time;
                   8966:         foreach my $key (keys(%roleshash)) {
                   8967:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   8968:                 my $group = $1;
                   8969:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   8970:                     my $start = $2;
                   8971:                     my $end = $1;
                   8972:                     if ($start == -1) { next; } # deleted from group
                   8973:                     if (($start!=0) && ($start>$now)) { next; }
                   8974:                     if (($end!=0) && ($end<$now)) {
                   8975:                         if ($access_end && $access_end < $now) {
                   8976:                             if ($access_end - $end < 86400) {
                   8977:                                 push(@usersgroups,$group);
1.733     raeburn  8978:                             }
                   8979:                         }
1.817     raeburn  8980:                         next;
1.733     raeburn  8981:                     }
1.817     raeburn  8982:                     push(@usersgroups,$group);
1.683     raeburn  8983:                 }
                   8984:             }
                   8985:         }
1.817     raeburn  8986:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8987:         $grouplist = join(':',@usersgroups);
                   8988:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8989:     }
1.733     raeburn  8990:     return @usersgroups;
1.683     raeburn  8991: }
                   8992: 
                   8993: sub devalidate_getgroups_cache {
                   8994:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8995:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8996: 
1.683     raeburn  8997:     my $hashid="$udom:$uname:$courseid";
                   8998:     &devalidate_cache_new('getgroups',$hashid);
                   8999: }
                   9000: 
1.12      www      9001: # ------------------------------------------------------------------ Plain Text
                   9002: 
                   9003: sub plaintext {
1.988     raeburn  9004:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9005:     if ($short =~ m{^cr/}) {
1.758     albertel 9006: 	return (split('/',$short))[-1];
                   9007:     }
1.742     raeburn  9008:     if (!defined($cid)) {
                   9009:         $cid = $env{'request.course.id'};
                   9010:     }
                   9011:     my %rolenames = (
1.1008    raeburn  9012:                       Course    => 'std',
                   9013:                       Community => 'alt1',
1.742     raeburn  9014:                     );
1.1037    raeburn  9015:     if ($cid ne '') {
                   9016:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9017:             unless ($forcedefault) {
                   9018:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9019:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9020:                 return &Apache::lonlocal::mt($roletext);
                   9021:             }
                   9022:         }
                   9023:     }
                   9024:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9025:         (defined($rolenames{$type})) && 
                   9026:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9027:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9028:     } elsif ($cid ne '') {
                   9029:         my $crstype = $env{'course.'.$cid.'.type'};
                   9030:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9031:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9032:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9033:         }
1.742     raeburn  9034:     }
1.1037    raeburn  9035:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9036: }
                   9037: 
                   9038: # ----------------------------------------------------------------- Assign Role
                   9039: 
                   9040: sub assignrole {
1.957     raeburn  9041:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9042:         $context)=@_;
1.21      www      9043:     my $mrole;
                   9044:     if ($role =~ /^cr\//) {
1.393     www      9045:         my $cwosec=$url;
1.811     albertel 9046:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9047: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9048:            my $refused = 1;
                   9049:            if ($context eq 'requestcourses') {
                   9050:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9051:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9052:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9053:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9054:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9055:                            if ($crsenv{'internal.courseowner'} eq
                   9056:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9057:                                $refused = '';
                   9058:                            }
                   9059:                        }
                   9060:                    }
                   9061:                }
                   9062:            }
                   9063:            if ($refused) {
                   9064:                &logthis('Refused custom assignrole: '.
                   9065:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9066:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9067:                return 'refused';
                   9068:            }
1.104     www      9069:         }
1.21      www      9070:         $mrole='cr';
1.678     raeburn  9071:     } elsif ($role =~ /^gr\//) {
                   9072:         my $cwogrp=$url;
1.811     albertel 9073:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9074:         unless (&allowed('mdg',$cwogrp)) {
                   9075:             &logthis('Refused group assignrole: '.
                   9076:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9077:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9078:             return 'refused';
                   9079:         }
                   9080:         $mrole='gr';
1.21      www      9081:     } else {
1.82      www      9082:         my $cwosec=$url;
1.811     albertel 9083:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9084:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9085:             my $refused;
                   9086:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9087:                 if (!(&allowed('c'.$role,$url))) {
                   9088:                     $refused = 1;
                   9089:                 }
                   9090:             } else {
                   9091:                 $refused = 1;
                   9092:             }
1.947     raeburn  9093:             if ($refused) {
1.1045    raeburn  9094:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9095:                 if (!$selfenroll && $context eq 'course') {
                   9096:                     my %crsenv;
                   9097:                     if ($role eq 'cc' || $role eq 'co') {
                   9098:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9099:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9100:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9101:                                 if ($crsenv{'internal.courseowner'} eq 
                   9102:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9103:                                     $refused = '';
                   9104:                                 }
                   9105:                             }
                   9106:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9107:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9108:                                 if ($crsenv{'internal.courseowner'} eq 
                   9109:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9110:                                     $refused = '';
                   9111:                                 }
                   9112:                             }
                   9113:                         }
                   9114:                     }
                   9115:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  9116:                     $refused = '';
1.1017    raeburn  9117:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9118:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9119:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9120:                         my $wrongcc;
                   9121:                         if ($cnum =~ /^$match_community$/) {
                   9122:                             $wrongcc = 1 if ($role eq 'cc');
                   9123:                         } else {
                   9124:                             $wrongcc = 1 if ($role eq 'co');
                   9125:                         }
                   9126:                         unless ($wrongcc) {
                   9127:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9128:                             if ($crsenv{'internal.courseowner'} eq 
                   9129:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9130:                                 $refused = '';
                   9131:                             }
1.1017    raeburn  9132:                         }
                   9133:                     }
1.1172.2.9  raeburn  9134:                 } elsif ($context eq 'requestauthor') {
                   9135:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   9136:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9137:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9138:                             $refused = '';
                   9139:                         } else {
                   9140:                             my %domdefaults = &get_domain_defaults($udom);
                   9141:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9142:                                 my $checkbystatus;
                   9143:                                 if ($env{'user.adv'}) {
                   9144:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9145:                                     if ($disposition eq 'automatic') {
                   9146:                                         $refused = '';
                   9147:                                     } elsif ($disposition eq '') {
                   9148:                                         $checkbystatus = 1;
                   9149:                                     }
                   9150:                                 } else {
                   9151:                                     $checkbystatus = 1;
                   9152:                                 }
                   9153:                                 if ($checkbystatus) {
                   9154:                                     if ($env{'environment.inststatus'}) {
                   9155:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9156:                                         foreach my $type (@inststatuses) {
                   9157:                                             if (($type ne '') &&
                   9158:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9159:                                                 $refused = '';
                   9160:                                             }
                   9161:                                         }
                   9162:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9163:                                         $refused = '';
                   9164:                                     }
                   9165:                                 }
                   9166:                             }
                   9167:                         }
                   9168:                     }
1.1017    raeburn  9169:                 }
                   9170:                 if ($refused) {
1.947     raeburn  9171:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9172:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9173: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9174:                     return 'refused';
                   9175:                 }
1.932     raeburn  9176:             }
1.1131    raeburn  9177:         } elsif ($role eq 'au') {
                   9178:             if ($url ne '/'.$udom.'/') {
                   9179:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9180:                          ' to assign author role for '.$uname.':'.$udom.
                   9181:                          ' in domain: '.$url.' refused (wrong domain).');
                   9182:                 return 'refused';
                   9183:             }
1.104     www      9184:         }
1.21      www      9185:         $mrole=$role;
                   9186:     }
1.620     albertel 9187:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9188:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9189:     if ($end) { $command.='_'.$end; }
1.21      www      9190:     if ($start) {
                   9191: 	if ($end) { 
1.81      www      9192:            $command.='_'.$start; 
1.21      www      9193:         } else {
1.81      www      9194:            $command.='_0_'.$start;
1.21      www      9195:         }
                   9196:     }
1.739     raeburn  9197:     my $origstart = $start;
                   9198:     my $origend = $end;
1.957     raeburn  9199:     my $delflag;
1.357     www      9200: # actually delete
                   9201:     if ($deleteflag) {
1.373     www      9202: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9203: # modify command to delete the role
1.620     albertel 9204:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9205:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9206: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9207: # set start and finish to negative values for userrolelog
                   9208:            $start=-1;
                   9209:            $end=-1;
1.957     raeburn  9210:            $delflag = 1;
1.357     www      9211:         }
                   9212:     }
                   9213: # send command
1.349     www      9214:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9215: # log new user role if status is ok
1.349     www      9216:     if ($answer eq 'ok') {
1.663     raeburn  9217: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  9218:         if (($role eq 'cc') || ($role eq 'in') ||
                   9219:             ($role eq 'ep') || ($role eq 'ad') ||
                   9220:             ($role eq 'ta') || ($role eq 'st') ||
                   9221:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9222:             ($role eq 'co')) {
1.1172.2.13  raeburn  9223: # for course roles, perform group memberships changes triggered by role change.
                   9224:             unless ($role =~ /^gr/) {
                   9225:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9226:                                                  $origstart,$selfenroll,$context);
                   9227:             }
1.1172.2.9  raeburn  9228:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9229:                            $selfenroll,$context);
                   9230:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  9231:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9232:                  ($role eq 'da')) {
1.1172.2.9  raeburn  9233:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9234:                            $context);
                   9235:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9236:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9237:                              $context);
                   9238:         }
1.1053    raeburn  9239:         if ($role eq 'cc') {
                   9240:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9241:         }
1.349     www      9242:     }
                   9243:     return $answer;
1.169     harris41 9244: }
                   9245: 
1.1053    raeburn  9246: sub autoupdate_coowners {
                   9247:     my ($url,$end,$start,$uname,$udom) = @_;
                   9248:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9249:     if (($cdom ne '') && ($cnum ne '')) {
                   9250:         my $now = time;
                   9251:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9252:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9253:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9254:             my $instcode = $coursehash{'internal.coursecode'};
                   9255:             if ($instcode ne '') {
1.1056    raeburn  9256:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9257:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9258:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9259:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9260:                         if ($result eq 'valid') {
                   9261:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9262:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9263:                                     push(@newcoowners,$coowner);
                   9264:                                 }
                   9265:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9266:                                     push(@newcoowners,$uname.':'.$udom);
                   9267:                                 }
                   9268:                                 @newcoowners = sort(@newcoowners);
                   9269:                             } else {
                   9270:                                 push(@newcoowners,$uname.':'.$udom);
                   9271:                             }
                   9272:                         } else {
                   9273:                             if ($coursehash{'internal.co-owners'}) {
                   9274:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9275:                                     unless ($coowner eq $uname.':'.$udom) {
                   9276:                                         push(@newcoowners,$coowner);
                   9277:                                     }
                   9278:                                 }
                   9279:                                 unless (@newcoowners > 0) {
                   9280:                                     $delcoowners = 1;
                   9281:                                     $coowners = '';
                   9282:                                 }
                   9283:                             }
                   9284:                         }
                   9285:                         if (@newcoowners || $delcoowners) {
                   9286:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9287:                                             $delcoowners,@newcoowners);
                   9288:                         }
                   9289:                     }
                   9290:                 }
                   9291:             }
                   9292:         }
                   9293:     }
                   9294: }
                   9295: 
                   9296: sub store_coowners {
                   9297:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9298:     my $cid = $cdom.'_'.$cnum;
                   9299:     my ($coowners,$delresult,$putresult);
                   9300:     if (@newcoowners) {
                   9301:         $coowners = join(',',@newcoowners);
                   9302:         my %coownershash = (
                   9303:                             'internal.co-owners' => $coowners,
                   9304:                            );
                   9305:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9306:         if ($putresult eq 'ok') {
                   9307:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9308:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9309:             }
                   9310:         }
                   9311:     }
                   9312:     if ($delcoowners) {
                   9313:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9314:         if ($delresult eq 'ok') {
                   9315:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9316:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9317:             }
                   9318:         }
                   9319:     }
                   9320:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9321:         my %crsinfo =
                   9322:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9323:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9324:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9325:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9326:         }
                   9327:     }
                   9328: }
                   9329: 
1.169     harris41 9330: # -------------------------------------------------- Modify user authentication
1.197     www      9331: # Overrides without validation
                   9332: 
1.169     harris41 9333: sub modifyuserauth {
                   9334:     my ($udom,$uname,$umode,$upass)=@_;
                   9335:     my $uhome=&homeserver($uname,$udom);
1.197     www      9336:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   9337:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9338:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9339:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9340:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9341: 		     &escape($upass),$uhome);
1.620     albertel 9342:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9343:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9344:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9345:     &log($udom,,$uname,$uhome,
1.620     albertel 9346:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9347:                                      $env{'user.name'}.', '.$umode.
1.197     www      9348:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9349:     unless ($reply eq 'ok') {
1.197     www      9350:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9351: 	return 'error: '.$reply;
                   9352:     }   
1.170     harris41 9353:     return 'ok';
1.80      www      9354: }
                   9355: 
1.81      www      9356: # --------------------------------------------------------------- Modify a user
1.80      www      9357: 
1.81      www      9358: sub modifyuser {
1.206     matthew  9359:     my ($udom,    $uname, $uid,
                   9360:         $umode,   $upass, $first,
                   9361:         $middle,  $last,  $gene,
1.1058    raeburn  9362:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9363:     $udom= &LONCAPA::clean_domain($udom);
                   9364:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9365:     my $showcandelete = 'none';
                   9366:     if (ref($candelete) eq 'ARRAY') {
                   9367:         if (@{$candelete} > 0) {
                   9368:             $showcandelete = join(', ',@{$candelete});
                   9369:         }
                   9370:     }
1.81      www      9371:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9372:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9373: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9374:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9375:                                      ' desiredhome not specified'). 
1.620     albertel 9376:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9377:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9378:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9379:     my $newuser;
                   9380:     if ($uhome eq 'no_host') {
                   9381:         $newuser = 1;
                   9382:     }
1.80      www      9383: # ----------------------------------------------------------------- Create User
1.406     albertel 9384:     if (($uhome eq 'no_host') && 
                   9385: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      9386:         my $unhome='';
1.844     albertel 9387:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9388:             $unhome = $desiredhome;
1.620     albertel 9389: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9390: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9391:         } else { # load balancing routine for determining $unhome
1.81      www      9392:             my $loadm=10000000;
1.841     albertel 9393: 	    my %servers = &get_servers($udom,'library');
                   9394: 	    foreach my $tryserver (keys(%servers)) {
                   9395: 		my $answer=reply('load',$tryserver);
                   9396: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9397: 		    $loadm=$answer;
                   9398: 		    $unhome=$tryserver;
                   9399: 		}
1.80      www      9400: 	    }
                   9401:         }
                   9402:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9403: 	    return 'error: unable to find a home server for '.$uname.
                   9404:                    ' in domain '.$udom;
1.80      www      9405:         }
                   9406:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9407:                          &escape($upass),$unhome);
                   9408: 	unless ($reply eq 'ok') {
                   9409:             return 'error: '.$reply;
                   9410:         }   
1.230     stredwic 9411:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9412:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9413: 	    return 'error: unable verify users home machine.';
1.80      www      9414:         }
1.209     matthew  9415:     }   # End of creation of new user
1.80      www      9416: # ---------------------------------------------------------------------- Add ID
                   9417:     if ($uid) {
                   9418:        $uid=~tr/A-Z/a-z/;
                   9419:        my %uidhash=&idrget($udom,$uname);
1.196     www      9420:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9421:          && (!$forceid)) {
1.80      www      9422: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9423: 	      return 'error: user id "'.$uid.'" does not match '.
                   9424:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9425:           }
                   9426:        } else {
                   9427: 	  &idput($udom,($uname => $uid));
                   9428:        }
                   9429:     }
                   9430: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9431:     my @tmp=&get('environment',
1.899     raeburn  9432: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9433:                     'permanentemail','inststatus'],
1.134     albertel 9434: 		   $udom,$uname);
1.1075    raeburn  9435:     my (%names,%oldnames);
1.313     matthew  9436:     if ($tmp[0] =~ m/^error:.*/) { 
                   9437:         %names=(); 
                   9438:     } else {
                   9439:         %names = @tmp;
1.1075    raeburn  9440:         %oldnames = %names;
1.313     matthew  9441:     }
1.388     www      9442: #
1.1058    raeburn  9443: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9444: # of users did not contain them), do not overwrite existing values
                   9445: # unless field is in $candelete array ref.  
                   9446: #
                   9447: 
                   9448:     my @fields = ('firstname','middlename','lastname','generation',
                   9449:                   'permanentemail','id');
                   9450:     my %newvalues;
                   9451:     if (ref($candelete) eq 'ARRAY') {
                   9452:         foreach my $field (@fields) {
                   9453:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9454:                 if ($field eq 'firstname') {
                   9455:                     $names{$field} = $first;
                   9456:                 } elsif ($field eq 'middlename') {
                   9457:                     $names{$field} = $middle;
                   9458:                 } elsif ($field eq 'lastname') {
                   9459:                     $names{$field} = $last;
                   9460:                 } elsif ($field eq 'generation') { 
                   9461:                     $names{$field} = $gene;
                   9462:                 } elsif ($field eq 'permanentemail') {
                   9463:                     $names{$field} = $email;
                   9464:                 } elsif ($field eq 'id') {
                   9465:                     $names{$field}  = $uid;
                   9466:                 }
                   9467:             }
                   9468:         }
                   9469:     }
1.388     www      9470:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9471:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9472:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9473:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9474:     if ($email) {
                   9475:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9476:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9477:     }
1.899     raeburn  9478:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9479:     if (defined($inststatus)) {
                   9480:         $names{'inststatus'} = '';
                   9481:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9482:         if (ref($usertypes) eq 'HASH') {
                   9483:             my @okstatuses; 
                   9484:             foreach my $item (split(/:/,$inststatus)) {
                   9485:                 if (defined($usertypes->{$item})) {
                   9486:                     push(@okstatuses,$item);  
                   9487:                 }
                   9488:             }
                   9489:             if (@okstatuses) {
                   9490:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9491:             }
                   9492:         }
                   9493:     }
1.1075    raeburn  9494:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9495:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9496:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9497:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9498:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9499:     } else {
                   9500:         $logmsg .= ' during self creation';
                   9501:     }
1.1075    raeburn  9502:     my $changed;
                   9503:     if ($newuser) {
                   9504:         $changed = 1;
                   9505:     } else {
                   9506:         foreach my $field (@fields) {
                   9507:             if ($names{$field} ne $oldnames{$field}) {
                   9508:                 $changed = 1;
                   9509:                 last;
                   9510:             }
                   9511:         }
                   9512:     }
                   9513:     unless ($changed) {
                   9514:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9515:         &logthis($logmsg);
                   9516:         return 'ok';
                   9517:     }
                   9518:     my $reply = &put('environment', \%names, $udom,$uname);
                   9519:     if ($reply ne 'ok') { 
                   9520:         return 'error: '.$reply;
                   9521:     }
1.1087    raeburn  9522:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9523:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9524:     }
1.1075    raeburn  9525:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9526:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9527:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9528:     &logthis($logmsg);
1.134     albertel 9529:     return 'ok';
1.80      www      9530: }
                   9531: 
1.81      www      9532: # -------------------------------------------------------------- Modify student
1.80      www      9533: 
1.81      www      9534: sub modifystudent {
                   9535:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9536:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  9537:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9538:     if (!$cid) {
1.620     albertel 9539: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9540: 	    return 'not_in_class';
                   9541: 	}
1.80      www      9542:     }
                   9543: # --------------------------------------------------------------- Make the user
1.81      www      9544:     my $reply=&modifyuser
1.209     matthew  9545: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9546:          $desiredhome,$email,$inststatus);
1.80      www      9547:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9548:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  9549:     # student's environment
1.297     matthew  9550:     $uid = undef if (!$forceid);
1.455     albertel 9551:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  9552: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  9553:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9554:     return $reply;
                   9555: }
                   9556: 
                   9557: sub modify_student_enrollment {
1.1172.2.23  raeburn  9558:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  9559:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9560:     my ($cdom,$cnum,$chome);
                   9561:     if (!$cid) {
1.620     albertel 9562: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9563: 	    return 'not_in_class';
                   9564: 	}
1.620     albertel 9565: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9566: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9567:     } else {
                   9568: 	($cdom,$cnum)=split(/_/,$cid);
                   9569:     }
1.620     albertel 9570:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9571:     if (!$chome) {
1.457     raeburn  9572: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9573:     }
1.455     albertel 9574:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9575:     # Make sure the user exists
1.81      www      9576:     my $uhome=&homeserver($uname,$udom);
                   9577:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9578: 	return 'error: no such user';
                   9579:     }
1.297     matthew  9580:     # Get student data if we were not given enough information
                   9581:     if (!defined($first)  || $first  eq '' || 
                   9582:         !defined($last)   || $last   eq '' || 
                   9583:         !defined($uid)    || $uid    eq '' || 
                   9584:         !defined($middle) || $middle eq '' || 
                   9585:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9586:         # They did not supply us with enough data to enroll the student, so
                   9587:         # we need to pick up more information.
1.297     matthew  9588:         my %tmp = &get('environment',
1.294     matthew  9589:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9590:                        ,$udom,$uname);
                   9591: 
1.800     albertel 9592:         #foreach my $key (keys(%tmp)) {
                   9593:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9594:         #}
1.294     matthew  9595:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9596:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9597:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9598:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9599:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9600:     }
1.556     albertel 9601:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9602:     my $user = "$uname:$udom";
                   9603:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9604:     my $reply=cput('classlist',
1.1148    raeburn  9605: 		   {$user => 
1.1172.2.76  raeburn  9606: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 9607: 		   $cdom,$cnum);
1.1148    raeburn  9608:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9609:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9610:     } else { 
1.81      www      9611: 	return 'error: '.$reply;
                   9612:     }
1.297     matthew  9613:     # Add student role to user
1.83      www      9614:     my $uurl='/'.$cid;
1.81      www      9615:     $uurl=~s/\_/\//g;
                   9616:     if ($usec) {
                   9617: 	$uurl.='/'.$usec;
                   9618:     }
1.1148    raeburn  9619:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9620:                              $selfenroll,$context);
                   9621:     if ($result ne 'ok') {
                   9622:         if ($old_entry{$user} ne '') {
                   9623:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9624:         } else {
                   9625:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9626:         }
                   9627:     }
                   9628:     return $result; 
1.21      www      9629: }
                   9630: 
1.556     albertel 9631: sub format_name {
                   9632:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9633:     my $name;
                   9634:     if ($first ne 'lastname') {
                   9635: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9636:     } else {
                   9637: 	if ($lastname=~/\S/) {
                   9638: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9639: 	    $name=~s/\s+,/,/;
                   9640: 	} else {
                   9641: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9642: 	}
                   9643:     }
                   9644:     $name=~s/^\s+//;
                   9645:     $name=~s/\s+$//;
                   9646:     $name=~s/\s+/ /g;
                   9647:     return $name;
                   9648: }
                   9649: 
1.84      www      9650: # ------------------------------------------------- Write to course preferences
                   9651: 
                   9652: sub writecoursepref {
                   9653:     my ($courseid,%prefs)=@_;
                   9654:     $courseid=~s/^\///;
                   9655:     $courseid=~s/\_/\//g;
                   9656:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9657:     my $chome=homeserver($cnum,$cdomain);
                   9658:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9659: 	return 'error: no such course';
                   9660:     }
                   9661:     my $cstring='';
1.800     albertel 9662:     foreach my $pref (keys(%prefs)) {
                   9663: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9664:     }
1.84      www      9665:     $cstring=~s/\&$//;
                   9666:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9667: }
                   9668: 
                   9669: # ---------------------------------------------------------- Make/modify course
                   9670: 
                   9671: sub createcourse {
1.741     raeburn  9672:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  9673:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      9674:     $url=&declutter($url);
                   9675:     my $cid='';
1.1028    raeburn  9676:     if ($context eq 'requestcourses') {
                   9677:         my $can_create = 0;
                   9678:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9679:         if ($udom eq $ownerdom) {
                   9680:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   9681:                                   $context)) {
                   9682:                 $can_create = 1;
                   9683:             }
                   9684:         } else {
                   9685:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9686:                                            $category);
                   9687:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   9688:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   9689:                 if (@curr > 0) {
                   9690:                     my @options = qw(approval validate autolimit);
                   9691:                     my $optregex = join('|',@options);
                   9692:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   9693:                         $can_create = 1;
                   9694:                     }
                   9695:                 }
                   9696:             }
                   9697:         }
                   9698:         if ($can_create) {
                   9699:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   9700:                 unless (&allowed('ccc',$udom)) {
                   9701:                     return 'refused'; 
                   9702:                 }
1.1017    raeburn  9703:             }
                   9704:         } else {
                   9705:             return 'refused';
                   9706:         }
1.1028    raeburn  9707:     } elsif (!&allowed('ccc',$udom)) {
                   9708:         return 'refused';
1.84      www      9709:     }
1.1011    raeburn  9710: # --------------------------------------------------------------- Get Unique ID
                   9711:     my $uname;
                   9712:     if ($cnum =~ /^$match_courseid$/) {
                   9713:         my $chome=&homeserver($cnum,$udom,'true');
                   9714:         if (($chome eq '') || ($chome eq 'no_host')) {
                   9715:             $uname = $cnum;
                   9716:         } else {
1.1038    raeburn  9717:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9718:         }
                   9719:     } else {
1.1038    raeburn  9720:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9721:     }
                   9722:     return $uname if ($uname =~ /^error/);
                   9723: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  9724:     if (!defined($course_server)) {
                   9725:         if (defined(&domain($udom,'primary'))) {
                   9726:             $course_server = &domain($udom,'primary');
                   9727:         } else {
                   9728:             $course_server = $env{'user.home'}; 
                   9729:         }
                   9730:     }
                   9731:     my %host_servers =
                   9732:         &Apache::lonnet::get_servers($udom,'library');
                   9733:     unless ($host_servers{$course_server}) {
                   9734:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  9735:     }
1.84      www      9736: # ------------------------------------------------------------- Make the course
                   9737:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  9738:                       $course_server);
1.84      www      9739:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  9740:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      9741:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9742: 	return 'error: no such course';
                   9743:     }
1.271     www      9744: # ----------------------------------------------------------------- Course made
1.516     raeburn  9745: # log existence
1.1029    raeburn  9746:     my $now = time;
1.918     raeburn  9747:     my $newcourse = {
                   9748:                     $udom.'_'.$uname => {
1.921     raeburn  9749:                                      description => $description,
                   9750:                                      inst_code   => $inst_code,
                   9751:                                      owner       => $course_owner,
                   9752:                                      type        => $crstype,
1.1029    raeburn  9753:                                      creator     => $env{'user.name'}.':'.
                   9754:                                                     $env{'user.domain'},
                   9755:                                      created     => $now,
                   9756:                                      context     => $context,
1.918     raeburn  9757:                                                 },
                   9758:                     };
1.921     raeburn  9759:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      9760: # set toplevel url
1.271     www      9761:     my $topurl=$url;
                   9762:     unless ($nonstandard) {
                   9763: # ------------------------------------------ For standard courses, make top url
                   9764:         my $mapurl=&clutter($url);
1.278     www      9765:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 9766:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      9767: <map>
                   9768: <resource id="1" type="start"></resource>
                   9769: <resource id="2" src="$mapurl"></resource>
                   9770: <resource id="3" type="finish"></resource>
                   9771: <link index="1" from="1" to="2"></link>
                   9772: <link index="2" from="2" to="3"></link>
                   9773: </map>
                   9774: ENDINITMAP
                   9775:         $topurl=&declutter(
1.638     albertel 9776:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      9777:                           );
                   9778:     }
                   9779: # ----------------------------------------------------------- Write preferences
1.84      www      9780:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  9781:                      ('description'              => $description,
                   9782:                       'url'                      => $topurl,
                   9783:                       'internal.creator'         => $env{'user.name'}.':'.
                   9784:                                                     $env{'user.domain'},
                   9785:                       'internal.created'         => $now,
                   9786:                       'internal.creationcontext' => $context)
                   9787:                     );
1.84      www      9788:     return '/'.$udom.'/'.$uname;
                   9789: }
                   9790: 
1.1011    raeburn  9791: # ------------------------------------------------------------------- Create ID
                   9792: sub generate_coursenum {
1.1038    raeburn  9793:     my ($udom,$crstype) = @_;
1.1011    raeburn  9794:     my $domdesc = &domain($udom);
                   9795:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  9796:     my $first;
                   9797:     if ($crstype eq 'Community') {
                   9798:         $first = '0';
                   9799:     } else {
                   9800:         $first = int(1+rand(9)); 
                   9801:     } 
                   9802:     my $uname=$first.
1.1011    raeburn  9803:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9804:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9805:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9806: # ----------------------------------------------- Make sure that does not exist
                   9807:     my $uhome=&homeserver($uname,$udom,'true');
                   9808:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  9809:         if ($crstype eq 'Community') {
                   9810:             $first = '0';
                   9811:         } else {
                   9812:             $first = int(1+rand(9));
                   9813:         }
                   9814:         $uname=$first.
1.1011    raeburn  9815:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9816:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9817:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9818:         $uhome=&homeserver($uname,$udom,'true');
                   9819:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   9820:             return 'error: unable to generate unique course-ID';
                   9821:         }
                   9822:     }
                   9823:     return $uname;
                   9824: }
                   9825: 
1.813     albertel 9826: sub is_course {
1.1167    droeschl 9827:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   9828:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  9829:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   9830:     my $uhome=&homeserver($cnum,$cdom);
                   9831:     my $iscourse;
                   9832:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   9833:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   9834:     } else {
                   9835:         my $hashid = $cdom.':'.$cnum;
                   9836:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   9837:         unless (defined($cached)) {
                   9838:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   9839:                                         $cnum,undef,undef,'.');
                   9840:             $iscourse = 0;
                   9841:             if (exists($courses{$cdom.'_'.$cnum})) {
                   9842:                 $iscourse = 1;
                   9843:             }
                   9844:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   9845:         }
                   9846:     }
                   9847:     return unless($iscourse);
1.1167    droeschl 9848:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 9849: }
                   9850: 
1.1015    raeburn  9851: sub store_userdata {
                   9852:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  9853:     my $result;
1.1016    raeburn  9854:     if ($datakey ne '') {
1.1013    raeburn  9855:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  9856:             if ($udom eq '' || $uname eq '') {
                   9857:                 $udom = $env{'user.domain'};
                   9858:                 $uname = $env{'user.name'};
                   9859:             }
                   9860:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  9861:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   9862:                 $result = 'error: no_host';
                   9863:             } else {
                   9864:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   9865:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   9866: 
                   9867:                 my $namevalue='';
                   9868:                 foreach my $key (keys(%{$storehash})) {
                   9869:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   9870:                 }
                   9871:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  9872:                 unless ($namespace eq 'courserequests') {
                   9873:                     $datakey = &escape($datakey);
                   9874:                 }
1.1105    raeburn  9875:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   9876:                                   $namevalue,$uhome);
1.1013    raeburn  9877:             }
                   9878:         } else {
                   9879:             $result = 'error: data to store was not a hash reference'; 
                   9880:         }
                   9881:     } else {
                   9882:         $result= 'error: invalid requestkey'; 
                   9883:     }
                   9884:     return $result;
                   9885: }
                   9886: 
1.21      www      9887: # ---------------------------------------------------------- Assign Custom Role
                   9888: 
                   9889: sub assigncustomrole {
1.957     raeburn  9890:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9891:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  9892:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      9893: }
                   9894: 
                   9895: # ----------------------------------------------------------------- Revoke Role
                   9896: 
                   9897: sub revokerole {
1.957     raeburn  9898:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9899:     my $now=time;
1.965     raeburn  9900:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      9901: }
                   9902: 
                   9903: # ---------------------------------------------------------- Revoke Custom Role
                   9904: 
                   9905: sub revokecustomrole {
1.957     raeburn  9906:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9907:     my $now=time;
1.357     www      9908:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  9909:            $deleteflag,$selfenroll,$context);
1.17      www      9910: }
                   9911: 
1.533     banghart 9912: # ------------------------------------------------------------ Disk usage
1.535     albertel 9913: sub diskusage {
1.955     raeburn  9914:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   9915:     $directorypath =~ s/\/$//;
                   9916:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   9917:                        .&escape($getpropath).':'.&escape($uname).':'
                   9918:                        .&escape($udom),homeserver($uname,$udom));
                   9919:     if ($listing eq 'unknown_cmd') {
                   9920:         if ($getpropath) {
                   9921:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   9922:         }
                   9923:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   9924:     }
1.514     albertel 9925:     return $listing;
1.512     banghart 9926: }
                   9927: 
1.566     banghart 9928: sub is_locked {
1.1096    raeburn  9929:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 9930:     my @check;
                   9931:     my $is_locked;
1.1093    raeburn  9932:     push (@check,$file_name);
1.613     albertel 9933:     my %locked = &get('file_permissions',\@check,
1.620     albertel 9934: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 9935:     my ($tmp)=keys(%locked);
                   9936:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  9937:     
1.566     banghart 9938:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  9939:         $is_locked = 'false';
                   9940:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  9941:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  9942:                $is_locked = 'true';
1.1096    raeburn  9943:                if (ref($which) eq 'ARRAY') {
                   9944:                    push(@{$which},$entry);
                   9945:                } else {
                   9946:                    last;
                   9947:                }
1.745     raeburn  9948:            }
                   9949:        }
1.566     banghart 9950:     } else {
                   9951:         $is_locked = 'false';
                   9952:     }
1.1093    raeburn  9953:     return $is_locked;
1.566     banghart 9954: }
                   9955: 
1.759     albertel 9956: sub declutter_portfile {
                   9957:     my ($file) = @_;
1.833     albertel 9958:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 9959:     return $file;
                   9960: }
                   9961: 
1.559     banghart 9962: # ------------------------------------------------------------- Mark as Read Only
                   9963: 
                   9964: sub mark_as_readonly {
                   9965:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 9966:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9967:     my ($tmp)=keys(%current_permissions);
                   9968:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 9969:     foreach my $file (@{$files}) {
1.759     albertel 9970: 	$file = &declutter_portfile($file);
1.561     banghart 9971:         push(@{$current_permissions{$file}},$what);
1.559     banghart 9972:     }
1.613     albertel 9973:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9974:     return;
                   9975: }
                   9976: 
1.572     banghart 9977: # ------------------------------------------------------------Save Selected Files
                   9978: 
                   9979: sub save_selected_files {
                   9980:     my ($user, $path, @files) = @_;
                   9981:     my $filename = $user."savedfiles";
1.573     banghart 9982:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  9983:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 9984:     foreach my $file (@files) {
1.620     albertel 9985:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 9986:     }
                   9987:     foreach my $file (@other_files) {
1.574     banghart 9988:         print (OUT $file."\n");
1.572     banghart 9989:     }
1.574     banghart 9990:     close (OUT);
1.572     banghart 9991:     return 'ok';
                   9992: }
                   9993: 
1.574     banghart 9994: sub clear_selected_files {
                   9995:     my ($user) = @_;
                   9996:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  9997:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 9998:     print (OUT undef);
                   9999:     close (OUT);
                   10000:     return ("ok");    
                   10001: }
                   10002: 
1.572     banghart 10003: sub files_in_path {
                   10004:     my ($user, $path) = @_;
                   10005:     my $filename = $user."savedfiles";
                   10006:     my %return_files;
1.1172.2.96  raeburn  10007:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10008:     while (my $line_in = <IN>) {
1.574     banghart 10009:         chomp ($line_in);
                   10010:         my @paths_and_file = split (m!/!, $line_in);
                   10011:         my $file_part = pop (@paths_and_file);
                   10012:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10013:         $path_part.='/';
                   10014:         my $path_and_file = $path_part.$file_part;
                   10015:         if ($path_part eq $path) {
                   10016:             $return_files{$file_part}= 'selected';
                   10017:         }
                   10018:     }
1.574     banghart 10019:     close (IN);
                   10020:     return (\%return_files);
1.572     banghart 10021: }
                   10022: 
                   10023: # called in portfolio select mode, to show files selected NOT in current directory
                   10024: sub files_not_in_path {
                   10025:     my ($user, $path) = @_;
                   10026:     my $filename = $user."savedfiles";
                   10027:     my @return_files;
                   10028:     my $path_part;
1.1172.2.96  raeburn  10029:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10030:     while (my $line = <IN>) {
1.572     banghart 10031:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10032:         my @paths_and_file = split(m|/|, $line);
                   10033:         my $file_part = pop(@paths_and_file);
                   10034:         chomp($file_part);
                   10035:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10036:         $path_part .= '/';
                   10037:         my $path_and_file = $path_part.$file_part;
                   10038:         if ($path_part ne $path) {
1.800     albertel 10039:             push(@return_files, ($path_and_file));
1.572     banghart 10040:         }
                   10041:     }
1.800     albertel 10042:     close(OUT);
1.574     banghart 10043:     return (@return_files);
1.572     banghart 10044: }
                   10045: 
1.745     raeburn  10046: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10047: 
1.745     raeburn  10048: sub get_portfile_permissions {
                   10049:     my ($domain,$user) = @_;
1.613     albertel 10050:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10051:     my ($tmp)=keys(%current_permissions);
                   10052:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10053:     return \%current_permissions;
                   10054: }
                   10055: 
                   10056: #---------------------------------------------Get portfolio file access controls
                   10057: 
1.749     raeburn  10058: sub get_access_controls {
1.745     raeburn  10059:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10060:     my %access;
                   10061:     my $real_file = $file;
                   10062:     $file =~ s/\.meta$//;
1.745     raeburn  10063:     if (defined($file)) {
1.749     raeburn  10064:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10065:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10066:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10067:             }
                   10068:         }
1.745     raeburn  10069:     } else {
1.749     raeburn  10070:         foreach my $key (keys(%{$current_permissions})) {
                   10071:             if ($key =~ /\0accesscontrol$/) {
                   10072:                 if (defined($group)) {
                   10073:                     if ($key !~ m-^\Q$group\E/-) {
                   10074:                         next;
                   10075:                     }
                   10076:                 }
                   10077:                 my ($fullpath) = split(/\0/,$key);
                   10078:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10079:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10080:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10081:                     }
                   10082:                 }
                   10083:             }
                   10084:         }
                   10085:     }
                   10086:     return %access;
                   10087: }
                   10088: 
                   10089: sub modify_access_controls {
                   10090:     my ($file_name,$changes,$domain,$user)=@_;
                   10091:     my ($outcome,$deloutcome);
                   10092:     my %store_permissions;
                   10093:     my %new_values;
                   10094:     my %new_control;
                   10095:     my %translation;
                   10096:     my @deletions = ();
                   10097:     my $now = time;
                   10098:     if (exists($$changes{'activate'})) {
                   10099:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10100:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10101:             my $numnew = scalar(@newitems);
                   10102:             for (my $i=0; $i<$numnew; $i++) {
                   10103:                 my $newkey = $newitems[$i];
                   10104:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10105:                 if ($newkey =~ /^\d+:/) { 
                   10106:                     $newkey =~ s/^(\d+)/$newid/;
                   10107:                     $translation{$1} = $newid;
                   10108:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10109:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10110:                     $translation{$1} = $newid;
                   10111:                 }
1.749     raeburn  10112:                 $new_values{$file_name."\0".$newkey} = 
                   10113:                                           $$changes{'activate'}{$newitems[$i]};
                   10114:                 $new_control{$newkey} = $now;
                   10115:             }
                   10116:         }
                   10117:     }
                   10118:     my %todelete;
                   10119:     my %changed_items;
                   10120:     foreach my $action ('delete','update') {
                   10121:         if (exists($$changes{$action})) {
                   10122:             if (ref($$changes{$action}) eq 'HASH') {
                   10123:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10124:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10125:                     if ($action eq 'delete') { 
                   10126:                         $todelete{$itemnum} = 1;
                   10127:                     } else {
                   10128:                         $changed_items{$itemnum} = $key;
                   10129:                     }
                   10130:                 }
1.745     raeburn  10131:             }
                   10132:         }
1.749     raeburn  10133:     }
                   10134:     # get lock on access controls for file.
                   10135:     my $lockhash = {
                   10136:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10137:                                                        ':'.$env{'user.domain'},
                   10138:                    }; 
                   10139:     my $tries = 0;
                   10140:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10141:    
1.1172.2.79  raeburn  10142:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10143:         $tries ++;
1.1172.2.79  raeburn  10144:         sleep(0.1);
1.749     raeburn  10145:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10146:     }
                   10147:     if ($gotlock eq 'ok') {
                   10148:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10149:         my ($tmp)=keys(%curr_permissions);
                   10150:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10151:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10152:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10153:             if (ref($curr_controls) eq 'HASH') {
                   10154:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10155:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10156:                     if (defined($todelete{$itemnum})) {
                   10157:                         push(@deletions,$file_name."\0".$control_item);
                   10158:                     } else {
                   10159:                         if (defined($changed_items{$itemnum})) {
                   10160:                             $new_control{$changed_items{$itemnum}} = $now;
                   10161:                             push(@deletions,$file_name."\0".$control_item);
                   10162:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10163:                         } else {
                   10164:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10165:                         }
                   10166:                     }
1.745     raeburn  10167:                 }
                   10168:             }
                   10169:         }
1.970     raeburn  10170:         my ($group);
                   10171:         if (&is_course($domain,$user)) {
                   10172:             ($group,my $file) = split(/\//,$file_name,2);
                   10173:         }
1.749     raeburn  10174:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10175:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10176:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10177:         #  remove lock
                   10178:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10179:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10180:         my $sqlresult =
1.970     raeburn  10181:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10182:                                     $group);
1.749     raeburn  10183:     } else {
                   10184:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10185:     }
1.749     raeburn  10186:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10187: }
                   10188: 
1.827     raeburn  10189: sub make_public_indefinitely {
                   10190:     my ($requrl) = @_;
                   10191:     my $now = time;
                   10192:     my $action = 'activate';
                   10193:     my $aclnum = 0;
                   10194:     if (&is_portfolio_url($requrl)) {
                   10195:         my (undef,$udom,$unum,$file_name,$group) =
                   10196:             &parse_portfolio_url($requrl);
                   10197:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   10198:         my %access_controls = &get_access_controls($current_perms,
                   10199:                                                    $group,$file_name);
                   10200:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10201:             my ($num,$scope,$end,$start) = 
                   10202:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   10203:             if ($scope eq 'public') {
                   10204:                 if ($start <= $now && $end == 0) {
                   10205:                     $action = 'none';
                   10206:                 } else {
                   10207:                     $action = 'update';
                   10208:                     $aclnum = $num;
                   10209:                 }
                   10210:                 last;
                   10211:             }
                   10212:         }
                   10213:         if ($action eq 'none') {
                   10214:              return 'ok';
                   10215:         } else {
                   10216:             my %changes;
                   10217:             my $newend = 0;
                   10218:             my $newstart = $now;
                   10219:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   10220:             $changes{$action}{$newkey} = {
                   10221:                 type => 'public',
                   10222:                 time => {
                   10223:                     start => $newstart,
                   10224:                     end   => $newend,
                   10225:                 },
                   10226:             };
                   10227:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10228:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   10229:             return $outcome;
                   10230:         }
                   10231:     } else {
                   10232:         return 'invalid';
                   10233:     }
                   10234: }
                   10235: 
1.745     raeburn  10236: #------------------------------------------------------Get Marked as Read Only
                   10237: 
                   10238: sub get_marked_as_readonly {
                   10239:     my ($domain,$user,$what,$group) = @_;
                   10240:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10241:     my @readonly_files;
1.629     banghart 10242:     my $cmp1=$what;
                   10243:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10244:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10245:         if (defined($group)) {
                   10246:             if ($file_name !~ m-^\Q$group\E/-) {
                   10247:                 next;
                   10248:             }
                   10249:         }
1.561     banghart 10250:         if (ref($value) eq "ARRAY"){
                   10251:             foreach my $stored_what (@{$value}) {
1.629     banghart 10252:                 my $cmp2=$stored_what;
1.759     albertel 10253:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10254:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10255:                 }
1.629     banghart 10256:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10257:                     push(@readonly_files, $file_name);
1.745     raeburn  10258:                     last;
1.563     banghart 10259:                 } elsif (!defined($what)) {
                   10260:                     push(@readonly_files, $file_name);
1.745     raeburn  10261:                     last;
1.561     banghart 10262:                 }
                   10263:             }
1.745     raeburn  10264:         }
1.561     banghart 10265:     }
                   10266:     return @readonly_files;
                   10267: }
1.577     banghart 10268: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10269: 
1.577     banghart 10270: sub get_marked_as_readonly_hash {
1.745     raeburn  10271:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10272:     my %readonly_files;
1.745     raeburn  10273:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10274:         if (defined($group)) {
                   10275:             if ($file_name !~ m-^\Q$group\E/-) {
                   10276:                 next;
                   10277:             }
                   10278:         }
1.577     banghart 10279:         if (ref($value) eq "ARRAY"){
                   10280:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10281:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10282:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10283:                         if ($lock_descriptor eq 'graded') {
                   10284:                             $readonly_files{$file_name} = 'graded';
                   10285:                         } elsif ($lock_descriptor eq 'handback') {
                   10286:                             $readonly_files{$file_name} = 'handback';
                   10287:                         } else {
                   10288:                             if (!exists($readonly_files{$file_name})) {
                   10289:                                 $readonly_files{$file_name} = 'locked';
                   10290:                             }
                   10291:                         }
1.745     raeburn  10292:                     }
1.750     banghart 10293:                 } 
1.577     banghart 10294:             }
                   10295:         } 
                   10296:     }
                   10297:     return %readonly_files;
                   10298: }
1.559     banghart 10299: # ------------------------------------------------------------ Unmark as Read Only
                   10300: 
                   10301: sub unmark_as_readonly {
1.629     banghart 10302:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10303:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10304:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10305:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10306:     my $symb_crs = $what;
                   10307:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10308:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10309:     my ($tmp)=keys(%current_permissions);
                   10310:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10311:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10312:     foreach my $file (@readonly_files) {
1.759     albertel 10313: 	my $clean_file = &declutter_portfile($file);
                   10314: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10315: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10316:         my @new_locks;
                   10317:         my @del_keys;
                   10318:         if (ref($current_locks) eq "ARRAY"){
                   10319:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10320:                 my $compare=$locker;
1.749     raeburn  10321:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10322:                     $compare=join('',@{$locker});
1.746     raeburn  10323:                     if ($compare ne $symb_crs) {
                   10324:                         push(@new_locks, $locker);
                   10325:                     }
1.563     banghart 10326:                 }
                   10327:             }
1.650     albertel 10328:             if (scalar(@new_locks) > 0) {
1.563     banghart 10329:                 $current_permissions{$file} = \@new_locks;
                   10330:             } else {
                   10331:                 push(@del_keys, $file);
1.613     albertel 10332:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10333:                 delete($current_permissions{$file});
1.563     banghart 10334:             }
                   10335:         }
1.561     banghart 10336:     }
1.613     albertel 10337:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10338:     return;
                   10339: }
1.512     banghart 10340: 
1.17      www      10341: # ------------------------------------------------------------ Directory lister
                   10342: 
                   10343: sub dirlist {
1.955     raeburn  10344:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10345:     $uri=~s/^\///;
                   10346:     $uri=~s/\/$//;
1.253     stredwic 10347:     my ($udom, $uname);
1.955     raeburn  10348:     if ($getuserdir) {
1.253     stredwic 10349:         $udom = $userdomain;
                   10350:         $uname = $username;
1.955     raeburn  10351:     } else {
                   10352:         (undef,$udom,$uname)=split(/\//,$uri);
                   10353:         if(defined($userdomain)) {
                   10354:             $udom = $userdomain;
                   10355:         }
                   10356:         if(defined($username)) {
                   10357:             $uname = $username;
                   10358:         }
1.253     stredwic 10359:     }
1.955     raeburn  10360:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10361: 
1.955     raeburn  10362:     $dirRoot = $perlvar{'lonDocRoot'};
                   10363:     if (defined($getpropath)) {
                   10364:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10365:         $dirRoot =~ s/\/$//;
1.955     raeburn  10366:     } elsif (defined($getuserdir)) {
                   10367:         my $subdir=$uname.'__';
                   10368:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10369:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10370:                    ."/$udom/$subdir/$uname";
                   10371:     } elsif (defined($alternateRoot)) {
                   10372:         $dirRoot = $alternateRoot;
1.751     banghart 10373:     }
1.253     stredwic 10374: 
                   10375:     if($udom) {
                   10376:         if($uname) {
1.1135    raeburn  10377:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10378:             if ($uhome eq 'no_host') {
                   10379:                 return ([],'no_host');
                   10380:             }
1.955     raeburn  10381:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10382:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10383:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10384:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10385:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10386:             } else {
                   10387:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10388:             }
1.605     matthew  10389:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10390:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10391:                 @listing_results = split(/:/,$listing);
                   10392:             } else {
                   10393:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10394:             }
1.1135    raeburn  10395:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10396:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10397:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10398:                 return ([],$listing);
                   10399:             } else {
                   10400:                 return (\@listing_results);
1.1135    raeburn  10401:             }
1.955     raeburn  10402:         } elsif(!$alternateRoot) {
1.1136    raeburn  10403:             my (%allusers,%listerror);
1.841     albertel 10404: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10405:  	    foreach my $tryserver (keys(%servers)) {
                   10406:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10407:                                   &escape($udom),$tryserver);
                   10408:                 if ($listing eq 'unknown_cmd') {
                   10409: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10410: 				      $udom, $tryserver);
                   10411:                 } else {
                   10412:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10413:                 }
1.841     albertel 10414: 		if ($listing eq 'unknown_cmd') {
                   10415: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10416: 				      $udom, $tryserver);
                   10417: 		    @listing_results = split(/:/,$listing);
                   10418: 		} else {
                   10419: 		    @listing_results =
                   10420: 			map { &unescape($_); } split(/:/,$listing);
                   10421: 		}
1.1136    raeburn  10422:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10423:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10424:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10425:                     $listerror{$tryserver} = $listing;
                   10426:                 } else {
1.841     albertel 10427: 		    foreach my $line (@listing_results) {
                   10428: 			my ($entry) = split(/&/,$line,2);
                   10429: 			$allusers{$entry} = 1;
                   10430: 		    }
                   10431: 		}
1.253     stredwic 10432:             }
1.1136    raeburn  10433:             my @alluserslist=();
1.800     albertel 10434:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10435:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10436:             }
1.1172.2.80  raeburn  10437:             if (!%listerror) {
                   10438:                 # no errors
                   10439:                 return (\@alluserslist);
                   10440:             } elsif (scalar(keys(%servers)) == 1) {
                   10441:                 # one library server, one error
                   10442:                 my ($key) = keys(%listerror);
                   10443:                 return (\@alluserslist, $listerror{$key});
                   10444:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10445:                 # con_lost indicates that we might miss data from at least one
                   10446:                 # library server
                   10447:                 return (\@alluserslist, 'con_lost');
                   10448:             } else {
                   10449:                 # multiple library servers and no con_lost -> data should be
                   10450:                 # complete.
                   10451:                 return (\@alluserslist);
                   10452:             }
                   10453: 
1.253     stredwic 10454:         } else {
1.1136    raeburn  10455:             return ([],'missing username');
1.253     stredwic 10456:         }
1.955     raeburn  10457:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10458:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10459:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10460:         return (\@all_domains);
1.955     raeburn  10461:     } else {
1.1136    raeburn  10462:         return ([],'missing domain');
1.275     stredwic 10463:     }
                   10464: }
                   10465: 
                   10466: # --------------------------------------------- GetFileTimestamp
                   10467: # This function utilizes dirlist and returns the date stamp for
                   10468: # when it was last modified.  It will also return an error of -1
                   10469: # if an error occurs
                   10470: 
                   10471: sub GetFileTimestamp {
1.955     raeburn  10472:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10473:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10474:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10475:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10476:                                     undef,$getuserdir);
                   10477:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10478:         return -1;
                   10479:     }
                   10480:     if (ref($fileref) eq 'ARRAY') {
                   10481:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10482:         # @stats contains first the filename, then the stat output
                   10483:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10484:     } else {
                   10485:         return -1;
1.253     stredwic 10486:     }
1.26      www      10487: }
                   10488: 
1.712     albertel 10489: sub stat_file {
                   10490:     my ($uri) = @_;
1.787     albertel 10491:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10492: 
1.955     raeburn  10493:     my ($udom,$uname,$file);
1.712     albertel 10494:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10495: 	($udom,$uname,$file) =
1.811     albertel 10496: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10497: 	$file = 'userfiles/'.$file;
                   10498:     }
                   10499:     if ($uri =~ m-^/res/-) {
                   10500: 	($udom,$uname) = 
1.807     albertel 10501: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10502: 	$file = $uri;
                   10503:     }
                   10504: 
                   10505:     if (!$udom || !$uname || !$file) {
                   10506: 	# unable to handle the uri
                   10507: 	return ();
                   10508:     }
1.956     raeburn  10509:     my $getpropath;
                   10510:     if ($file =~ /^userfiles\//) {
                   10511:         $getpropath = 1;
                   10512:     }
1.1136    raeburn  10513:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10514:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10515:         return ();
                   10516:     } else {
                   10517:         if (ref($listref) eq 'ARRAY') {
                   10518:             my @stats = split('&',$listref->[0]);
                   10519: 	    shift(@stats); #filename is first
                   10520: 	    return @stats;
                   10521:         }
1.712     albertel 10522:     }
                   10523:     return ();
                   10524: }
                   10525: 
1.26      www      10526: # -------------------------------------------------------- Value of a Condition
                   10527: 
1.713     albertel 10528: # gets the value of a specific preevaluated condition
                   10529: #    stored in the string  $env{user.state.<cid>}
                   10530: # or looks up a condition reference in the bighash and if if hasn't
                   10531: # already been evaluated recurses into docondval to get the value of
                   10532: # the condition, then memoizing it to 
                   10533: #   $env{user.state.<cid>.<condition>}
1.40      www      10534: sub directcondval {
                   10535:     my $number=shift;
1.620     albertel 10536:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 10537: 	&Apache::lonuserstate::evalstate();
                   10538:     }
1.713     albertel 10539:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   10540: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   10541:     } elsif ($number =~ /^_/) {
                   10542: 	my $sub_condition;
                   10543: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10544: 		&GDBM_READER(),0640)) {
                   10545: 	    $sub_condition=$bighash{'conditions'.$number};
                   10546: 	    untie(%bighash);
                   10547: 	}
                   10548: 	my $value = &docondval($sub_condition);
1.949     raeburn  10549: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 10550: 	return $value;
                   10551:     }
1.620     albertel 10552:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   10553:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      10554:     } else {
                   10555:        return 2;
                   10556:     }
                   10557: }
                   10558: 
1.713     albertel 10559: # get the collection of conditions for this resource
1.26      www      10560: sub condval {
                   10561:     my $condidx=shift;
1.54      www      10562:     my $allpathcond='';
1.713     albertel 10563:     foreach my $cond (split(/\|/,$condidx)) {
                   10564: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   10565: 	    $allpathcond.=
                   10566: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   10567: 	}
1.191     harris41 10568:     }
1.54      www      10569:     $allpathcond=~s/\|$//;
1.713     albertel 10570:     return &docondval($allpathcond);
                   10571: }
                   10572: 
                   10573: #evaluates an expression of conditions
                   10574: sub docondval {
                   10575:     my ($allpathcond) = @_;
                   10576:     my $result=0;
                   10577:     if ($env{'request.course.id'}
                   10578: 	&& defined($allpathcond)) {
                   10579: 	my $operand='|';
                   10580: 	my @stack;
                   10581: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   10582: 	    if ($chunk eq '(') {
                   10583: 		push @stack,($operand,$result);
                   10584: 	    } elsif ($chunk eq ')') {
                   10585: 		my $before=pop @stack;
                   10586: 		if (pop @stack eq '&') {
                   10587: 		    $result=$result>$before?$before:$result;
                   10588: 		} else {
                   10589: 		    $result=$result>$before?$result:$before;
                   10590: 		}
                   10591: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   10592: 		$operand=$chunk;
                   10593: 	    } else {
                   10594: 		my $new=directcondval($chunk);
                   10595: 		if ($operand eq '&') {
                   10596: 		    $result=$result>$new?$new:$result;
                   10597: 		} else {
                   10598: 		    $result=$result>$new?$result:$new;
                   10599: 		}
                   10600: 	    }
                   10601: 	}
1.26      www      10602:     }
                   10603:     return $result;
1.421     albertel 10604: }
                   10605: 
                   10606: # ---------------------------------------------------- Devalidate courseresdata
                   10607: 
                   10608: sub devalidatecourseresdata {
                   10609:     my ($coursenum,$coursedomain)=@_;
                   10610:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10611:     &devalidate_cache_new('courseres',$hashid);
1.28      www      10612: }
                   10613: 
1.763     www      10614: 
1.200     www      10615: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     10616: #
                   10617: #  Parameters:
                   10618: #      $coursenum    - Number of the course.
                   10619: #      $coursedomain - Domain at which the course was created.
                   10620: #  Returns:
                   10621: #     A hash of the course parameters along (I think) with timestamps
                   10622: #     and version info.
1.877     foxr     10623: 
1.624     albertel 10624: sub get_courseresdata {
                   10625:     my ($coursenum,$coursedomain)=@_;
1.200     www      10626:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   10627:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10628:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 10629:     my %dumpreply;
1.417     albertel 10630:     unless (defined($cached)) {
1.624     albertel 10631: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 10632: 	$result=\%dumpreply;
1.251     albertel 10633: 	my ($tmp) = keys(%dumpreply);
                   10634: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 10635: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 10636: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   10637: 	    return $tmp;
1.416     albertel 10638: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 10639: 	    $result=undef;
1.599     albertel 10640: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 10641: 	}
                   10642:     }
1.624     albertel 10643:     return $result;
                   10644: }
                   10645: 
1.633     albertel 10646: sub devalidateuserresdata {
                   10647:     my ($uname,$udom)=@_;
                   10648:     my $hashid="$udom:$uname";
                   10649:     &devalidate_cache_new('userres',$hashid);
                   10650: }
                   10651: 
1.624     albertel 10652: sub get_userresdata {
                   10653:     my ($uname,$udom)=@_;
                   10654:     #most student don\'t have any data set, check if there is some data
                   10655:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   10656: 
                   10657:     my $hashid="$udom:$uname";
                   10658:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   10659:     if (!defined($cached)) {
                   10660: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   10661: 	$result=\%resourcedata;
                   10662: 	&do_cache_new('userres',$hashid,$result,600);
                   10663:     }
                   10664:     my ($tmp)=keys(%$result);
                   10665:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   10666: 	return $result;
                   10667:     }
                   10668:     #error 2 occurs when the .db doesn't exist
                   10669:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  10670:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   10671: 	    &logthis("<font color=\"blue\">WARNING:".
                   10672: 		     " Trying to get resource data for ".
                   10673: 		     $uname." at ".$udom.": ".
                   10674: 		     $tmp."</font>");
                   10675:         }
1.624     albertel 10676:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 10677: 	#&EXT_cache_set($udom,$uname);
                   10678: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 10679: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 10680:     }
                   10681:     return $tmp;
                   10682: }
1.879     foxr     10683: #----------------------------------------------- resdata - return resource data
                   10684: #  Purpose:
                   10685: #    Return resource data for either users or for a course.
                   10686: #  Parameters:
                   10687: #     $name      - Course/user name.
                   10688: #     $domain    - Name of the domain the user/course is registered on.
                   10689: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   10690: #     @which     - Array of names of resources desired.
                   10691: #  Returns:
                   10692: #     The value of the first reasource in @which that is found in the
                   10693: #     resource hash.
                   10694: #  Exceptional Conditions:
                   10695: #     If the $type passed in is not valid (not the string 'course' or 
                   10696: #     'user', an undefined  reference is returned.
                   10697: #     If none of the resources are found, an undef is returned
1.624     albertel 10698: sub resdata {
                   10699:     my ($name,$domain,$type,@which)=@_;
                   10700:     my $result;
                   10701:     if ($type eq 'course') {
                   10702: 	$result=&get_courseresdata($name,$domain);
                   10703:     } elsif ($type eq 'user') {
                   10704: 	$result=&get_userresdata($name,$domain);
                   10705:     }
                   10706:     if (!ref($result)) { return $result; }    
1.251     albertel 10707:     foreach my $item (@which) {
1.927     albertel 10708: 	if (defined($result->{$item->[0]})) {
                   10709: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 10710: 	}
1.250     albertel 10711:     }
1.291     albertel 10712:     return undef;
1.200     www      10713: }
                   10714: 
1.1172.2.31  raeburn  10715: sub get_numsuppfiles {
                   10716:     my ($cnum,$cdom,$ignorecache)=@_;
                   10717:     my $hashid=$cnum.':'.$cdom;
                   10718:     my ($suppcount,$cached);
                   10719:     unless ($ignorecache) {
                   10720:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   10721:     }
                   10722:     unless (defined($cached)) {
                   10723:         my $chome=&homeserver($cnum,$cdom);
                   10724:         unless ($chome eq 'no_host') {
                   10725:             ($suppcount,my $errors) = (0,0);
                   10726:             my $suppmap = 'supplemental.sequence';
                   10727:             ($suppcount,$errors) =
                   10728:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   10729:         }
                   10730:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   10731:     }
                   10732:     return $suppcount;
                   10733: }
                   10734: 
1.379     matthew  10735: #
                   10736: # EXT resource caching routines
                   10737: #
                   10738: 
                   10739: sub clear_EXT_cache_status {
1.383     albertel 10740:     &delenv('cache.EXT.');
1.379     matthew  10741: }
                   10742: 
                   10743: sub EXT_cache_status {
                   10744:     my ($target_domain,$target_user) = @_;
1.383     albertel 10745:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 10746:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  10747:         # We know already the user has no data
                   10748:         return 1;
                   10749:     } else {
                   10750:         return 0;
                   10751:     }
                   10752: }
                   10753: 
                   10754: sub EXT_cache_set {
                   10755:     my ($target_domain,$target_user) = @_;
1.383     albertel 10756:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  10757:     #&appenv({$cachename => time});
1.379     matthew  10758: }
                   10759: 
1.28      www      10760: # --------------------------------------------------------- Value of a Variable
1.58      www      10761: sub EXT {
1.715     albertel 10762: 
1.1172.2.28  raeburn  10763:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      10764:     unless ($varname) { return ''; }
1.218     albertel 10765:     #get real user name/domain, courseid and symb
                   10766:     my $courseid;
1.359     albertel 10767:     my $publicuser;
1.427     www      10768:     if ($symbparm) {
                   10769: 	$symbparm=&get_symb_from_alias($symbparm);
                   10770:     }
1.218     albertel 10771:     if (!($uname && $udom)) {
1.790     albertel 10772:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 10773:       if (!$symbparm) {	$symbparm=$cursymb; }
                   10774:     } else {
1.620     albertel 10775: 	$courseid=$env{'request.course.id'};
1.218     albertel 10776:     }
1.48      www      10777:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   10778:     my $rest;
1.320     albertel 10779:     if (defined($therest[0])) {
1.48      www      10780:        $rest=join('.',@therest);
                   10781:     } else {
                   10782:        $rest='';
                   10783:     }
1.320     albertel 10784: 
1.57      www      10785:     my $qualifierrest=$qualifier;
                   10786:     if ($rest) { $qualifierrest.='.'.$rest; }
                   10787:     my $spacequalifierrest=$space;
                   10788:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      10789:     if ($realm eq 'user') {
1.48      www      10790: # --------------------------------------------------------------- user.resource
                   10791: 	if ($space eq 'resource') {
1.651     albertel 10792: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   10793: 		  || defined($Apache::lonhomework::parsing_a_task))
                   10794: 		 &&
1.744     albertel 10795: 		 ($symbparm eq &symbread()) ) {	
                   10796: 		# if we are in the middle of processing the resource the
                   10797: 		# get the value we are planning on committing
                   10798:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   10799:                     return $Apache::lonhomework::results{$qualifierrest};
                   10800:                 } else {
                   10801:                     return $Apache::lonhomework::history{$qualifierrest};
                   10802:                 }
1.335     albertel 10803: 	    } else {
1.359     albertel 10804: 		my %restored;
1.620     albertel 10805: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 10806: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   10807: 		} else {
                   10808: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   10809: 		}
1.335     albertel 10810: 		return $restored{$qualifierrest};
                   10811: 	    }
1.48      www      10812: # ----------------------------------------------------------------- user.access
                   10813:         } elsif ($space eq 'access') {
1.218     albertel 10814: 	    # FIXME - not supporting calls for a specific user
1.48      www      10815:             return &allowed($qualifier,$rest);
                   10816: # ------------------------------------------ user.preferences, user.environment
                   10817:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 10818: 	    if (($uname eq $env{'user.name'}) &&
                   10819: 		($udom eq $env{'user.domain'})) {
                   10820: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 10821: 	    } else {
1.359     albertel 10822: 		my %returnhash;
                   10823: 		if (!$publicuser) {
                   10824: 		    %returnhash=&userenvironment($udom,$uname,
                   10825: 						 $qualifierrest);
                   10826: 		}
1.218     albertel 10827: 		return $returnhash{$qualifierrest};
                   10828: 	    }
1.48      www      10829: # ----------------------------------------------------------------- user.course
                   10830:         } elsif ($space eq 'course') {
1.218     albertel 10831: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10832:             return $env{join('.',('request.course',$qualifier))};
1.48      www      10833: # ------------------------------------------------------------------- user.role
                   10834:         } elsif ($space eq 'role') {
1.218     albertel 10835: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10836:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      10837:             if ($qualifier eq 'value') {
                   10838: 		return $role;
                   10839:             } elsif ($qualifier eq 'extent') {
                   10840:                 return $where;
                   10841:             }
                   10842: # ----------------------------------------------------------------- user.domain
                   10843:         } elsif ($space eq 'domain') {
1.218     albertel 10844:             return $udom;
1.48      www      10845: # ------------------------------------------------------------------- user.name
                   10846:         } elsif ($space eq 'name') {
1.218     albertel 10847:             return $uname;
1.48      www      10848: # ---------------------------------------------------- Any other user namespace
1.29      www      10849:         } else {
1.359     albertel 10850: 	    my %reply;
                   10851: 	    if (!$publicuser) {
                   10852: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   10853: 	    }
                   10854: 	    return $reply{$qualifierrest};
1.48      www      10855:         }
1.236     www      10856:     } elsif ($realm eq 'query') {
                   10857: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 10858:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   10859: 						[$spacequalifierrest]);
1.620     albertel 10860: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      10861:    } elsif ($realm eq 'request') {
1.48      www      10862: # ------------------------------------------------------------- request.browser
                   10863:         if ($space eq 'browser') {
1.1145    bisitz   10864:             return $env{'browser.'.$qualifier};
1.57      www      10865: # ------------------------------------------------------------ request.filename
                   10866:         } else {
1.620     albertel 10867:             return $env{'request.'.$spacequalifierrest};
1.29      www      10868:         }
1.28      www      10869:     } elsif ($realm eq 'course') {
1.48      www      10870: # ---------------------------------------------------------- course.description
1.620     albertel 10871:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      10872:     } elsif ($realm eq 'resource') {
1.165     www      10873: 
1.620     albertel 10874: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 10875: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   10876: 	}
1.693     albertel 10877: 
1.1172.2.30  raeburn  10878:         if ($qualifier eq '') {
                   10879: 	    if ($space eq 'title') {
                   10880: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   10881: 	        return &gettitle($symbparm);
                   10882: 	    }
1.693     albertel 10883: 	
1.1172.2.30  raeburn  10884: 	    if ($space eq 'map') {
                   10885: 	        my ($map) = &decode_symb($symbparm);
                   10886: 	        return &symbread($map);
                   10887: 	    }
                   10888:             if ($space eq 'maptitle') {
                   10889:                 my ($map) = &decode_symb($symbparm);
                   10890:                 return &gettitle($map);
                   10891:             }
                   10892: 	    if ($space eq 'filename') {
                   10893: 	        if ($symbparm) {
                   10894: 		    return &clutter((&decode_symb($symbparm))[2]);
                   10895: 	        }
                   10896: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 10897: 	    }
1.1172.2.30  raeburn  10898: 
                   10899:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   10900:                 if ($space eq 'visibleparts') {
                   10901:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10902:                     my $item;
                   10903:                     if (ref($navmap)) {
                   10904:                         my $res = $navmap->getBySymb($symbparm);
                   10905:                         my $parts = $res->parts();
                   10906:                         if (ref($parts) eq 'ARRAY') {
                   10907:                             $item = join(',',@{$parts});
                   10908:                         }
                   10909:                         undef($navmap);
                   10910:                     }
                   10911:                     return $item;
                   10912:                 }
                   10913:             }
                   10914:         }
1.693     albertel 10915: 
                   10916: 	my ($section, $group, @groups);
1.593     albertel 10917: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  10918:         if (($courseid eq '') && ($cid)) {
                   10919:             $courseid = $cid;
                   10920:         }
                   10921: 	if (($symbparm && $courseid) && 
                   10922: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      10923: 
1.218     albertel 10924: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      10925: 
1.60      www      10926: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 10927: 	    my $symbp=$symbparm;
1.735     albertel 10928: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 10929: 
                   10930: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   10931: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   10932: 
1.620     albertel 10933: 	    if (($env{'user.name'} eq $uname) &&
                   10934: 		($env{'user.domain'} eq $udom)) {
                   10935: 		$section=$env{'request.course.sec'};
1.733     raeburn  10936:                 @groups = split(/:/,$env{'request.course.groups'});  
                   10937:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 10938: 	    } else {
1.539     albertel 10939: 		if (! defined($usection)) {
1.551     albertel 10940: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 10941: 		} else {
                   10942: 		    $section = $usection;
                   10943: 		}
1.733     raeburn  10944:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 10945: 	    }
                   10946: 
                   10947: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   10948: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   10949: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   10950: 
1.593     albertel 10951: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 10952: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 10953: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      10954: 
1.60      www      10955: # ----------------------------------------------------------- first, check user
1.624     albertel 10956: 
                   10957: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 10958: 				       ([$courselevelr,'resource'],
                   10959: 					[$courselevelm,'map'     ],
                   10960: 					[$courselevel, 'course'  ]));
1.931     albertel 10961: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      10962: 
1.594     albertel 10963: # ------------------------------------------------ second, check some of course
1.684     raeburn  10964:             my $coursereply;
1.691     raeburn  10965:             if (@groups > 0) {
                   10966:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   10967:                                        $mapparm,$spacequalifierrest);
1.927     albertel 10968:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  10969:             }
1.96      www      10970: 
1.684     raeburn  10971: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 10972: 				  $env{'course.'.$courseid.'.domain'},
                   10973: 				  'course',
                   10974: 				  ([$seclevelr,   'resource'],
                   10975: 				   [$seclevelm,   'map'     ],
                   10976: 				   [$seclevel,    'course'  ],
                   10977: 				   [$courselevelr,'resource']));
                   10978: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      10979: 
1.60      www      10980: # ------------------------------------------------------ third, check map parms
1.218     albertel 10981: 	    my %parmhash=();
                   10982: 	    my $thisparm='';
                   10983: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 10984: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 10985: 		    &GDBM_READER(),0640)) {
1.218     albertel 10986: 		$thisparm=$parmhash{$symbparm};
                   10987: 		untie(%parmhash);
                   10988: 	    }
1.927     albertel 10989: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 10990: 	}
1.594     albertel 10991: # ------------------------------------------ fourth, look in resource metadata
1.71      www      10992: 
1.218     albertel 10993: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 10994: 	my $filename;
                   10995: 	if (!$symbparm) { $symbparm=&symbread(); }
                   10996: 	if ($symbparm) {
1.409     www      10997: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 10998: 	} else {
1.620     albertel 10999: 	    $filename=$env{'request.filename'};
1.282     albertel 11000: 	}
                   11001: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 11002: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 11003: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 11004: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11005: 
1.927     albertel 11006: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 11007: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11008: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11009: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11010: 				     $env{'course.'.$courseid.'.domain'},
                   11011: 				     'course',
1.927     albertel 11012: 				     ([$courselevelm,'map'   ],
                   11013: 				      [$courselevel, 'course']));
                   11014: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11015: 	}
1.145     www      11016: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11017: 	unless ($space eq '0') {
1.336     albertel 11018: 	    my @parts=split(/_/,$space);
                   11019: 	    my $id=pop(@parts);
                   11020: 	    my $part=join('_',@parts);
                   11021: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11022: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11023: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11024: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11025: 	}
1.395     albertel 11026: 	if ($recurse) { return undef; }
                   11027: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 11028: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11029: # ---------------------------------------------------- Any other user namespace
                   11030:     } elsif ($realm eq 'environment') {
                   11031: # ----------------------------------------------------------------- environment
1.620     albertel 11032: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11033: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11034: 	} else {
1.770     albertel 11035: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11036: 		return '';
                   11037: 	    }
1.219     albertel 11038: 	    my %returnhash=&userenvironment($udom,$uname,
                   11039: 					    $spacequalifierrest);
                   11040: 	    return $returnhash{$spacequalifierrest};
                   11041: 	}
1.28      www      11042:     } elsif ($realm eq 'system') {
1.48      www      11043: # ----------------------------------------------------------------- system.time
                   11044: 	if ($space eq 'time') {
                   11045: 	    return time;
                   11046:         }
1.696     albertel 11047:     } elsif ($realm eq 'server') {
                   11048: # ----------------------------------------------------------------- system.time
                   11049: 	if ($space eq 'name') {
                   11050: 	    return $ENV{'SERVER_NAME'};
                   11051:         }
1.28      www      11052:     }
1.48      www      11053:     return '';
1.61      www      11054: }
                   11055: 
1.927     albertel 11056: sub get_reply {
                   11057:     my ($reply_value) = @_;
1.940     raeburn  11058:     if (ref($reply_value) eq 'ARRAY') {
                   11059:         if (wantarray) {
                   11060: 	    return @$reply_value;
                   11061:         }
                   11062:         return $reply_value->[0];
                   11063:     } else {
                   11064:         return $reply_value;
1.927     albertel 11065:     }
                   11066: }
                   11067: 
1.691     raeburn  11068: sub check_group_parms {
                   11069:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   11070:     my @groupitems = ();
                   11071:     my $resultitem;
1.927     albertel 11072:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  11073:     foreach my $group (@{$groups}) {
                   11074:         foreach my $level (@levels) {
1.927     albertel 11075:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11076:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11077:         }
                   11078:     }
                   11079:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11080:                             $env{'course.'.$courseid.'.domain'},
                   11081:                                      'course',@groupitems);
                   11082:     return $coursereply;
                   11083: }
                   11084: 
                   11085: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11086:     my ($courseid,@groups) = @_;
                   11087:     @groups = sort(@groups);
1.691     raeburn  11088:     return @groups;
                   11089: }
                   11090: 
1.395     albertel 11091: sub packages_tab_default {
                   11092:     my ($uri,$varname)=@_;
                   11093:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11094: 
                   11095:     my (@extension,@specifics,$do_default);
                   11096:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11097: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11098: 	if ($pack_type eq 'default') {
                   11099: 	    $do_default=1;
                   11100: 	} elsif ($pack_type eq 'extension') {
                   11101: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11102: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11103: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11104: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11105: 	}
                   11106:     }
                   11107:     # first look for a package that matches the requested part id
                   11108:     foreach my $package (@specifics) {
                   11109: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11110: 	next if ($pack_part ne $part);
                   11111: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11112: 	    return $packagetab{"$pack_type&$name&default"};
                   11113: 	}
                   11114:     }
                   11115:     # look for any possible matching non extension_ package
                   11116:     foreach my $package (@specifics) {
                   11117: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11118: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11119: 	    return $packagetab{"$pack_type&$name&default"};
                   11120: 	}
1.585     albertel 11121: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11122: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11123: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11124: 	}
                   11125:     }
1.738     albertel 11126:     # look for any posible extension_ match
                   11127:     foreach my $package (@extension) {
                   11128: 	my ($package,$pack_type)=@{$package};
                   11129: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11130: 	    return $packagetab{"$pack_type&$name&default"};
                   11131: 	}
                   11132: 	if (defined($packagetab{$package."&$name&default"})) {
                   11133: 	    return $packagetab{$package."&$name&default"};
                   11134: 	}
                   11135:     }
                   11136:     # look for a global default setting
                   11137:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11138: 	return $packagetab{"default&$name&default"};
                   11139:     }
1.395     albertel 11140:     return undef;
                   11141: }
                   11142: 
1.334     albertel 11143: sub add_prefix_and_part {
                   11144:     my ($prefix,$part)=@_;
                   11145:     my $keyroot;
                   11146:     if (defined($prefix) && $prefix !~ /^__/) {
                   11147: 	# prefix that has a part already
                   11148: 	$keyroot=$prefix;
                   11149:     } elsif (defined($prefix)) {
                   11150: 	# prefix that is missing a part
                   11151: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11152:     } else {
                   11153: 	# no prefix at all
                   11154: 	if (defined($part)) { $keyroot='_'.$part; }
                   11155:     }
                   11156:     return $keyroot;
                   11157: }
                   11158: 
1.71      www      11159: # ---------------------------------------------------------------- Get metadata
                   11160: 
1.599     albertel 11161: my %metaentry;
1.1070    www      11162: my %importedpartids;
1.1172.2.99  raeburn  11163: my %importedrespids;
1.71      www      11164: sub metadata {
1.176     www      11165:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11166:     $uri=&declutter($uri);
1.288     albertel 11167:     # if it is a non metadata possible uri return quickly
1.529     albertel 11168:     if (($uri eq '') || 
                   11169: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  11170: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  11171:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11172: 	return undef;
                   11173:     }
1.1172.2.49  raeburn  11174:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11175: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11176: 	return undef;
1.288     albertel 11177:     }
1.73      www      11178:     my $filename=$uri;
                   11179:     $uri=~s/\.meta$//;
1.172     www      11180: #
                   11181: # Is the metadata already cached?
1.177     www      11182: # Look at timestamp of caching
1.172     www      11183: # Everything is cached by the main uri, libraries are never directly cached
                   11184: #
1.428     albertel 11185:     if (!defined($liburi)) {
1.599     albertel 11186: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11187: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11188:     }
                   11189:     {
1.1069    www      11190: # Imported parts would go here
1.1172.2.99  raeburn  11191:         my @origfiletagids=();
1.1069    www      11192:         my $importedparts=0;
1.1172.2.99  raeburn  11193: 
                   11194: # Imported responseids would go here
                   11195:         my $importedresponses=0;
1.172     www      11196: #
                   11197: # Is this a recursive call for a library?
                   11198: #
1.599     albertel 11199: #	if (! exists($metacache{$uri})) {
                   11200: #	    $metacache{$uri}={};
                   11201: #	}
1.924     albertel 11202: 	my $cachetime = 60*60;
1.171     www      11203:         if ($liburi) {
                   11204: 	    $liburi=&declutter($liburi);
                   11205:             $filename=$liburi;
1.401     bowersj2 11206:         } else {
1.599     albertel 11207: 	    &devalidate_cache_new('meta',$uri);
                   11208: 	    undef(%metaentry);
1.401     bowersj2 11209: 	}
1.140     www      11210:         my %metathesekeys=();
1.73      www      11211:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11212: 	my $metastring;
1.1140    www      11213: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11214: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11215: 	    $metastring = 
1.929     albertel 11216: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11217: 					  ('grade_target' => 'meta'));
                   11218: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11219: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11220:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11221: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11222: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11223: 	    $metastring=&getfile($file);
1.489     albertel 11224: 	}
1.208     albertel 11225:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11226:         my $token;
1.140     www      11227:         undef %metathesekeys;
1.71      www      11228:         while ($token=$parser->get_token) {
1.339     albertel 11229: 	    if ($token->[0] eq 'S') {
                   11230: 		if (defined($token->[2]->{'package'})) {
1.172     www      11231: #
                   11232: # This is a package - get package info
                   11233: #
1.339     albertel 11234: 		    my $package=$token->[2]->{'package'};
                   11235: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11236: 		    if (defined($token->[2]->{'id'})) { 
                   11237: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11238: 		    }
1.599     albertel 11239: 		    if ($metaentry{':packages'}) {
                   11240: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11241: 		    } else {
1.599     albertel 11242: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11243: 		    }
1.736     albertel 11244: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11245: 			my $part=$keyroot;
                   11246: 			$part=~s/^\_//;
1.736     albertel 11247: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11248: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11249: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11250: 			    # ignore package.tab specified default values
                   11251:                             # here &package_tab_default() will fetch those
                   11252: 			    if ($subp eq 'default') { next; }
1.736     albertel 11253: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11254: 			    my $unikey;
                   11255: 			    if ($pack =~ /_0$/) {
                   11256: 				$unikey='parameter_0_'.$name;
                   11257: 				$part=0;
                   11258: 			    } else {
                   11259: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11260: 			    }
1.339     albertel 11261: 			    if ($subp eq 'display') {
                   11262: 				$value.=' [Part: '.$part.']';
                   11263: 			    }
1.599     albertel 11264: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11265: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11266: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11267: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11268: 			    }
1.599     albertel 11269: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11270: 				$metaentry{':'.$unikey}=
                   11271: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11272: 			    }
1.339     albertel 11273: 			}
                   11274: 		    }
                   11275: 		} else {
1.172     www      11276: #
                   11277: # This is not a package - some other kind of start tag
1.339     albertel 11278: #
                   11279: 		    my $entry=$token->[1];
1.1068    www      11280: 		    my $unikey='';
1.175     www      11281: 
1.339     albertel 11282: 		    if ($entry eq 'import') {
1.175     www      11283: #
                   11284: # Importing a library here
1.339     albertel 11285: #
1.1067    www      11286:                         my $location=$parser->get_text('/import');
                   11287:                         my $dir=$filename;
                   11288:                         $dir=~s|[^/]*$||;
                   11289:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  11290: 
                   11291:                         my $importid=$token->[2]->{'id'};
1.1068    www      11292:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  11293: #
                   11294: # Check metadata for imported file to
                   11295: # see if it contained response items
                   11296: #
                   11297:                         my %currmetaentry = %metaentry;
                   11298:                         my $libresponseorder = &metadata($location,'responseorder');
                   11299:                         my $origfile;
                   11300:                         if ($libresponseorder ne '') {
                   11301:                             if ($#origfiletagids<0) {
                   11302:                                 undef(%importedrespids);
                   11303:                                 undef(%importedpartids);
                   11304:                             }
                   11305:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   11306:                             if (@{$importedrespids{$importid}} > 0) {
                   11307:                                 $importedresponses = 1;
                   11308: # We need to get the original file and the imported file to get the response order correct
                   11309: # Load and inspect original file
                   11310:                                 if ($#origfiletagids<0) {
                   11311:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11312:                                     $origfile=&getfile($origfilelocation);
                   11313:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11314:                                 }
                   11315:                             }
                   11316:                         }
                   11317: # Do not overwrite contents of %metaentry hash for resource itself with 
                   11318: # hash populated for imported library file
                   11319:                         %metaentry = %currmetaentry;
                   11320:                         undef(%currmetaentry);
1.1068    www      11321:                         if ($importmode eq 'problem') {
1.1069    www      11322: # Import as problem/response
1.1068    www      11323:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11324:                         } elsif ($importmode eq 'part') {
                   11325: # Import as part(s)
1.1069    www      11326:                            $importedparts=1;
                   11327: # We need to get the original file and the imported file to get the part order correct
                   11328: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  11329: # Load and inspect original file if we didn't do that already
                   11330:                            if ($#origfiletagids<0) {
                   11331:                                undef(%importedrespids);
                   11332:                                undef(%importedpartids);
                   11333:                                if ($origfile eq '') {
                   11334:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11335:                                    $origfile=&getfile($origfilelocation);
                   11336:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11337:                                }
1.1070    www      11338:                            }
                   11339: 
1.1069    www      11340: # Load and inspect imported file
                   11341:                            my $impfile=&getfile($location);
                   11342:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11343:                            if ($#impfilepartids>=0) {
                   11344: # This problem had parts
1.1070    www      11345:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11346:                            } else {
                   11347: # Importing by turning a single problem into a problem part
                   11348: # It gets the import-tags ID as part-ID
                   11349:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11350:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11351:                            }
1.1068    www      11352:                         } else {
                   11353: # Normal import
                   11354:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11355:                            if (defined($token->[2]->{'id'})) {
                   11356:                               $unikey.='_'.$token->[2]->{'id'};
                   11357:                            }
1.1067    www      11358:                         }
                   11359: 
1.339     albertel 11360: 			if ($depthcount<20) {
1.736     albertel 11361: 			    my $metadata = 
                   11362: 				&metadata($uri,'keys', $location,$unikey,
                   11363: 					  $depthcount+1);
                   11364: 			    foreach my $meta (split(',',$metadata)) {
                   11365: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   11366: 				$metathesekeys{$meta}=1;
1.339     albertel 11367: 			    }
1.1068    www      11368: 			
                   11369:                         }
1.1067    www      11370: 		    } else {
                   11371: #
                   11372: # Not importing, some other kind of non-package, non-library start tag
                   11373: # 
                   11374:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11375:                         if (defined($token->[2]->{'id'})) {
                   11376:                             $unikey.='_'.$token->[2]->{'id'};
                   11377:                         }
1.339     albertel 11378: 			if (defined($token->[2]->{'name'})) { 
                   11379: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   11380: 			}
                   11381: 			$metathesekeys{$unikey}=1;
1.736     albertel 11382: 			foreach my $param (@{$token->[3]}) {
                   11383: 			    $metaentry{':'.$unikey.'.'.$param} =
                   11384: 				$token->[2]->{$param};
1.339     albertel 11385: 			}
                   11386: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 11387: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 11388: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   11389: 		 # only ws inside the tag, and not in default, so use default
                   11390: 		 # as value
1.599     albertel 11391: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 11392: 			} elsif ( $internaltext =~ /\S/ ) {
                   11393: 		  # something interesting inside the tag
                   11394: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 11395: 			} else {
1.908     albertel 11396: 		  # no interesting values, don't set a default
1.339     albertel 11397: 			}
1.172     www      11398: # end of not-a-package not-a-library import
1.339     albertel 11399: 		    }
1.172     www      11400: # end of not-a-package start tag
1.339     albertel 11401: 		}
1.172     www      11402: # the next is the end of "start tag"
1.339     albertel 11403: 	    }
                   11404: 	}
1.483     albertel 11405: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 11406: 	$extension = lc($extension);
                   11407: 	if ($extension eq 'htm') { $extension='html'; }
                   11408: 
1.737     albertel 11409: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 11410: 	    #no specific packages #how's our extension
                   11411: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 11412: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 11413: 					 \%metathesekeys);
                   11414: 	}
1.883     albertel 11415: 
                   11416: 	if (!exists($metaentry{':packages'})
                   11417: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 11418: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 11419: 		#no specific packages well let's get default then
                   11420: 		if ($key!~/^default&/) { next; }
1.488     albertel 11421: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 11422: 					     \%metathesekeys);
                   11423: 	    }
                   11424: 	}
1.338     www      11425: # are there custom rights to evaluate
1.599     albertel 11426: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 11427: 
1.338     www      11428:     #
                   11429:     # Importing a rights file here
1.339     albertel 11430:     #
                   11431: 	    unless ($depthcount) {
1.599     albertel 11432: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 11433: 		my $dir=$filename;
                   11434: 		$dir=~s|[^/]*$||;
                   11435: 		$location=&filelocation($dir,$location);
1.736     albertel 11436: 		my $rights_metadata =
                   11437: 		    &metadata($uri,'keys',$location,'_rights',
                   11438: 			      $depthcount+1);
                   11439: 		foreach my $rights (split(',',$rights_metadata)) {
                   11440: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   11441: 		    $metathesekeys{$rights}=1;
1.339     albertel 11442: 		}
                   11443: 	    }
                   11444: 	}
1.737     albertel 11445: 	# uniqifiy package listing
                   11446: 	my %seen;
                   11447: 	my @uniq_packages =
                   11448: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   11449: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   11450: 
1.1172.2.99  raeburn  11451:         if (($importedresponses) || ($importedparts)) {
                   11452:             if ($importedparts) {
1.1070    www      11453: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  11454:                 $metaentry{':partorder'}='';
                   11455:                 $metathesekeys{'partorder'}=1;
                   11456:             }
                   11457:             if ($importedresponses) {
                   11458: # We had imported responses and need to rebuild responseorder
                   11459:                 $metaentry{':responseorder'}='';
                   11460:                 $metathesekeys{'responseorder'}=1;
                   11461:             }
                   11462:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   11463:                 my $origid = $origfiletagids[$index+1];
                   11464:                 if ($origfiletagids[$index] eq 'part') {
                   11465: # Original part, part of the problem
                   11466:                     if ($importedparts) {
                   11467:                         $metaentry{':partorder'}.=','.$origid;
                   11468:                     }
                   11469:                 } elsif ($origfiletagids[$index] eq 'import') {
                   11470:                     if ($importedparts) {
                   11471: # We have imported parts at this position
                   11472:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   11473:                     }
                   11474:                     if ($importedresponses) {
                   11475: # We have imported responses at this position
                   11476:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   11477:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   11478:                         }
                   11479:                     }
                   11480:                 } else {
                   11481: # Original response item, part of the problem
                   11482:                     if ($importedresponses) {
                   11483:                         $metaentry{':responseorder'}.=','.$origid;
                   11484:                     }
                   11485:                 }
                   11486:             }
                   11487:             if ($importedparts) {
                   11488:                 $metaentry{':partorder'}=~s/^\,//;
                   11489:             }
                   11490:             if ($importedresponses) {
                   11491:                 $metaentry{':responseorder'}=~s/^\,//;
                   11492:             }
1.1070    www      11493:         }
                   11494: 
1.737     albertel 11495: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 11496: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  11497: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 11498: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      11499: # this is the end of "was not already recently cached
1.71      www      11500:     }
1.599     albertel 11501:     return $metaentry{':'.$what};
1.261     albertel 11502: }
                   11503: 
1.488     albertel 11504: sub metadata_create_package_def {
1.483     albertel 11505:     my ($uri,$key,$package,$metathesekeys)=@_;
                   11506:     my ($pack,$name,$subp)=split(/\&/,$key);
                   11507:     if ($subp eq 'default') { next; }
                   11508:     
1.599     albertel 11509:     if (defined($metaentry{':packages'})) {
                   11510: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 11511:     } else {
1.599     albertel 11512: 	$metaentry{':packages'}=$package;
1.483     albertel 11513:     }
                   11514:     my $value=$packagetab{$key};
                   11515:     my $unikey;
                   11516:     $unikey='parameter_0_'.$name;
1.599     albertel 11517:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 11518:     $$metathesekeys{$unikey}=1;
1.599     albertel 11519:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11520: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 11521:     }
1.599     albertel 11522:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   11523: 	$metaentry{':'.$unikey}=
                   11524: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 11525:     }
                   11526: }
                   11527: 
1.261     albertel 11528: sub metadata_generate_part0 {
                   11529:     my ($metadata,$metacache,$uri) = @_;
                   11530:     my %allnames;
1.737     albertel 11531:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 11532: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 11533: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   11534: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 11535: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 11536: 	    $allnames{$name}=$part;
                   11537: 	  }
                   11538: 	}
                   11539:     }
                   11540:     foreach my $name (keys(%allnames)) {
                   11541:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 11542:       my $key=":parameter_0_$name";
1.261     albertel 11543:       $$metacache{"$key.part"}='0';
                   11544:       $$metacache{"$key.name"}=$name;
1.428     albertel 11545:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 11546: 					   $allnames{$name}.'_'.$name.
                   11547: 					   '.type'};
1.428     albertel 11548:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 11549: 			     '.display'};
1.644     www      11550:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 11551:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 11552:       $$metacache{"$key.display"}=$olddis;
                   11553:     }
1.71      www      11554: }
                   11555: 
1.764     albertel 11556: # ------------------------------------------------------ Devalidate title cache
                   11557: 
                   11558: sub devalidate_title_cache {
                   11559:     my ($url)=@_;
                   11560:     if (!$env{'request.course.id'}) { return; }
                   11561:     my $symb=&symbread($url);
                   11562:     if (!$symb) { return; }
                   11563:     my $key=$env{'request.course.id'}."\0".$symb;
                   11564:     &devalidate_cache_new('title',$key);
                   11565: }
                   11566: 
1.1014    droeschl 11567: # ------------------------------------------------- Get the title of a course
                   11568: 
                   11569: sub current_course_title {
                   11570:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   11571: }
1.301     www      11572: # ------------------------------------------------- Get the title of a resource
                   11573: 
                   11574: sub gettitle {
                   11575:     my $urlsymb=shift;
                   11576:     my $symb=&symbread($urlsymb);
1.534     albertel 11577:     if ($symb) {
1.620     albertel 11578: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 11579: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 11580: 	if (defined($cached)) { 
                   11581: 	    return $result;
                   11582: 	}
1.534     albertel 11583: 	my ($map,$resid,$url)=&decode_symb($symb);
                   11584: 	my $title='';
1.907     albertel 11585: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   11586: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   11587: 	} else {
                   11588: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11589: 		    &GDBM_READER(),0640)) {
                   11590: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   11591: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   11592: 		untie(%bighash);
                   11593: 	    }
1.534     albertel 11594: 	}
                   11595: 	$title=~s/\&colon\;/\:/gs;
                   11596: 	if ($title) {
1.1159    www      11597: # Remember both $symb and $title for dynamic metadata
                   11598:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      11599:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      11600: # Cache this title and then return it
1.599     albertel 11601: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 11602: 	}
                   11603: 	$urlsymb=$url;
                   11604:     }
                   11605:     my $title=&metadata($urlsymb,'title');
                   11606:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   11607:     return $title;
1.301     www      11608: }
1.613     albertel 11609: 
1.614     albertel 11610: sub get_slot {
                   11611:     my ($which,$cnum,$cdom)=@_;
                   11612:     if (!$cnum || !$cdom) {
1.790     albertel 11613: 	(undef,my $courseid)=&whichuser();
1.620     albertel 11614: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   11615: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 11616:     }
1.703     albertel 11617:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   11618:     my %slotinfo;
                   11619:     if (exists($remembered{$key})) {
                   11620: 	$slotinfo{$which} = $remembered{$key};
                   11621:     } else {
                   11622: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   11623: 	&Apache::lonhomework::showhash(%slotinfo);
                   11624: 	my ($tmp)=keys(%slotinfo);
                   11625: 	if ($tmp=~/^error:/) { return (); }
                   11626: 	$remembered{$key} = $slotinfo{$which};
                   11627:     }
1.616     albertel 11628:     if (ref($slotinfo{$which}) eq 'HASH') {
                   11629: 	return %{$slotinfo{$which}};
                   11630:     }
                   11631:     return $slotinfo{$which};
1.614     albertel 11632: }
1.1150    raeburn  11633: 
                   11634: sub get_reservable_slots {
                   11635:     my ($cnum,$cdom,$uname,$udom) = @_;
                   11636:     my $now = time;
                   11637:     my $reservable_info;
                   11638:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   11639:     if (exists($remembered{$key})) {
                   11640:         $reservable_info = $remembered{$key};
                   11641:     } else {
                   11642:         my %resv;
                   11643:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   11644:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   11645:         $reservable_info = \%resv;
                   11646:         $remembered{$key} = $reservable_info;
                   11647:     }
                   11648:     return $reservable_info;
                   11649: }
                   11650: 
                   11651: sub get_course_slots {
                   11652:     my ($cnum,$cdom) = @_;
                   11653:     my $hashid=$cnum.':'.$cdom;
                   11654:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   11655:     if (defined($cached)) {
                   11656:         if (ref($result) eq 'HASH') {
                   11657:             return %{$result};
                   11658:         }
                   11659:     } else {
                   11660:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   11661:         my ($tmp) = keys(%slots);
                   11662:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  11663:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  11664:             return %slots;
                   11665:         }
                   11666:     }
                   11667:     return;
                   11668: }
                   11669: 
                   11670: sub devalidate_slots_cache {
                   11671:     my ($cnum,$cdom)=@_;
                   11672:     my $hashid=$cnum.':'.$cdom;
                   11673:     &devalidate_cache_new('allslots',$hashid);
                   11674: }
                   11675: 
1.1172.2.8  raeburn  11676: sub get_coursechange {
                   11677:     my ($cdom,$cnum) = @_;
                   11678:     if ($cdom eq '' || $cnum eq '') {
                   11679:         return unless ($env{'request.course.id'});
                   11680:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   11681:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11682:     }
                   11683:     my $hashid=$cdom.'_'.$cnum;
                   11684:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   11685:     if ((defined($cached)) && ($change ne '')) {
                   11686:         return $change;
                   11687:     } else {
                   11688:         my %crshash;
                   11689:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   11690:         if ($crshash{'internal.contentchange'} eq '') {
                   11691:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   11692:             if ($change eq '') {
                   11693:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   11694:                 $change = $crshash{'internal.created'};
                   11695:             }
                   11696:         } else {
                   11697:             $change = $crshash{'internal.contentchange'};
                   11698:         }
                   11699:         my $cachetime = 600;
                   11700:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   11701:     }
                   11702:     return $change;
                   11703: }
                   11704: 
                   11705: sub devalidate_coursechange_cache {
                   11706:     my ($cnum,$cdom)=@_;
                   11707:     my $hashid=$cnum.':'.$cdom;
                   11708:     &devalidate_cache_new('crschange',$hashid);
                   11709: }
                   11710: 
1.31      www      11711: # ------------------------------------------------- Update symbolic store links
                   11712: 
                   11713: sub symblist {
                   11714:     my ($mapname,%newhash)=@_;
1.438     www      11715:     $mapname=&deversion(&declutter($mapname));
1.31      www      11716:     my %hash;
1.620     albertel 11717:     if (($env{'request.course.fn'}) && (%newhash)) {
                   11718:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11719:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  11720: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 11721: 		next if ($url eq 'last_known'
                   11722: 			 && $env{'form.no_update_last_known'});
                   11723: 		$hash{declutter($url)}=&encode_symb($mapname,
                   11724: 						    $newhash{$url}->[1],
                   11725: 						    $newhash{$url}->[0]);
1.191     harris41 11726:             }
1.31      www      11727:             if (untie(%hash)) {
                   11728: 		return 'ok';
                   11729:             }
                   11730:         }
                   11731:     }
                   11732:     return 'error';
1.212     www      11733: }
                   11734: 
                   11735: # --------------------------------------------------------------- Verify a symb
                   11736: 
                   11737: sub symbverify {
1.1172.2.11  raeburn  11738:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      11739:     my $thisfn=$thisurl;
1.439     www      11740:     $thisfn=&declutter($thisfn);
1.215     www      11741: # direct jump to resource in page or to a sequence - will construct own symbs
                   11742:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   11743: # check URL part
1.409     www      11744:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      11745: 
1.431     www      11746:     unless ($url eq $thisfn) { return 0; }
1.213     www      11747: 
1.216     www      11748:     $symb=&symbclean($symb);
1.510     www      11749:     $thisurl=&deversion($thisurl);
1.439     www      11750:     $thisfn=&deversion($thisfn);
1.213     www      11751: 
                   11752:     my %bighash;
                   11753:     my $okay=0;
1.431     www      11754: 
1.620     albertel 11755:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11756:                             &GDBM_READER(),0640)) {
1.1172.2.13  raeburn  11757:         my $noclutter;
1.1032    raeburn  11758:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   11759:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  11760:             if ($map =~ m{^uploaded/.+\.page$}) {
                   11761:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   11762:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   11763:                 $noclutter = 1;
                   11764:             }
                   11765:         }
                   11766:         my $ids;
                   11767:         if ($noclutter) {
                   11768:             $ids=$bighash{'ids_'.$thisurl};
                   11769:         } else {
                   11770:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  11771:         }
1.1102    raeburn  11772:         unless ($ids) {
1.1172.2.13  raeburn  11773:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  11774:             $ids=$bighash{$idkey};
1.216     www      11775:         }
                   11776:         if ($ids) {
                   11777: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  11778:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   11779:                 $symb =~ s/\?.+$//;
                   11780:             }
1.800     albertel 11781: 	    foreach my $id (split(/\,/,$ids)) {
                   11782: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      11783:                if (
                   11784:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  11785:    eq $symb) {
1.1172.2.11  raeburn  11786:                    if (ref($encstate)) {
                   11787:                        $$encstate = $bighash{'encrypted_'.$id};
                   11788:                    }
1.1172.2.13  raeburn  11789:                    if (($env{'request.role.adv'}) ||
                   11790:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  11791:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  11792:                        $okay=1;
                   11793:                        last;
                   11794:                    }
                   11795:                }
                   11796:            }
1.216     www      11797:         }
1.213     www      11798: 	untie(%bighash);
                   11799:     }
                   11800:     return $okay;
1.31      www      11801: }
                   11802: 
1.210     www      11803: # --------------------------------------------------------------- Clean-up symb
                   11804: 
                   11805: sub symbclean {
                   11806:     my $symb=shift;
1.568     albertel 11807:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      11808: # remove version from map
                   11809:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      11810: 
1.210     www      11811: # remove version from URL
                   11812:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      11813: 
1.507     www      11814: # remove wrapper
                   11815: 
1.510     www      11816:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 11817:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      11818:     return $symb;
1.409     www      11819: }
                   11820: 
                   11821: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 11822: 
                   11823: sub encode_symb {
                   11824:     my ($map,$resid,$url)=@_;
                   11825:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   11826: }
1.409     www      11827: 
                   11828: sub decode_symb {
1.568     albertel 11829:     my $symb=shift;
                   11830:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   11831:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      11832:     return (&fixversion($map),$resid,&fixversion($url));
                   11833: }
                   11834: 
                   11835: sub fixversion {
                   11836:     my $fn=shift;
1.609     banghart 11837:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      11838:     my %bighash;
                   11839:     my $uri=&clutter($fn);
1.620     albertel 11840:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      11841: # is this cached?
1.599     albertel 11842:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      11843:     if (defined($cached)) { return $result; }
                   11844: # unfortunately not cached, or expired
1.620     albertel 11845:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      11846: 	    &GDBM_READER(),0640)) {
                   11847:  	if ($bighash{'version_'.$uri}) {
                   11848:  	    my $version=$bighash{'version_'.$uri};
1.444     www      11849:  	    unless (($version eq 'mostrecent') || 
                   11850: 		    ($version==&getversion($uri))) {
1.440     www      11851:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   11852:  	    }
                   11853:  	}
                   11854:  	untie %bighash;
1.413     www      11855:     }
1.599     albertel 11856:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      11857: }
                   11858: 
                   11859: sub deversion {
                   11860:     my $url=shift;
                   11861:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   11862:     return $url;
1.210     www      11863: }
                   11864: 
1.31      www      11865: # ------------------------------------------------------ Return symb list entry
                   11866: 
                   11867: sub symbread {
1.1172.2.66  raeburn  11868:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54  raeburn  11869:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66  raeburn  11870:     if (defined($env{$cache_str})) {
                   11871:         if ($ignorecachednull) {
                   11872:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   11873:         } else {
                   11874:             return $env{$cache_str};
                   11875:         }
                   11876:     }
1.242     www      11877: # no filename provided? try from environment
1.1172.2.54  raeburn  11878:     unless ($thisfn) {
1.620     albertel 11879:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  11880:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   11881:         }
                   11882:         $thisfn=$env{'request.filename'};
1.44      www      11883:     }
1.569     albertel 11884:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      11885: # is that filename actually a symb? Verify, clean, and return
                   11886:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 11887: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 11888: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 11889: 	}
1.242     www      11890:     }
1.44      www      11891:     $thisfn=declutter($thisfn);
1.31      www      11892:     my %hash;
1.37      www      11893:     my %bighash;
                   11894:     my $syval='';
1.620     albertel 11895:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  11896:         my $targetfn = $thisfn;
1.609     banghart 11897:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  11898:             $targetfn = 'adm/wrapper/'.$thisfn;
                   11899:         }
1.687     albertel 11900: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   11901: 	    $targetfn=$1;
                   11902: 	}
1.620     albertel 11903:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11904:                       &GDBM_READER(),0640)) {
1.481     raeburn  11905: 	    $syval=$hash{$targetfn};
1.37      www      11906:             untie(%hash);
                   11907:         }
                   11908: # ---------------------------------------------------------- There was an entry
                   11909:         if ($syval) {
1.601     albertel 11910: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 11911: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  11912: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11913: 		    #return $env{$cache_str}='';
1.601     albertel 11914: 		#}    
                   11915: 		#$syval.=$1;
                   11916: 	    #}
1.37      www      11917:         } else {
                   11918: # ------------------------------------------------------- Was not in symb table
1.620     albertel 11919:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11920:                             &GDBM_READER(),0640)) {
1.37      www      11921: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      11922:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      11923:               unless ($ids) { 
                   11924:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      11925:               }
                   11926:               unless ($ids) {
                   11927: # alias?
                   11928: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      11929:               }
1.37      www      11930:               if ($ids) {
                   11931: # ------------------------------------------------------------------- Has ID(s)
                   11932:                  my @possibilities=split(/\,/,$ids);
1.39      www      11933:                  if ($#possibilities==0) {
                   11934: # ----------------------------------------------- There is only one possibility
1.37      www      11935: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 11936: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11937: 						    $resid,$thisfn);
1.1172.2.66  raeburn  11938:                      if (ref($possibles) eq 'HASH') {
                   11939:                          $possibles->{$syval} = 1;
                   11940:                      }
                   11941:                      if ($checkforblock) {
                   11942:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   11943:                          if (@blockers) {
                   11944:                              $syval = '';
                   11945:                              return;
                   11946:                          }
                   11947:                      }
                   11948:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      11949: # ------------------------------------------ There is more than one possibility
                   11950:                      my $realpossible=0;
1.800     albertel 11951:                      foreach my $id (@possibilities) {
                   11952: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  11953:                          my $canaccess;
                   11954:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   11955:                              $canaccess = 1;
                   11956:                          } else {
                   11957:                              $canaccess = &allowed('bre',$file);
                   11958:                          }
                   11959:                          if ($canaccess) {
                   11960:          		     my ($mapid,$resid)=split(/\./,$id);
                   11961:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   11962:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11963:                                                              $resid,$thisfn);
                   11964:                                  if (ref($possibles) eq 'HASH') {
                   11965:                                      $possibles->{$syval} = 1;
                   11966:                                  }
                   11967:                                  if ($checkforblock) {
                   11968:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   11969:                                      unless (@blockers > 0) {
                   11970:                                          $syval = $poss_syval;
                   11971:                                          $realpossible++;
                   11972:                                      }
                   11973:                                  } else {
                   11974:                                      $syval = $poss_syval;
                   11975:                                      $realpossible++;
                   11976:                                  }
                   11977:                              }
1.39      www      11978: 			 }
1.191     harris41 11979:                      }
1.39      www      11980: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      11981:                  } else {
                   11982:                      $syval='';
1.37      www      11983:                  }
                   11984: 	      }
1.1172.2.66  raeburn  11985:               untie(%bighash);
1.481     raeburn  11986:            }
1.31      www      11987:         }
1.62      www      11988:         if ($syval) {
1.620     albertel 11989: 	    return $env{$cache_str}=$syval;
1.62      www      11990:         }
1.31      www      11991:     }
1.949     raeburn  11992:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11993:     return $env{$cache_str}='';
1.31      www      11994: }
                   11995: 
                   11996: # ---------------------------------------------------------- Return random seed
                   11997: 
1.32      www      11998: sub numval {
                   11999:     my $txt=shift;
                   12000:     $txt=~tr/A-J/0-9/;
                   12001:     $txt=~tr/a-j/0-9/;
                   12002:     $txt=~tr/K-T/0-9/;
                   12003:     $txt=~tr/k-t/0-9/;
                   12004:     $txt=~tr/U-Z/0-5/;
                   12005:     $txt=~tr/u-z/0-5/;
                   12006:     $txt=~s/\D//g;
1.564     albertel 12007:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12008:     return int($txt);
1.368     albertel 12009: }
                   12010: 
1.484     albertel 12011: sub numval2 {
                   12012:     my $txt=shift;
                   12013:     $txt=~tr/A-J/0-9/;
                   12014:     $txt=~tr/a-j/0-9/;
                   12015:     $txt=~tr/K-T/0-9/;
                   12016:     $txt=~tr/k-t/0-9/;
                   12017:     $txt=~tr/U-Z/0-5/;
                   12018:     $txt=~tr/u-z/0-5/;
                   12019:     $txt=~s/\D//g;
                   12020:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12021:     my $total;
                   12022:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12023:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12024:     return int($total);
                   12025: }
                   12026: 
1.575     albertel 12027: sub numval3 {
                   12028:     use integer;
                   12029:     my $txt=shift;
                   12030:     $txt=~tr/A-J/0-9/;
                   12031:     $txt=~tr/a-j/0-9/;
                   12032:     $txt=~tr/K-T/0-9/;
                   12033:     $txt=~tr/k-t/0-9/;
                   12034:     $txt=~tr/U-Z/0-5/;
                   12035:     $txt=~tr/u-z/0-5/;
                   12036:     $txt=~s/\D//g;
                   12037:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12038:     my $total;
                   12039:     foreach my $val (@txts) { $total+=$val; }
                   12040:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12041:     return $total;
                   12042: }
                   12043: 
1.675     albertel 12044: sub digest {
                   12045:     my ($data)=@_;
                   12046:     my $digest=&Digest::MD5::md5($data);
                   12047:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12048:     my ($e,$f);
                   12049:     {
                   12050:         use integer;
                   12051:         $e=($a+$b);
                   12052:         $f=($c+$d);
                   12053:         if ($_64bit) {
                   12054:             $e=(($e<<32)>>32);
                   12055:             $f=(($f<<32)>>32);
                   12056:         }
                   12057:     }
                   12058:     if (wantarray) {
                   12059: 	return ($e,$f);
                   12060:     } else {
                   12061: 	my $g;
                   12062: 	{
                   12063: 	    use integer;
                   12064: 	    $g=($e+$f);
                   12065: 	    if ($_64bit) {
                   12066: 		$g=(($g<<32)>>32);
                   12067: 	    }
                   12068: 	}
                   12069: 	return $g;
                   12070:     }
                   12071: }
                   12072: 
1.368     albertel 12073: sub latest_rnd_algorithm_id {
1.675     albertel 12074:     return '64bit5';
1.366     albertel 12075: }
1.32      www      12076: 
1.503     albertel 12077: sub get_rand_alg {
                   12078:     my ($courseid)=@_;
1.790     albertel 12079:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12080:     if ($courseid) {
1.620     albertel 12081: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12082:     }
                   12083:     return &latest_rnd_algorithm_id();
                   12084: }
                   12085: 
1.562     albertel 12086: sub validCODE {
                   12087:     my ($CODE)=@_;
                   12088:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12089:     return 0;
                   12090: }
                   12091: 
1.491     albertel 12092: sub getCODE {
1.620     albertel 12093:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12094:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12095: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12096: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12097: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12098:     }
                   12099:     return undef;
                   12100: }
1.1133    foxr     12101: #
                   12102: #  Determines the random seed for a specific context:
                   12103: #
                   12104: # parameters:
                   12105: #   symb      - in course context the symb for the seed.
                   12106: #   course_id - The course id of the form domain_coursenum.
                   12107: #   domain    - Domain for the user.
                   12108: #   course    - Course for the user.
                   12109: #   cenv      - environment of the course.
                   12110: #
                   12111: # NOTE:
                   12112: #   All parameters are picked out of the environment if missing
                   12113: #   or not defined.
                   12114: #   If a symb cannot be determined the current time is used instead.
                   12115: #
                   12116: #  For a given well defined symb, courside, domain, username,
                   12117: #  and course environment, the seed is reproducible.
                   12118: #
1.31      www      12119: sub rndseed {
1.1133    foxr     12120:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12121:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12122:     if (!defined($symb)) {
1.366     albertel 12123: 	unless ($symb=$wsymb) { return time; }
                   12124:     }
1.1146    foxr     12125:     if (!defined $courseid) { 
                   12126: 	$courseid=$wcourseid; 
                   12127:     }
                   12128:     if (!defined $domain) { $domain=$wdomain; }
                   12129:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12130: 
                   12131:     my $which;
                   12132:     if (defined($cenv->{'rndseed'})) {
                   12133: 	$which = $cenv->{'rndseed'};
                   12134:     } else {
                   12135: 	$which =&get_rand_alg($courseid);
                   12136:     }
1.491     albertel 12137:     if (defined(&getCODE())) {
1.675     albertel 12138: 	if ($which eq '64bit5') {
                   12139: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12140: 	} elsif ($which eq '64bit4') {
1.575     albertel 12141: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12142: 	} else {
                   12143: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12144: 	}
1.675     albertel 12145:     } elsif ($which eq '64bit5') {
                   12146: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12147:     } elsif ($which eq '64bit4') {
                   12148: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12149:     } elsif ($which eq '64bit3') {
                   12150: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12151:     } elsif ($which eq '64bit2') {
                   12152: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12153:     } elsif ($which eq '64bit') {
                   12154: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12155:     }
                   12156:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12157: }
                   12158: 
                   12159: sub rndseed_32bit {
                   12160:     my ($symb,$courseid,$domain,$username)=@_;
                   12161:     {
                   12162: 	use integer;
                   12163: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12164: 	my $symbseed=numval($symb) << 22;
                   12165: 	my $namechck=unpack("%32C*",$username) << 17;
                   12166: 	my $nameseed=numval($username) << 12;
                   12167: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12168: 	my $courseseed=unpack("%32C*",$courseid);
                   12169: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12170: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12171: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12172: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12173: 	return $num;
                   12174:     }
                   12175: }
                   12176: 
                   12177: sub rndseed_64bit {
                   12178:     my ($symb,$courseid,$domain,$username)=@_;
                   12179:     {
                   12180: 	use integer;
                   12181: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12182: 	my $symbseed=numval($symb) << 10;
                   12183: 	my $namechck=unpack("%32S*",$username);
                   12184: 	
                   12185: 	my $nameseed=numval($username) << 21;
                   12186: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12187: 	my $courseseed=unpack("%32S*",$courseid);
                   12188: 	
                   12189: 	my $num1=$symbchck+$symbseed+$namechck;
                   12190: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12191: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12192: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12193: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12194: 	return "$num1,$num2";
1.155     albertel 12195:     }
1.366     albertel 12196: }
                   12197: 
1.443     albertel 12198: sub rndseed_64bit2 {
                   12199:     my ($symb,$courseid,$domain,$username)=@_;
                   12200:     {
                   12201: 	use integer;
                   12202: 	# strings need to be an even # of cahracters long, it it is odd the
                   12203:         # last characters gets thrown away
                   12204: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12205: 	my $symbseed=numval($symb) << 10;
                   12206: 	my $namechck=unpack("%32S*",$username.' ');
                   12207: 	
                   12208: 	my $nameseed=numval($username) << 21;
1.501     albertel 12209: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12210: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12211: 	
                   12212: 	my $num1=$symbchck+$symbseed+$namechck;
                   12213: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12214: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12215: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12216: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12217: 	return "$num1,$num2";
                   12218:     }
                   12219: }
                   12220: 
                   12221: sub rndseed_64bit3 {
                   12222:     my ($symb,$courseid,$domain,$username)=@_;
                   12223:     {
                   12224: 	use integer;
                   12225: 	# strings need to be an even # of cahracters long, it it is odd the
                   12226:         # last characters gets thrown away
                   12227: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12228: 	my $symbseed=numval2($symb) << 10;
                   12229: 	my $namechck=unpack("%32S*",$username.' ');
                   12230: 	
                   12231: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12232: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12233: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12234: 	
                   12235: 	my $num1=$symbchck+$symbseed+$namechck;
                   12236: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12237: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12238: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12239: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12240: 	
1.503     albertel 12241: 	return "$num1:$num2";
1.443     albertel 12242:     }
                   12243: }
                   12244: 
1.575     albertel 12245: sub rndseed_64bit4 {
                   12246:     my ($symb,$courseid,$domain,$username)=@_;
                   12247:     {
                   12248: 	use integer;
                   12249: 	# strings need to be an even # of cahracters long, it it is odd the
                   12250:         # last characters gets thrown away
                   12251: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12252: 	my $symbseed=numval3($symb) << 10;
                   12253: 	my $namechck=unpack("%32S*",$username.' ');
                   12254: 	
                   12255: 	my $nameseed=numval3($username) << 21;
                   12256: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12257: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12258: 	
                   12259: 	my $num1=$symbchck+$symbseed+$namechck;
                   12260: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12261: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12262: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12263: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12264: 	
1.575     albertel 12265: 	return "$num1:$num2";
                   12266:     }
                   12267: }
                   12268: 
1.675     albertel 12269: sub rndseed_64bit5 {
                   12270:     my ($symb,$courseid,$domain,$username)=@_;
                   12271:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12272:     return "$num1:$num2";
                   12273: }
                   12274: 
1.366     albertel 12275: sub rndseed_CODE_64bit {
                   12276:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12277:     {
1.366     albertel 12278: 	use integer;
1.443     albertel 12279: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12280: 	my $symbseed=numval2($symb);
1.491     albertel 12281: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12282: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12283: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12284: 	my $num1=$symbseed+$CODEchck;
                   12285: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12286: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12287: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12288: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12289: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12290: 	return "$num1:$num2";
1.366     albertel 12291:     }
                   12292: }
                   12293: 
1.575     albertel 12294: sub rndseed_CODE_64bit4 {
                   12295:     my ($symb,$courseid,$domain,$username)=@_;
                   12296:     {
                   12297: 	use integer;
                   12298: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12299: 	my $symbseed=numval3($symb);
                   12300: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12301: 	my $CODEseed=numval3(&getCODE());
                   12302: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12303: 	my $num1=$symbseed+$CODEchck;
                   12304: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12305: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12306: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12307: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12308: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12309: 	return "$num1:$num2";
                   12310:     }
                   12311: }
                   12312: 
1.675     albertel 12313: sub rndseed_CODE_64bit5 {
                   12314:     my ($symb,$courseid,$domain,$username)=@_;
                   12315:     my $code = &getCODE();
                   12316:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12317:     return "$num1:$num2";
                   12318: }
                   12319: 
1.366     albertel 12320: sub setup_random_from_rndseed {
                   12321:     my ($rndseed)=@_;
1.503     albertel 12322:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  12323: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12324:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12325:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   12326:         } else {
                   12327:             &Math::Random::random_set_seed($num1,$num2);
                   12328:         }
1.366     albertel 12329:     } else {
                   12330: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12331:     }
1.36      albertel 12332: }
                   12333: 
1.474     albertel 12334: sub latest_receipt_algorithm_id {
1.835     albertel 12335:     return 'receipt3';
1.474     albertel 12336: }
                   12337: 
1.480     www      12338: sub recunique {
                   12339:     my $fucourseid=shift;
                   12340:     my $unique;
1.835     albertel 12341:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   12342: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12343: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      12344:     } else {
                   12345: 	$unique=$perlvar{'lonReceipt'};
                   12346:     }
                   12347:     return unpack("%32C*",$unique);
                   12348: }
                   12349: 
                   12350: sub recprefix {
                   12351:     my $fucourseid=shift;
                   12352:     my $prefix;
1.835     albertel 12353:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   12354: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12355: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      12356:     } else {
                   12357: 	$prefix=$perlvar{'lonHostID'};
                   12358:     }
                   12359:     return unpack("%32C*",$prefix);
                   12360: }
                   12361: 
1.76      www      12362: sub ireceipt {
1.474     albertel 12363:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 12364: 
                   12365:     my $return =&recprefix($fucourseid).'-';
                   12366: 
                   12367:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   12368: 	$env{'request.state'} eq 'construct') {
                   12369: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   12370: 	return $return;
                   12371:     }
                   12372: 
1.76      www      12373:     my $cuname=unpack("%32C*",$funame);
                   12374:     my $cudom=unpack("%32C*",$fudom);
                   12375:     my $cucourseid=unpack("%32C*",$fucourseid);
                   12376:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      12377:     my $cunique=&recunique($fucourseid);
1.474     albertel 12378:     my $cpart=unpack("%32S*",$part);
1.835     albertel 12379:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   12380: 
1.790     albertel 12381: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 12382: 			       
                   12383: 	$return.= ($cunique%$cuname+
                   12384: 		   $cunique%$cudom+
                   12385: 		   $cusymb%$cuname+
                   12386: 		   $cusymb%$cudom+
                   12387: 		   $cucourseid%$cuname+
                   12388: 		   $cucourseid%$cudom+
                   12389: 		   $cpart%$cuname+
                   12390: 		   $cpart%$cudom);
                   12391:     } else {
                   12392: 	$return.= ($cunique%$cuname+
                   12393: 		   $cunique%$cudom+
                   12394: 		   $cusymb%$cuname+
                   12395: 		   $cusymb%$cudom+
                   12396: 		   $cucourseid%$cuname+
                   12397: 		   $cucourseid%$cudom);
                   12398:     }
                   12399:     return $return;
1.76      www      12400: }
                   12401: 
                   12402: sub receipt {
1.474     albertel 12403:     my ($part)=@_;
1.790     albertel 12404:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 12405:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      12406: }
1.260     ng       12407: 
1.790     albertel 12408: sub whichuser {
                   12409:     my ($passedsymb)=@_;
                   12410:     my ($symb,$courseid,$domain,$name,$publicuser);
                   12411:     if (defined($env{'form.grade_symb'})) {
                   12412: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   12413: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   12414: 	if (!$allowed &&
                   12415: 	    exists($env{'request.course.sec'}) &&
                   12416: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   12417: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   12418: 			      '/'.$env{'request.course.sec'});
                   12419: 	}
                   12420: 	if ($allowed) {
                   12421: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   12422: 	    $courseid=$tmp_courseid;
                   12423: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   12424: 	    ($name)=&get_env_multiple('form.grade_username');
                   12425: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   12426: 	}
                   12427:     }
                   12428:     if (!$passedsymb) {
                   12429: 	$symb=&symbread();
                   12430:     } else {
                   12431: 	$symb=$passedsymb;
                   12432:     }
                   12433:     $courseid=$env{'request.course.id'};
                   12434:     $domain=$env{'user.domain'};
                   12435:     $name=$env{'user.name'};
                   12436:     if ($name eq 'public' && $domain eq 'public') {
                   12437: 	if (!defined($env{'form.username'})) {
                   12438: 	    $env{'form.username'}.=time.rand(10000000);
                   12439: 	}
                   12440: 	$name.=$env{'form.username'};
                   12441:     }
                   12442:     return ($symb,$courseid,$domain,$name,$publicuser);
                   12443: 
                   12444: }
                   12445: 
1.36      albertel 12446: # ------------------------------------------------------------ Serves up a file
1.472     albertel 12447: # returns either the contents of the file or 
                   12448: # -1 if the file doesn't exist
1.481     raeburn  12449: #
                   12450: # if the target is a file that was uploaded via DOCS, 
                   12451: # a check will be made to see if a current copy exists on the local server,
                   12452: # if it does this will be served, otherwise a copy will be retrieved from
                   12453: # the home server for the course and stored in /home/httpd/html/userfiles on
                   12454: # the local server.   
1.472     albertel 12455: 
1.36      albertel 12456: sub getfile {
1.538     albertel 12457:     my ($file) = @_;
1.609     banghart 12458:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 12459:     &repcopy($file);
                   12460:     return &readfile($file);
                   12461: }
                   12462: 
                   12463: sub repcopy_userfile {
                   12464:     my ($file)=@_;
1.1142    raeburn  12465:     my $londocroot = $perlvar{'lonDocRoot'};
                   12466:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  12467:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 12468:     my ($cdom,$cnum,$filename) = 
1.811     albertel 12469: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 12470:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   12471:     if (-e "$file") {
1.828     www      12472: # we already have a local copy, check it out
1.538     albertel 12473: 	my @fileinfo = stat($file);
1.828     www      12474: 	my $rtncode;
                   12475: 	my $info;
1.538     albertel 12476: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 12477: 	if ($lwpresp ne 'ok') {
1.828     www      12478: # there is no such file anymore, even though we had a local copy
1.482     albertel 12479: 	    if ($rtncode eq '404') {
1.538     albertel 12480: 		unlink($file);
1.482     albertel 12481: 	    }
                   12482: 	    return -1;
                   12483: 	}
                   12484: 	if ($info < $fileinfo[9]) {
1.828     www      12485: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  12486: 	    return 'ok';
1.828     www      12487: 	} else {
                   12488: # the file is outdated, get rid of it
                   12489: 	    unlink($file);
1.482     albertel 12490: 	}
1.828     www      12491:     }
                   12492: # one way or the other, at this point, we don't have the file
                   12493: # construct the correct path for the file
                   12494:     my @parts = ($cdom,$cnum); 
                   12495:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   12496: 	push @parts, split(/\//,$1);
                   12497:     }
                   12498:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   12499:     foreach my $part (@parts) {
                   12500: 	$path .= '/'.$part;
                   12501: 	if (!-e $path) {
                   12502: 	    mkdir($path,0770);
1.482     albertel 12503: 	}
                   12504:     }
1.828     www      12505: # now the path exists for sure
                   12506: # get a user agent
                   12507:     my $ua=new LWP::UserAgent;
                   12508:     my $transferfile=$file.'.in.transfer';
                   12509: # FIXME: this should flock
                   12510:     if (-e $transferfile) { return 'ok'; }
                   12511:     my $request;
                   12512:     $uri=~s/^\///;
1.980     raeburn  12513:     my $homeserver = &homeserver($cnum,$cdom);
                   12514:     my $protocol = $protocol{$homeserver};
                   12515:     $protocol = 'http' if ($protocol ne 'https');
                   12516:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      12517:     my $response=$ua->request($request,$transferfile);
                   12518: # did it work?
                   12519:     if ($response->is_error()) {
                   12520: 	unlink($transferfile);
                   12521: 	&logthis("Userfile repcopy failed for $uri");
                   12522: 	return -1;
                   12523:     }
                   12524: # worked, rename the transfer file
                   12525:     rename($transferfile,$file);
1.607     raeburn  12526:     return 'ok';
1.481     raeburn  12527: }
                   12528: 
1.517     albertel 12529: sub tokenwrapper {
                   12530:     my $uri=shift;
1.980     raeburn  12531:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 12532:     $uri=~s|^/||;
1.620     albertel 12533:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 12534:     my $token=$1;
1.552     albertel 12535:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   12536:     if ($udom && $uname && $file) {
                   12537: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  12538:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  12539:         my $homeserver = &homeserver($uname,$udom);
                   12540:         my $protocol = $protocol{$homeserver};
                   12541:         $protocol = 'http' if ($protocol ne 'https');
                   12542:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 12543:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   12544:                                '&tokenissued='.$perlvar{'lonHostID'};
                   12545:     } else {
                   12546:         return '/adm/notfound.html';
                   12547:     }
                   12548: }
                   12549: 
1.828     www      12550: # call with reqtype HEAD: get last modification time
                   12551: # call with reqtype GET: get the file contents
                   12552: # Do not call this with reqtype GET for large files! It loads everything into memory
                   12553: #
1.481     raeburn  12554: sub getuploaded {
                   12555:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   12556:     $uri=~s/^\///;
1.980     raeburn  12557:     my $homeserver = &homeserver($cnum,$cdom);
                   12558:     my $protocol = $protocol{$homeserver};
                   12559:     $protocol = 'http' if ($protocol ne 'https');
                   12560:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  12561:     my $ua=new LWP::UserAgent;
                   12562:     my $request=new HTTP::Request($reqtype,$uri);
                   12563:     my $response=$ua->request($request);
                   12564:     $$rtncode = $response->code;
1.482     albertel 12565:     if (! $response->is_success()) {
                   12566: 	return 'failed';
                   12567:     }      
                   12568:     if ($reqtype eq 'HEAD') {
1.486     www      12569: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 12570:     } elsif ($reqtype eq 'GET') {
                   12571: 	$$info = $response->content;
1.472     albertel 12572:     }
1.482     albertel 12573:     return 'ok';
1.36      albertel 12574: }
                   12575: 
1.481     raeburn  12576: sub readfile {
                   12577:     my $file = shift;
                   12578:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   12579:     my $fh;
1.1172.2.96  raeburn  12580:     open($fh,"<",$file);
1.481     raeburn  12581:     my $a='';
1.800     albertel 12582:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  12583:     return $a;
                   12584: }
                   12585: 
1.36      albertel 12586: sub filelocation {
1.590     banghart 12587:     my ($dir,$file) = @_;
                   12588:     my $location;
                   12589:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 12590: 
                   12591:     if ($file =~ m-^/adm/-) {
                   12592: 	$file=~s-^/adm/wrapper/-/-;
                   12593: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   12594:     }
1.882     albertel 12595: 
1.1139    www      12596:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  12597:         $location = $file;
1.609     banghart 12598:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 12599:         my ($udom,$uname,$filename)=
1.811     albertel 12600:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 12601:         my $home=&homeserver($uname,$udom);
                   12602:         my $is_me=0;
                   12603:         my @ids=&current_machine_ids();
                   12604:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   12605:         if ($is_me) {
1.1117    foxr     12606:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 12607:         } else {
                   12608:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   12609:   	      $udom.'/'.$uname.'/'.$filename;
                   12610:         }
1.882     albertel 12611:     } elsif ($file =~ m-^/adm/-) {
                   12612: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 12613:     } else {
                   12614:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      12615:         $file=~s:^/(res|priv)/:/:;
                   12616:         my $space=$1;
1.590     banghart 12617:         if ( !( $file =~ m:^/:) ) {
                   12618:             $location = $dir. '/'.$file;
                   12619:         } else {
1.1142    raeburn  12620:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 12621:         }
1.59      albertel 12622:     }
1.590     banghart 12623:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 12624:     while ($location=~m{/\.\./}) {
                   12625: 	if ($location =~ m{/[^/]+/\.\./}) {
                   12626: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   12627: 	} else {
                   12628: 	    $location=~ s{/\.\./}{/}g;
                   12629: 	}
                   12630:     } #remove dir/..
1.590     banghart 12631:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   12632:     return $location;
1.46      www      12633: }
1.36      albertel 12634: 
1.46      www      12635: sub hreflocation {
                   12636:     my ($dir,$file)=@_;
1.980     raeburn  12637:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 12638: 	$file=filelocation($dir,$file);
1.700     albertel 12639:     } elsif ($file=~m-^/adm/-) {
                   12640: 	$file=~s-^/adm/wrapper/-/-;
                   12641: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 12642:     }
                   12643:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   12644: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   12645:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  12646: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   12647: 	        {/uploaded/$1/$2/}x;
1.46      www      12648:     }
1.913     albertel 12649:     if ($file=~ m{^/userfiles/}) {
                   12650: 	$file =~ s{^/userfiles/}{/uploaded/};
                   12651:     }
1.462     albertel 12652:     return $file;
1.465     albertel 12653: }
                   12654: 
1.1139    www      12655: 
                   12656: 
                   12657: 
                   12658: 
1.465     albertel 12659: sub current_machine_domains {
1.853     albertel 12660:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   12661: }
                   12662: 
                   12663: sub machine_domains {
                   12664:     my ($hostname) = @_;
1.465     albertel 12665:     my @domains;
1.838     albertel 12666:     my %hostname = &all_hostnames();
1.465     albertel 12667:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  12668: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 12669: 	if ($hostname eq $name) {
1.844     albertel 12670: 	    push(@domains,&host_domain($id));
1.465     albertel 12671: 	}
                   12672:     }
                   12673:     return @domains;
                   12674: }
                   12675: 
                   12676: sub current_machine_ids {
1.853     albertel 12677:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   12678: }
                   12679: 
                   12680: sub machine_ids {
                   12681:     my ($hostname) = @_;
                   12682:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 12683:     my @ids;
1.888     albertel 12684:     my %name_to_host = &all_names();
1.889     albertel 12685:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   12686: 	return @{ $name_to_host{$hostname} };
                   12687:     }
                   12688:     return;
1.31      www      12689: }
                   12690: 
1.824     raeburn  12691: sub additional_machine_domains {
                   12692:     my @domains;
1.1172.2.96  raeburn  12693:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  12694:     while( my $line = <$fh>) {
                   12695:         $line =~ s/\s//g;
                   12696:         push(@domains,$line);
                   12697:     }
                   12698:     return @domains;
                   12699: }
                   12700: 
                   12701: sub default_login_domain {
                   12702:     my $domain = $perlvar{'lonDefDomain'};
                   12703:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   12704:     foreach my $posdom (&current_machine_domains(),
                   12705:                         &additional_machine_domains()) {
                   12706:         if (lc($posdom) eq lc($testdomain)) {
                   12707:             $domain=$posdom;
                   12708:             last;
                   12709:         }
                   12710:     }
                   12711:     return $domain;
                   12712: }
                   12713: 
1.1172.2.106! raeburn  12714: sub shared_institution {
        !          12715:     my ($dom) = @_;
        !          12716:     my $same_intdom;
        !          12717:     my $hostintdom = &internet_dom($perlvar{'lonHostID'});
        !          12718:     if ($hostintdom ne '') {
        !          12719:         my %iphost = &get_iphost();
        !          12720:         my $primary_id = &domain($dom,'primary');
        !          12721:         my $primary_ip = &get_host_ip($primary_id);
        !          12722:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
        !          12723:             foreach my $id (@{$iphost{$primary_ip}}) {
        !          12724:                 my $intdom = &internet_dom($id);
        !          12725:                 if ($intdom eq $hostintdom) {
        !          12726:                     $same_intdom = 1;
        !          12727:                     last;
        !          12728:                 }
        !          12729:             }
        !          12730:         }
        !          12731:     }
        !          12732:     return $same_intdom;
        !          12733: }
        !          12734: 
1.31      www      12735: # ------------------------------------------------------------- Declutters URLs
                   12736: 
                   12737: sub declutter {
                   12738:     my $thisfn=shift;
1.569     albertel 12739:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  12740:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   12741:         $thisfn=~s{^/home/httpd/html}{};
                   12742:     }
1.31      www      12743:     $thisfn=~s/^\///;
1.697     albertel 12744:     $thisfn=~s|^adm/wrapper/||;
                   12745:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      12746:     $thisfn=~s/^res\///;
1.1172    bisitz   12747:     $thisfn=~s/^priv\///;
1.1032    raeburn  12748:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   12749:         $thisfn=~s/\?.+$//;
                   12750:     }
1.268     www      12751:     return $thisfn;
                   12752: }
                   12753: 
                   12754: # ------------------------------------------------------------- Clutter up URLs
                   12755: 
                   12756: sub clutter {
                   12757:     my $thisfn='/'.&declutter(shift);
1.887     albertel 12758:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 12759: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      12760:        $thisfn='/res'.$thisfn; 
                   12761:     }
1.1031    raeburn  12762:     if ($thisfn !~m|^/adm|) {
                   12763: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 12764: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 12765: 	} else {
                   12766: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   12767: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 12768: 	    if ($embstyle eq 'ssi'
                   12769: 		|| ($embstyle eq 'hdn')
                   12770: 		|| ($embstyle eq 'rat')
                   12771: 		|| ($embstyle eq 'prv')
                   12772: 		|| ($embstyle eq 'ign')) {
                   12773: 		#do nothing with these
                   12774: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 12775: 		|| ($embstyle eq 'emb')
                   12776: 		|| ($embstyle eq 'wrp')) {
                   12777: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 12778: 	    } elsif ($embstyle eq 'unk'
                   12779: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 12780: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 12781: 	    } else {
1.718     www      12782: #		&logthis("Got a blank emb style");
1.695     albertel 12783: 	    }
1.694     albertel 12784: 	}
                   12785:     }
1.31      www      12786:     return $thisfn;
1.12      www      12787: }
                   12788: 
1.787     albertel 12789: sub clutter_with_no_wrapper {
                   12790:     my $uri = &clutter(shift);
                   12791:     if ($uri =~ m-^/adm/-) {
                   12792: 	$uri =~ s-^/adm/wrapper/-/-;
                   12793: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   12794:     }
                   12795:     return $uri;
                   12796: }
                   12797: 
1.557     albertel 12798: sub freeze_escape {
                   12799:     my ($value)=@_;
                   12800:     if (ref($value)) {
                   12801: 	$value=&nfreeze($value);
                   12802: 	return '__FROZEN__'.&escape($value);
                   12803:     }
                   12804:     return &escape($value);
                   12805: }
                   12806: 
1.11      www      12807: 
1.557     albertel 12808: sub thaw_unescape {
                   12809:     my ($value)=@_;
                   12810:     if ($value =~ /^__FROZEN__/) {
                   12811: 	substr($value,0,10,undef);
                   12812: 	$value=&unescape($value);
                   12813: 	return &thaw($value);
                   12814:     }
                   12815:     return &unescape($value);
                   12816: }
                   12817: 
1.436     albertel 12818: sub correct_line_ends {
                   12819:     my ($result)=@_;
                   12820:     $$result =~s/\r\n/\n/mg;
                   12821:     $$result =~s/\r/\n/mg;
1.415     albertel 12822: }
1.1       albertel 12823: # ================================================================ Main Program
                   12824: 
1.184     www      12825: sub goodbye {
1.204     albertel 12826:    &logthis("Starting Shut down");
1.443     albertel 12827: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 12828:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 12829: #converted
1.599     albertel 12830: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 12831:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   12832: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   12833: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 12834: #1.1 only
1.870     albertel 12835: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   12836: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   12837: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   12838: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   12839:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 12840:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   12841:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      12842:    &flushcourselogs();
                   12843:    &logthis("Shutting down");
                   12844: }
                   12845: 
1.852     albertel 12846: sub get_dns {
1.1172.2.17  raeburn  12847:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 12848:     if (!$ignore_cache) {
                   12849: 	my ($content,$cached)=
                   12850: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   12851: 	if ($cached) {
1.1172.2.17  raeburn  12852: 	    &$func($content,$hashref);
1.869     albertel 12853: 	    return;
                   12854: 	}
                   12855:     }
                   12856: 
                   12857:     my %alldns;
1.1172.2.96  raeburn  12858:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   12859:         foreach my $dns (<$config>) {
                   12860: 	    next if ($dns !~ /^\^(\S*)/x);
                   12861:             my $line = $1;
                   12862:             my ($host,$protocol) = split(/:/,$line);
                   12863:             if ($protocol ne 'https') {
                   12864:                 $protocol = 'http';
                   12865:             }
                   12866: 	    $alldns{$host} = $protocol;
1.979     raeburn  12867:         }
1.1172.2.96  raeburn  12868:         close($config);
1.869     albertel 12869:     }
                   12870:     while (%alldns) {
1.1172.2.52  raeburn  12871: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 12872: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  12873:         $ua->timeout(30);
1.979     raeburn  12874: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 12875: 	my $response=$ua->request($request);
1.979     raeburn  12876:         delete($alldns{$dns});
1.852     albertel 12877: 	next if ($response->is_error());
                   12878: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  12879:         unless ($nocache) {
1.1172.2.23  raeburn  12880: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  12881:         }
                   12882: 	&$func(\@content,$hashref);
1.869     albertel 12883: 	return;
1.852     albertel 12884:     }
1.871     albertel 12885:     my $which = (split('/',$url))[3];
                   12886:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  12887:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   12888:         my @content = <$config>;
                   12889:         &$func(\@content,$hashref);
                   12890:     }
1.1172.2.17  raeburn  12891:     return;
                   12892: }
                   12893: 
                   12894: # ------------------------------------------------------Get DNS checksums file
                   12895: sub parse_dns_checksums_tab {
                   12896:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  12897:     my $lonhost = $perlvar{'lonHostID'};
                   12898:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  12899:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  12900:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   12901:     my $webconfdir = '/etc/httpd/conf';
                   12902:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   12903:         $webconfdir = '/etc/apache2';
                   12904:     } elsif ($distro =~ /^sles(\d+)$/) {
                   12905:         if ($1 >= 10) {
                   12906:             $webconfdir = '/etc/apache2';
                   12907:         }
                   12908:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   12909:         if ($1 >= 10.0) {
                   12910:             $webconfdir = '/etc/apache2';
                   12911:         }
                   12912:     }
1.1172.2.17  raeburn  12913:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12914:     my (%chksum,%revnum);
                   12915:     if (ref($lines) eq 'ARRAY') {
                   12916:         chomp(@{$lines});
1.1172.2.34  raeburn  12917:         my $version = shift(@{$lines});
                   12918:         if ($version eq $release) {
1.1172.2.17  raeburn  12919:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  12920:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  12921:                 if ($file =~ m{^/etc/httpd/conf}) {
                   12922:                     if ($webconfdir eq '/etc/apache2') {
                   12923:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   12924:                     }
                   12925:                 }
1.1172.2.34  raeburn  12926:                 $chksum{$file} = $shasum;
                   12927:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  12928:             }
                   12929:             if (ref($hashref) eq 'HASH') {
                   12930:                 %{$hashref} = (
                   12931:                                 sums     => \%chksum,
                   12932:                                 versions => \%revnum,
                   12933:                               );
                   12934:             }
                   12935:         }
                   12936:     }
1.869     albertel 12937:     return;
1.852     albertel 12938: }
1.1172.2.17  raeburn  12939: 
                   12940: sub fetch_dns_checksums {
                   12941:     my %checksums;
1.1172.2.34  raeburn  12942:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  12943:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  12944:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12945:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  12946:              \%checksums);
                   12947:     return \%checksums;
                   12948: }
                   12949: 
1.327     albertel 12950: # ------------------------------------------------------------ Read domain file
                   12951: {
1.852     albertel 12952:     my $loaded;
1.846     albertel 12953:     my %domain;
                   12954: 
1.852     albertel 12955:     sub parse_domain_tab {
                   12956: 	my ($lines) = @_;
                   12957: 	foreach my $line (@$lines) {
                   12958: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      12959: 
1.846     albertel 12960: 	    chomp($line);
1.852     albertel 12961: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 12962: 	    my %this_domain;
                   12963: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   12964: 			       'lang_def', 'city', 'longi', 'lati',
                   12965: 			       'primary') {
                   12966: 		$this_domain{$field} = shift(@elements);
                   12967: 	    }
                   12968: 	    $domain{$name} = \%this_domain;
1.852     albertel 12969: 	}
                   12970:     }
1.864     albertel 12971: 
                   12972:     sub reset_domain_info {
                   12973: 	undef($loaded);
                   12974: 	undef(%domain);
                   12975:     }
                   12976: 
1.852     albertel 12977:     sub load_domain_tab {
1.1172.2.70  raeburn  12978: 	my ($ignore_cache,$nocache) = @_;
                   12979: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 12980: 	my $fh;
1.1172.2.96  raeburn  12981: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 12982: 	    my @lines = <$fh>;
                   12983: 	    &parse_domain_tab(\@lines);
1.448     albertel 12984: 	}
1.852     albertel 12985: 	close($fh);
                   12986: 	$loaded = 1;
1.327     albertel 12987:     }
1.846     albertel 12988: 
                   12989:     sub domain {
1.852     albertel 12990: 	&load_domain_tab() if (!$loaded);
                   12991: 
1.846     albertel 12992: 	my ($name,$what) = @_;
                   12993: 	return if ( !exists($domain{$name}) );
                   12994: 
                   12995: 	if (!$what) {
                   12996: 	    return $domain{$name}{'description'};
                   12997: 	}
                   12998: 	return $domain{$name}{$what};
                   12999:     }
1.974     raeburn  13000: 
                   13001:     sub domain_info {
                   13002:         &load_domain_tab() if (!$loaded);
                   13003:         return %domain;
                   13004:     }
                   13005: 
1.327     albertel 13006: }
                   13007: 
                   13008: 
1.1       albertel 13009: # ------------------------------------------------------------- Read hosts file
                   13010: {
1.838     albertel 13011:     my %hostname;
1.844     albertel 13012:     my %hostdom;
1.845     albertel 13013:     my %libserv;
1.852     albertel 13014:     my $loaded;
1.888     albertel 13015:     my %name_to_host;
1.1074    raeburn  13016:     my %internetdom;
1.1107    raeburn  13017:     my %LC_dns_serv;
1.852     albertel 13018: 
                   13019:     sub parse_hosts_tab {
                   13020: 	my ($file) = @_;
                   13021: 	foreach my $configline (@$file) {
                   13022: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13023:             chomp($configline);
                   13024: 	    if ($configline =~ /^\^/) {
                   13025:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13026:                     $LC_dns_serv{$1} = 1;
                   13027:                 }
                   13028:                 next;
                   13029:             }
1.1074    raeburn  13030: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13031: 	    $name=~s/\s//g;
                   13032: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  13033:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   13034:                     my $curr = $hostname{$id};
                   13035:                     my $skip;
                   13036:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   13037:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   13038:                             $skip = 1;
                   13039:                         } else {
                   13040:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   13041:                         }
                   13042:                     }
                   13043:                     unless ($skip) {
                   13044:                         push(@{$name_to_host{$name}},$id);
                   13045:                     }
                   13046:                 } else {
                   13047:                     push(@{$name_to_host{$name}},$id);
                   13048:                 }
1.852     albertel 13049: 		$hostname{$id}=$name;
                   13050: 		$hostdom{$id}=$domain;
                   13051: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13052:                 if (defined($protocol)) {
                   13053:                     if ($protocol eq 'https') {
                   13054:                         $protocol{$id} = $protocol;
                   13055:                     } else {
                   13056:                         $protocol{$id} = 'http'; 
                   13057:                     }
1.968     raeburn  13058:                 } else {
1.969     raeburn  13059:                     $protocol{$id} = 'http';
1.968     raeburn  13060:                 }
1.1074    raeburn  13061:                 if (defined($intdom)) {
                   13062:                     $internetdom{$id} = $intdom;
                   13063:                 }
1.852     albertel 13064: 	    }
                   13065: 	}
                   13066:     }
1.864     albertel 13067:     
                   13068:     sub reset_hosts_info {
1.897     albertel 13069: 	&purge_remembered();
1.864     albertel 13070: 	&reset_domain_info();
                   13071: 	&reset_hosts_ip_info();
1.892     albertel 13072: 	undef(%name_to_host);
1.864     albertel 13073: 	undef(%hostname);
                   13074: 	undef(%hostdom);
                   13075: 	undef(%libserv);
                   13076: 	undef($loaded);
                   13077:     }
1.1       albertel 13078: 
1.852     albertel 13079:     sub load_hosts_tab {
1.1172.2.70  raeburn  13080: 	my ($ignore_cache,$nocache) = @_;
                   13081: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  13082: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13083: 	my @config = <$config>;
                   13084: 	&parse_hosts_tab(\@config);
                   13085: 	close($config);
                   13086: 	$loaded=1;
1.1       albertel 13087:     }
1.852     albertel 13088: 
1.838     albertel 13089:     sub hostname {
1.852     albertel 13090: 	&load_hosts_tab() if (!$loaded);
                   13091: 
1.838     albertel 13092: 	my ($lonid) = @_;
                   13093: 	return $hostname{$lonid};
                   13094:     }
1.845     albertel 13095: 
1.838     albertel 13096:     sub all_hostnames {
1.852     albertel 13097: 	&load_hosts_tab() if (!$loaded);
                   13098: 
1.838     albertel 13099: 	return %hostname;
                   13100:     }
1.845     albertel 13101: 
1.888     albertel 13102:     sub all_names {
1.1172.2.70  raeburn  13103:         my ($ignore_cache,$nocache) = @_;
                   13104: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13105: 
                   13106: 	return %name_to_host;
                   13107:     }
                   13108: 
1.974     raeburn  13109:     sub all_host_domain {
                   13110:         &load_hosts_tab() if (!$loaded);
                   13111:         return %hostdom;
                   13112:     }
                   13113: 
1.845     albertel 13114:     sub is_library {
1.852     albertel 13115: 	&load_hosts_tab() if (!$loaded);
                   13116: 
1.845     albertel 13117: 	return exists($libserv{$_[0]});
                   13118:     }
                   13119: 
                   13120:     sub all_library {
1.852     albertel 13121: 	&load_hosts_tab() if (!$loaded);
                   13122: 
1.845     albertel 13123: 	return %libserv;
                   13124:     }
                   13125: 
1.1062    droeschl 13126:     sub unique_library {
                   13127: 	#2x reverse removes all hostnames that appear more than once
                   13128:         my %unique = reverse &all_library();
                   13129:         return reverse %unique;
                   13130:     }
                   13131: 
1.841     albertel 13132:     sub get_servers {
1.852     albertel 13133: 	&load_hosts_tab() if (!$loaded);
                   13134: 
1.841     albertel 13135: 	my ($domain,$type) = @_;
                   13136: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13137: 	                                          : %hostname;
                   13138: 	my %result;
1.842     albertel 13139: 	if (ref($domain) eq 'ARRAY') {
                   13140: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13141: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13142: 		    $result{$host} = $hostname;
                   13143: 		}
                   13144: 	    }
                   13145: 	} else {
                   13146: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13147: 		if ($hostdom{$host} eq $domain) {
                   13148: 		    $result{$host} = $hostname;
                   13149: 		}
1.841     albertel 13150: 	    }
                   13151: 	}
                   13152: 	return %result;
                   13153:     }
1.845     albertel 13154: 
1.1062    droeschl 13155:     sub get_unique_servers {
                   13156:         my %unique = reverse &get_servers(@_);
                   13157: 	return reverse %unique;
                   13158:     }
                   13159: 
1.844     albertel 13160:     sub host_domain {
1.852     albertel 13161: 	&load_hosts_tab() if (!$loaded);
                   13162: 
1.844     albertel 13163: 	my ($lonid) = @_;
                   13164: 	return $hostdom{$lonid};
                   13165:     }
                   13166: 
1.841     albertel 13167:     sub all_domains {
1.852     albertel 13168: 	&load_hosts_tab() if (!$loaded);
                   13169: 
1.841     albertel 13170: 	my %seen;
                   13171: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13172: 	return @uniq;
                   13173:     }
1.1074    raeburn  13174: 
                   13175:     sub internet_dom {
                   13176:         &load_hosts_tab() if (!$loaded);
                   13177: 
                   13178:         my ($lonid) = @_;
                   13179:         return $internetdom{$lonid};
                   13180:     }
1.1107    raeburn  13181: 
                   13182:     sub is_LC_dns {
                   13183:         &load_hosts_tab() if (!$loaded);
                   13184: 
                   13185:         my ($hostname) = @_;
                   13186:         return exists($LC_dns_serv{$hostname});
                   13187:     }
                   13188: 
1.1       albertel 13189: }
                   13190: 
1.847     albertel 13191: { 
                   13192:     my %iphost;
1.856     albertel 13193:     my %name_to_ip;
                   13194:     my %lonid_to_ip;
1.869     albertel 13195: 
1.847     albertel 13196:     sub get_hosts_from_ip {
                   13197: 	my ($ip) = @_;
                   13198: 	my %iphosts = &get_iphost();
                   13199: 	if (ref($iphosts{$ip})) {
                   13200: 	    return @{$iphosts{$ip}};
                   13201: 	}
                   13202: 	return;
1.839     albertel 13203:     }
1.864     albertel 13204:     
                   13205:     sub reset_hosts_ip_info {
                   13206: 	undef(%iphost);
                   13207: 	undef(%name_to_ip);
                   13208: 	undef(%lonid_to_ip);
                   13209:     }
1.856     albertel 13210: 
                   13211:     sub get_host_ip {
                   13212: 	my ($lonid) = @_;
                   13213: 	if (exists($lonid_to_ip{$lonid})) {
                   13214: 	    return $lonid_to_ip{$lonid};
                   13215: 	}
                   13216: 	my $name=&hostname($lonid);
                   13217:    	my $ip = gethostbyname($name);
                   13218: 	return if (!$ip || length($ip) ne 4);
                   13219: 	$ip=inet_ntoa($ip);
                   13220: 	$name_to_ip{$name}   = $ip;
                   13221: 	$lonid_to_ip{$lonid} = $ip;
                   13222: 	return $ip;
                   13223:     }
1.847     albertel 13224:     
                   13225:     sub get_iphost {
1.1172.2.70  raeburn  13226: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13227: 
1.869     albertel 13228: 	if (!$ignore_cache) {
                   13229: 	    if (%iphost) {
                   13230: 		return %iphost;
                   13231: 	    }
                   13232: 	    my ($ip_info,$cached)=
                   13233: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13234: 	    if ($cached) {
                   13235: 		%iphost      = %{$ip_info->[0]};
                   13236: 		%name_to_ip  = %{$ip_info->[1]};
                   13237: 		%lonid_to_ip = %{$ip_info->[2]};
                   13238: 		return %iphost;
                   13239: 	    }
                   13240: 	}
1.894     albertel 13241: 
                   13242: 	# get yesterday's info for fallback
                   13243: 	my %old_name_to_ip;
                   13244: 	my ($ip_info,$cached)=
                   13245: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13246: 	if ($cached) {
                   13247: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13248: 	}
                   13249: 
1.1172.2.70  raeburn  13250: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13251: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13252: 	    my $ip;
                   13253: 	    if (!exists($name_to_ip{$name})) {
                   13254: 		$ip = gethostbyname($name);
                   13255: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13256: 		    if (defined($old_name_to_ip{$name})) {
                   13257: 			$ip = $old_name_to_ip{$name};
                   13258: 			&logthis("Can't find $name defaulting to old $ip");
                   13259: 		    } else {
                   13260: 			&logthis("Name $name no IP found");
                   13261: 			next;
                   13262: 		    }
                   13263: 		} else {
                   13264: 		    $ip=inet_ntoa($ip);
1.847     albertel 13265: 		}
                   13266: 		$name_to_ip{$name} = $ip;
                   13267: 	    } else {
                   13268: 		$ip = $name_to_ip{$name};
1.653     albertel 13269: 	    }
1.888     albertel 13270: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13271: 		$lonid_to_ip{$id} = $ip;
                   13272: 	    }
                   13273: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13274: 	}
1.1172.2.70  raeburn  13275:         unless ($nocache) {
                   13276: 	    &do_cache_new('iphost','iphost',
                   13277: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   13278: 		          48*60*60);
                   13279:         }
1.869     albertel 13280: 
1.847     albertel 13281: 	return %iphost;
1.598     albertel 13282:     }
                   13283: 
1.992     raeburn  13284:     #
                   13285:     #  Given a DNS returns the loncapa host name for that DNS 
                   13286:     # 
                   13287:     sub host_from_dns {
                   13288:         my ($dns) = @_;
                   13289:         my @hosts;
                   13290:         my $ip;
                   13291: 
1.993     raeburn  13292:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  13293:             $ip = $name_to_ip{$dns};
                   13294:         }
                   13295:         if (!$ip) {
                   13296:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   13297:             if (length($ip) == 4) { 
                   13298: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   13299:             }
                   13300:         }
                   13301:         if ($ip) {
                   13302: 	    @hosts = get_hosts_from_ip($ip);
                   13303: 	    return $hosts[0];
                   13304:         }
                   13305:         return undef;
1.986     foxr     13306:     }
1.992     raeburn  13307: 
1.1074    raeburn  13308:     sub get_internet_names {
                   13309:         my ($lonid) = @_;
                   13310:         return if ($lonid eq '');
                   13311:         my ($idnref,$cached)=
                   13312:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   13313:         if ($cached) {
                   13314:             return $idnref;
                   13315:         }
                   13316:         my $ip = &get_host_ip($lonid);
                   13317:         my @hosts = &get_hosts_from_ip($ip);
                   13318:         my %iphost = &get_iphost();
                   13319:         my (@idns,%seen);
                   13320:         foreach my $id (@hosts) {
                   13321:             my $dom = &host_domain($id);
                   13322:             my $prim_id = &domain($dom,'primary');
                   13323:             my $prim_ip = &get_host_ip($prim_id);
                   13324:             next if ($seen{$prim_ip});
                   13325:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   13326:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   13327:                     my $intdom = &internet_dom($id);
                   13328:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   13329:                         push(@idns,$intdom);
                   13330:                     }
                   13331:                 }
                   13332:             }
                   13333:             $seen{$prim_ip} = 1;
                   13334:         }
1.1172.2.23  raeburn  13335:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  13336:     }
                   13337: 
1.986     foxr     13338: }
                   13339: 
1.1079    raeburn  13340: sub all_loncaparevs {
1.1172.2.39  raeburn  13341:     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  13342: }
                   13343: 
1.1172.2.27  raeburn  13344: # ------------------------------------------------------- Read loncaparev table
                   13345: {
                   13346:     sub load_loncaparevs {
                   13347:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  13348:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  13349:                 while (my $configline=<$config>) {
                   13350:                     chomp($configline);
                   13351:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   13352:                     $loncaparevs{$hostid}=$loncaparev;
                   13353:                 }
                   13354:                 close($config);
                   13355:             }
                   13356:         }
                   13357:     }
                   13358: }
                   13359: 
                   13360: # ----------------------------------------------------- Read serverhostID table
                   13361: {
                   13362:     sub load_serverhomeIDs {
                   13363:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  13364:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  13365:                 while (my $configline=<$config>) {
                   13366:                     chomp($configline);
                   13367:                     my ($name,$id)=split(/:/,$configline);
                   13368:                     $serverhomeIDs{$name}=$id;
                   13369:                 }
                   13370:                 close($config);
                   13371:             }
                   13372:         }
                   13373:     }
                   13374: }
                   13375: 
                   13376: 
1.862     albertel 13377: BEGIN {
                   13378: 
                   13379: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   13380:     unless ($readit) {
                   13381: {
                   13382:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   13383:     %perlvar = (%perlvar,%{$configvars});
                   13384: }
                   13385: 
                   13386: 
1.1       albertel 13387: # ------------------------------------------------------ Read spare server file
                   13388: {
1.1172.2.96  raeburn  13389:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 13390: 
                   13391:     while (my $configline=<$config>) {
                   13392:        chomp($configline);
1.284     matthew  13393:        if ($configline) {
1.784     albertel 13394: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 13395: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 13396: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 13397:        }
                   13398:     }
1.448     albertel 13399:     close($config);
1.1       albertel 13400: }
1.11      www      13401: # ------------------------------------------------------------ Read permissions
                   13402: {
1.1172.2.96  raeburn  13403:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      13404: 
                   13405:     while (my $configline=<$config>) {
1.448     albertel 13406: 	chomp($configline);
                   13407: 	if ($configline) {
                   13408: 	    my ($role,$perm)=split(/ /,$configline);
                   13409: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   13410: 	}
1.11      www      13411:     }
1.448     albertel 13412:     close($config);
1.11      www      13413: }
                   13414: 
                   13415: # -------------------------------------------- Read plain texts for permissions
                   13416: {
1.1172.2.96  raeburn  13417:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      13418: 
                   13419:     while (my $configline=<$config>) {
1.448     albertel 13420: 	chomp($configline);
                   13421: 	if ($configline) {
1.742     raeburn  13422: 	    my ($short,@plain)=split(/:/,$configline);
                   13423:             %{$prp{$short}} = ();
                   13424: 	    if (@plain > 0) {
                   13425:                 $prp{$short}{'std'} = $plain[0];
                   13426:                 for (my $i=1; $i<@plain; $i++) {
                   13427:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   13428:                 }
                   13429:             }
1.448     albertel 13430: 	}
1.135     www      13431:     }
1.448     albertel 13432:     close($config);
1.135     www      13433: }
                   13434: 
                   13435: # ---------------------------------------------------------- Read package table
                   13436: {
1.1172.2.96  raeburn  13437:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      13438: 
                   13439:     while (my $configline=<$config>) {
1.483     albertel 13440: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 13441: 	chomp($configline);
                   13442: 	my ($short,$plain)=split(/:/,$configline);
                   13443: 	my ($pack,$name)=split(/\&/,$short);
                   13444: 	if ($plain ne '') {
                   13445: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   13446: 	    $packagetab{$short}=$plain; 
                   13447: 	}
1.11      www      13448:     }
1.448     albertel 13449:     close($config);
1.329     matthew  13450: }
                   13451: 
1.1172.2.27  raeburn  13452: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  13453: 
1.1172.2.27  raeburn  13454: &load_loncaparevs();
                   13455: 
                   13456: # ------------------------------------------------------- Read serverhostID table
                   13457: 
                   13458: &load_serverhomeIDs();
1.1074    raeburn  13459: 
1.1172.2.27  raeburn  13460: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  13461: {
                   13462:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   13463:     if (-e $file) {
                   13464:         my $parser = HTML::LCParser->new($file);
                   13465:         while (my $token = $parser->get_token()) {
                   13466:             if ($token->[0] eq 'S') {
                   13467:                 my $item = $token->[1];
                   13468:                 my $name = $token->[2]{'name'};
                   13469:                 my $value = $token->[2]{'value'};
                   13470:                 if ($item ne '' && $name ne '' && $value ne '') {
                   13471:                     my $release = $parser->get_text();
                   13472:                     $release =~ s/(^\s*|\s*$ )//gx;
                   13473:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   13474:                 }
                   13475:             }
                   13476:         }
                   13477:     }
1.1073    raeburn  13478: }
                   13479: 
1.1138    raeburn  13480: # ---------------------------------------------------------- Read managers table
                   13481: {
                   13482:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  13483:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  13484:             while (my $configline=<$config>) {
                   13485:                 chomp($configline);
                   13486:                 next if ($configline =~ /^\#/);
                   13487:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   13488:                     $managerstab{$configline} = 1;
                   13489:                 }
                   13490:             }
                   13491:             close($config);
                   13492:         }
                   13493:     }
                   13494: }
                   13495: 
1.329     matthew  13496: # ------------- set up temporary directory
                   13497: {
1.1117    foxr     13498:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  13499: 
1.11      www      13500: }
                   13501: 
1.1172.2.104  raeburn  13502: # ------------- set default texengine (domain default overrides this)
                   13503: {
                   13504:     $deftex = LONCAPA::texengine();
                   13505: }
                   13506: 
1.794     albertel 13507: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   13508: 				'compress_threshold'=> 20_000,
                   13509:  			        });
1.185     www      13510: 
1.281     www      13511: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      13512: $dumpcount=0;
1.958     www      13513: $locknum=0;
1.22      www      13514: 
1.163     harris41 13515: &logtouch();
1.672     albertel 13516: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      13517: $readit=1;
1.564     albertel 13518:     {
                   13519: 	use integer;
                   13520: 	my $test=(2**32)+1;
1.568     albertel 13521: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 13522: 	&logthis(" Detected 64bit platform ($_64bit)");
                   13523:     }
1.195     www      13524: }
1.1       albertel 13525: }
1.179     www      13526: 
1.1       albertel 13527: 1;
1.191     harris41 13528: __END__
                   13529: 
1.243     albertel 13530: =pod
                   13531: 
1.191     harris41 13532: =head1 NAME
                   13533: 
1.243     albertel 13534: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 13535: 
                   13536: =head1 SYNOPSIS
                   13537: 
1.243     albertel 13538: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 13539: 
                   13540:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   13541: 
1.243     albertel 13542: Common parameters:
                   13543: 
                   13544: =over 4
                   13545: 
                   13546: =item *
                   13547: 
                   13548: $uname : an internal username (if $cname expecting a course Id specifically)
                   13549: 
                   13550: =item *
                   13551: 
                   13552: $udom : a domain (if $cdom expecting a course's domain specifically)
                   13553: 
                   13554: =item *
                   13555: 
                   13556: $symb : a resource instance identifier
                   13557: 
                   13558: =item *
                   13559: 
                   13560: $namespace : the name of a .db file that contains the data needed or
                   13561: being set.
                   13562: 
                   13563: =back
                   13564: 
1.394     bowersj2 13565: =head1 OVERVIEW
1.191     harris41 13566: 
1.394     bowersj2 13567: lonnet provides subroutines which interact with the
                   13568: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   13569: about classes, users, and resources.
1.243     albertel 13570: 
                   13571: For many of these objects you can also use this to store data about
                   13572: them or modify them in various ways.
1.191     harris41 13573: 
1.394     bowersj2 13574: =head2 Symbs
1.191     harris41 13575: 
1.394     bowersj2 13576: To identify a specific instance of a resource, LON-CAPA uses symbols
                   13577: or "symbs"X<symb>. These identifiers are built from the URL of the
                   13578: map, the resource number of the resource in the map, and the URL of
                   13579: the resource itself. The latter is somewhat redundant, but might help
                   13580: if maps change.
                   13581: 
                   13582: An example is
                   13583: 
                   13584:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   13585: 
                   13586: The respective map entry is
                   13587: 
                   13588:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   13589:   title="Problem 2">
                   13590:  </resource>
                   13591: 
                   13592: Symbs are used by the random number generator, as well as to store and
                   13593: restore data specific to a certain instance of for example a problem.
                   13594: 
                   13595: =head2 Storing And Retrieving Data
                   13596: 
                   13597: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   13598: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   13599: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   13600: is is the non-critical message twin of cstore. These functions are for
                   13601: handlers to store a perl hash to a user's permanent data space in an
                   13602: easy manner, and to retrieve it again on another call. It is expected
                   13603: that a handler would use this once at the beginning to retrieve data,
                   13604: and then again once at the end to send only the new data back.
                   13605: 
                   13606: The data is stored in the user's data directory on the user's
                   13607: homeserver under the ID of the course.
                   13608: 
                   13609: The hash that is returned by restore will have all of the previous
                   13610: value for all of the elements of the hash.
                   13611: 
                   13612: Example:
                   13613: 
                   13614:  #creating a hash
                   13615:  my %hash;
                   13616:  $hash{'foo'}='bar';
                   13617: 
                   13618:  #storing it
                   13619:  &Apache::lonnet::cstore(\%hash);
                   13620: 
                   13621:  #changing a value
                   13622:  $hash{'foo'}='notbar';
                   13623: 
                   13624:  #adding a new value
                   13625:  $hash{'bar'}='foo';
                   13626:  &Apache::lonnet::cstore(\%hash);
                   13627: 
                   13628:  #retrieving the hash
                   13629:  my %history=&Apache::lonnet::restore();
                   13630: 
                   13631:  #print the hash
                   13632:  foreach my $key (sort(keys(%history))) {
                   13633:    print("\%history{$key} = $history{$key}");
                   13634:  }
                   13635: 
                   13636: Will print out:
1.191     harris41 13637: 
1.394     bowersj2 13638:  %history{1:foo} = bar
                   13639:  %history{1:keys} = foo:timestamp
                   13640:  %history{1:timestamp} = 990455579
                   13641:  %history{2:bar} = foo
                   13642:  %history{2:foo} = notbar
                   13643:  %history{2:keys} = foo:bar:timestamp
                   13644:  %history{2:timestamp} = 990455580
                   13645:  %history{bar} = foo
                   13646:  %history{foo} = notbar
                   13647:  %history{timestamp} = 990455580
                   13648:  %history{version} = 2
                   13649: 
                   13650: Note that the special hash entries C<keys>, C<version> and
                   13651: C<timestamp> were added to the hash. C<version> will be equal to the
                   13652: total number of versions of the data that have been stored. The
                   13653: C<timestamp> attribute will be the UNIX time the hash was
                   13654: stored. C<keys> is available in every historical section to list which
                   13655: keys were added or changed at a specific historical revision of a
                   13656: hash.
                   13657: 
                   13658: B<Warning>: do not store the hash that restore returns directly. This
                   13659: will cause a mess since it will restore the historical keys as if the
                   13660: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 13661: 
1.394     bowersj2 13662: Calling convention:
1.191     harris41 13663: 
1.1172.2.27  raeburn  13664:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  13665:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 13666: 
1.394     bowersj2 13667: For more detailed information, see lonnet specific documentation.
1.191     harris41 13668: 
1.394     bowersj2 13669: =head1 RETURN MESSAGES
1.191     harris41 13670: 
1.394     bowersj2 13671: =over 4
1.191     harris41 13672: 
1.394     bowersj2 13673: =item * B<con_lost>: unable to contact remote host
1.191     harris41 13674: 
1.394     bowersj2 13675: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   13676: when the connection is brought back up
1.191     harris41 13677: 
1.394     bowersj2 13678: =item * B<con_failed>: unable to contact remote host and unable to save message
                   13679: for later delivery
1.191     harris41 13680: 
1.967     bisitz   13681: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 13682: 
1.394     bowersj2 13683: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 13684: that was requested
1.191     harris41 13685: 
1.243     albertel 13686: =back
1.191     harris41 13687: 
1.243     albertel 13688: =head1 PUBLIC SUBROUTINES
1.191     harris41 13689: 
1.243     albertel 13690: =head2 Session Environment Functions
1.191     harris41 13691: 
1.243     albertel 13692: =over 4
1.191     harris41 13693: 
1.394     bowersj2 13694: =item * 
                   13695: X<appenv()>
1.949     raeburn  13696: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 13697: the user envirnoment file, and will be restored for each access this
1.620     albertel 13698: user makes during this session, also modifies the %env for the current
1.949     raeburn  13699: process. Optional rolesarrayref - if defined contains a reference to an array
                   13700: of roles which are exempt from the restriction on modifying user.role entries 
                   13701: in the user's environment.db and in %env.    
1.191     harris41 13702: 
                   13703: =item *
1.394     bowersj2 13704: X<delenv()>
1.987     raeburn  13705: B<delenv($delthis,$regexp)>: removes all items from the session
                   13706: environment file that begin with $delthis. If the 
                   13707: optional second arg - $regexp - is true, $delthis is treated as a 
                   13708: regular expression, otherwise \Q$delthis\E is used. 
                   13709: The values are also deleted from the current processes %env.
1.191     harris41 13710: 
1.795     albertel 13711: =item * get_env_multiple($name) 
                   13712: 
                   13713: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   13714: values may be defined and end up as an array ref.
                   13715: 
                   13716: returns an array of values
                   13717: 
1.243     albertel 13718: =back
                   13719: 
                   13720: =head2 User Information
1.191     harris41 13721: 
1.243     albertel 13722: =over 4
1.191     harris41 13723: 
                   13724: =item *
1.394     bowersj2 13725: X<queryauthenticate()>
                   13726: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 13727: authentication scheme
                   13728: 
                   13729: =item *
1.394     bowersj2 13730: X<authenticate()>
1.1073    raeburn  13731: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 13732: authenticate user from domain's lib servers (first use the current
                   13733: one). C<$upass> should be the users password.
1.1073    raeburn  13734: $checkdefauth is optional (value is 1 if a check should be made to
                   13735:    authenticate user using default authentication method, and allow
                   13736:    account creation if username does not have account in the domain).
                   13737: $clientcancheckhost is optional (value is 1 if checking whether the
                   13738:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 13739: 
                   13740: =item *
1.394     bowersj2 13741: X<homeserver()>
                   13742: B<homeserver($uname,$udom)>: find the server which has
                   13743: the user's directory and files (there must be only one), this caches
                   13744: the answer, and also caches if there is a borken connection.
1.191     harris41 13745: 
                   13746: =item *
1.394     bowersj2 13747: X<idget()>
                   13748: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   13749: (IDs are a unique resource in a domain, there must be only 1 ID per
                   13750: username, and only 1 username per ID in a specific domain) (returns
                   13751: hash: id=>name,id=>name)
1.191     harris41 13752: 
                   13753: =item *
1.394     bowersj2 13754: X<idrget()>
                   13755: B<idrget($udom,@unames)>: find the IDs behind a list of
                   13756: usernames (returns hash: name=>id,name=>id)
1.191     harris41 13757: 
                   13758: =item *
1.394     bowersj2 13759: X<idput()>
                   13760: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 13761: 
                   13762: =item *
1.394     bowersj2 13763: X<rolesinit()>
1.1169    droeschl 13764: B<rolesinit($udom,$username)>: get user privileges.
                   13765: returns user role, first access and timer interval hashes
1.243     albertel 13766: 
                   13767: =item *
1.1171    droeschl 13768: X<privileged()>
                   13769: B<privileged($username,$domain)>: returns a true if user has a
                   13770: privileged and active role (i.e. su or dc), false otherwise.
                   13771: 
                   13772: =item *
1.551     albertel 13773: X<getsection()>
                   13774: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 13775: course $cname, return section name/number or '' for "not in course"
                   13776: and '-1' for "no section"
                   13777: 
                   13778: =item *
1.394     bowersj2 13779: X<userenvironment()>
                   13780: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 13781: passed in @what from the requested user's environment, returns a hash
                   13782: 
1.858     raeburn  13783: =item * 
                   13784: X<userlog_query()>
1.859     albertel 13785: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   13786: activity.log file. %filters defines filters applied when parsing the
                   13787: log file. These can be start or end timestamps, or the type of action
                   13788: - log to look for Login or Logout events, check for Checkin or
                   13789: Checkout, role for role selection. The response is in the form
                   13790: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   13791: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  13792: 
1.243     albertel 13793: =back
                   13794: 
                   13795: =head2 User Roles
                   13796: 
                   13797: =over 4
                   13798: 
                   13799: =item *
                   13800: 
1.1172.2.65  raeburn  13801: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   13802: returns codes for allowed actions.
                   13803: 
                   13804: The first argument is required, all others are optional.
                   13805: 
                   13806: $priv is the privilege being checked.
                   13807: $uri contains additional information about what is being checked for access (e.g.,
                   13808: URL, course ID etc.).
                   13809: $symb is the unique resource instance identifier in a course; if needed,
                   13810: but not provided, it will be retrieved via a call to &symbread().
                   13811: $role is the role for which a priv is being checked (only used if priv is evb).
                   13812: $clientip is the user's IP address (only used when checking for access to portfolio
                   13813: files).
                   13814: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   13815: prevents recursive calls to &allowed.
                   13816: 
1.243     albertel 13817:  F: full access
                   13818:  U,I,K: authentication modes (cxx only)
                   13819:  '': forbidden
                   13820:  1: user needs to choose course
                   13821:  2: browse allowed
1.766     albertel 13822:  A: passphrase authentication needed
1.1172.2.65  raeburn  13823:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 13824: 
                   13825: =item *
                   13826: 
1.1172.2.13  raeburn  13827: constructaccess($url,$setpriv) : check for access to construction space URL
                   13828: 
                   13829: See if the owner domain and name in the URL match those in the
                   13830: expected environment.  If so, return three element list
                   13831: ($ownername,$ownerdomain,$ownerhome).
                   13832: 
                   13833: Otherwise return the null string.
                   13834: 
                   13835: If second argument 'setpriv' is true, it assigns the privileges,
                   13836: and returns the same three element list, unless the owner has
                   13837: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   13838: in which case the null string is returned.
                   13839: 
                   13840: =item *
                   13841: 
1.1172.2.84  raeburn  13842: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   13843: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   13844: for system, domain, and course level. $uname and $udom are optional (current
                   13845: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 13846: 
                   13847: =item *
                   13848: 
1.988     raeburn  13849: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   13850: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  13851: $type is Course (default) or Community.
1.988     raeburn  13852: If $forcedefault evaluates to true, text returned will be default 
                   13853: text for $type. Otherwise, if this is a course, the text returned 
                   13854: will be a custom name for the role (if defined in the course's 
                   13855: environment).  If no custom name is defined the default is returned.
                   13856:    
1.832     raeburn  13857: =item *
                   13858: 
1.1172.2.23  raeburn  13859: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  13860: All arguments are optional. Returns a hash of a roles, either for
                   13861: co-author/assistant author roles for a user's Construction Space
1.906     albertel 13862: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  13863: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   13864: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   13865: For each key, value is set to colon-separated start and end times for
                   13866: the role.  If no username and domain are specified, will default to
1.934     raeburn  13867: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  13868: of role statuses (active, future or previous), roles 
                   13869: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   13870: to restrict the list of roles reported. If no array ref is 
                   13871: provided for types, will default to return only active roles.
1.834     albertel 13872: 
1.1172.2.13  raeburn  13873: =item *
                   13874: 
                   13875: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   13876: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   13877: 
                   13878: Additional optional arguments are: $type (if role checking is to be restricted
                   13879: to certain user status types -- previous (expired roles), active (currently
                   13880: available roles) or future (roles available in the future), and
                   13881: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  13882: have active Domain Coordinator role in course's domain or in additional
                   13883: domains (specified in 'Domains to check for privileged users' in course
                   13884: environment -- set via:  Course Settings -> Classlists and staff listing).
                   13885: 
                   13886: =item *
                   13887: 
                   13888: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   13889: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   13890: $possdomains and $possroles are optional array refs -- to domains to check and
                   13891: roles to check.  If $possdomains is not specified, a dump will be done of the
                   13892: users' roles.db to check for a dc or su role in any domain. This can be
                   13893: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   13894: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   13895: this then allows &privileged_by_domain() to be used, which caches the identity
                   13896: of privileged users, eliminating the need for repeated calls to &dump().
                   13897: 
                   13898: =item *
                   13899: 
                   13900: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   13901: where the outer hash keys are domains specified in the $possdomains array ref,
                   13902: next inner hash keys are privileged roles specified in the $roles array ref,
                   13903: and the innermost hash contains key = value pairs for username:domain = end:start
                   13904: for active or future "privileged" users with that role in that domain. To avoid
                   13905: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   13906: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  13907: 
1.243     albertel 13908: =back
                   13909: 
                   13910: =head2 User Modification
                   13911: 
                   13912: =over 4
                   13913: 
                   13914: =item *
                   13915: 
1.957     raeburn  13916: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 13917: user for the level given by URL.  Optional start and end dates (leave empty
                   13918: string or zero for "no date")
1.191     harris41 13919: 
                   13920: =item *
                   13921: 
1.243     albertel 13922: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   13923: change a users, password, possible return values are: ok,
                   13924: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   13925: refused
1.191     harris41 13926: 
                   13927: =item *
                   13928: 
1.243     albertel 13929: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 13930: 
                   13931: =item *
                   13932: 
1.1058    raeburn  13933: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   13934:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   13935: 
                   13936: will update user information (firstname,middlename,lastname,generation,
                   13937: permanentemail), and if forceid is true, student/employee ID also.
                   13938: A user's institutional affiliation(s) can also be updated.
                   13939: User information fields will not be overwritten with empty entries 
                   13940: unless the field is included in the $candelete array reference.
                   13941: This array is included when a single user is modified via "Manage Users",
                   13942: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 13943: 
                   13944: =item *
                   13945: 
1.286     matthew  13946: modifystudent
                   13947: 
1.957     raeburn  13948: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  13949: The course id is resolved based on the current user's environment.  
                   13950: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  13951: associated with a course.
                   13952: 
1.297     matthew  13953: This call is essentially a wrapper for lonnet::modifyuser and
                   13954: lonnet::modify_student_enrollment
1.286     matthew  13955: 
                   13956: Inputs: 
                   13957: 
                   13958: =over 4
                   13959: 
1.957     raeburn  13960: =item B<$udom> Student's loncapa domain
1.286     matthew  13961: 
1.957     raeburn  13962: =item B<$uname> Student's loncapa login name
1.286     matthew  13963: 
1.964     bisitz   13964: =item B<$uid> Student/Employee ID
1.286     matthew  13965: 
1.957     raeburn  13966: =item B<$umode> Student's authentication mode
1.286     matthew  13967: 
1.957     raeburn  13968: =item B<$upass> Student's password
1.286     matthew  13969: 
1.957     raeburn  13970: =item B<$first> Student's first name
1.286     matthew  13971: 
1.957     raeburn  13972: =item B<$middle> Student's middle name
1.286     matthew  13973: 
1.957     raeburn  13974: =item B<$last> Student's last name
1.286     matthew  13975: 
1.957     raeburn  13976: =item B<$gene> Student's generation
1.286     matthew  13977: 
1.957     raeburn  13978: =item B<$usec> Student's section in course
1.286     matthew  13979: 
                   13980: =item B<$end> Unix time of the roles expiration
                   13981: 
                   13982: =item B<$start> Unix time of the roles start date
                   13983: 
                   13984: =item B<$forceid> If defined, allow $uid to be changed
                   13985: 
                   13986: =item B<$desiredhome> server to use as home server for student
                   13987: 
1.957     raeburn  13988: =item B<$email> Student's permanent e-mail address
                   13989: 
                   13990: =item B<$type> Type of enrollment (auto or manual)
                   13991: 
1.963     raeburn  13992: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   13993: 
                   13994: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  13995: 
1.963     raeburn  13996: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  13997: 
1.963     raeburn  13998: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  13999: 
1.1172.2.19  raeburn  14000: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14001: 
                   14002: =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  14003: 
1.286     matthew  14004: =back
1.297     matthew  14005: 
                   14006: =item *
                   14007: 
                   14008: modify_student_enrollment
                   14009: 
1.1172.2.31  raeburn  14010: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14011: 'role.request.course' must be defined for this function to proceed.
                   14012: 
                   14013: Inputs:
                   14014: 
                   14015: =over 4
                   14016: 
1.1172.2.31  raeburn  14017: =item $udom, student's domain
1.297     matthew  14018: 
1.1172.2.31  raeburn  14019: =item $uname, student's name
1.297     matthew  14020: 
1.1172.2.31  raeburn  14021: =item $uid, student's user id
1.297     matthew  14022: 
1.1172.2.31  raeburn  14023: =item $first, student's first name
1.297     matthew  14024: 
                   14025: =item $middle
                   14026: 
                   14027: =item $last
                   14028: 
                   14029: =item $gene
                   14030: 
                   14031: =item $usec
                   14032: 
                   14033: =item $end
                   14034: 
                   14035: =item $start
                   14036: 
1.957     raeburn  14037: =item $type
                   14038: 
                   14039: =item $locktype
                   14040: 
                   14041: =item $cid
                   14042: 
                   14043: =item $selfenroll
                   14044: 
                   14045: =item $context
                   14046: 
1.1172.2.19  raeburn  14047: =item $credits, number of credits student will earn from this class
                   14048: 
1.1172.2.76  raeburn  14049: =item $instsec, institutional course section code for student
                   14050: 
1.297     matthew  14051: =back
                   14052: 
1.191     harris41 14053: 
                   14054: =item *
                   14055: 
1.243     albertel 14056: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14057: custom role; give a custom role to a user for the level given by URL.  Specify
                   14058: name and domain of role author, and role name
1.191     harris41 14059: 
                   14060: =item *
                   14061: 
1.243     albertel 14062: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14063: 
                   14064: =item *
                   14065: 
1.243     albertel 14066: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14067: 
                   14068: =back
                   14069: 
                   14070: =head2 Course Infomation
                   14071: 
                   14072: =over 4
1.191     harris41 14073: 
                   14074: =item *
                   14075: 
1.1118    foxr     14076: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14077: specified course id, including all environment settings for the
                   14078: course, the description of the course will be in the hash under the
                   14079: key 'description'
1.191     harris41 14080: 
1.1118    foxr     14081: $options is an optional parameter that if supplied is a hash reference that controls
                   14082: what how this function works.  It has the following key/values:
                   14083: 
                   14084: =over 4
                   14085: 
                   14086: =item freshen_cache
                   14087: 
                   14088: If defined, and the environment cache for the course is valid, it is 
                   14089: returned in the returned hash.
                   14090: 
                   14091: =item one_time
                   14092: 
                   14093: If defined, the last cache time is set to _now_
                   14094: 
                   14095: =item user
                   14096: 
                   14097: If defined, the supplied username is used instead of the current user.
                   14098: 
                   14099: 
                   14100: =back
                   14101: 
1.191     harris41 14102: =item *
                   14103: 
1.624     albertel 14104: resdata($name,$domain,$type,@which) : request for current parameter
                   14105: setting for a specific $type, where $type is either 'course' or 'user',
                   14106: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  14107: answers for 10 minutes.
1.243     albertel 14108: 
1.877     foxr     14109: =item *
                   14110: 
                   14111: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14112: data base, returning a hash that is keyed by the resource name and has
                   14113: values that are the resource value.  I believe that the timestamps and
                   14114: versions are also returned.
                   14115: 
1.1172.2.31  raeburn  14116: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14117: supplemental content area. This routine caches the number of files for
                   14118: 10 minutes.
                   14119: 
1.243     albertel 14120: =back
                   14121: 
                   14122: =head2 Course Modification
                   14123: 
                   14124: =over 4
1.191     harris41 14125: 
                   14126: =item *
                   14127: 
1.243     albertel 14128: writecoursepref($courseid,%prefs) : write preferences (environment
                   14129: database) for a course
1.191     harris41 14130: 
                   14131: =item *
                   14132: 
1.1011    raeburn  14133: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14134: 
                   14135: =item *
                   14136: 
1.1038    raeburn  14137: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14138: 
1.1167    droeschl 14139: =item *
                   14140: 
                   14141: is_course($courseid), is_course($cdom, $cnum)
                   14142: 
                   14143: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14144: two component version $cdom, $cnum. It checks if the specified course exists.
                   14145: 
                   14146: Returns:
                   14147:     undef if the course doesn't exist, otherwise
                   14148:     in scalar context the combined courseid.
                   14149:     in list context the two components of the course identifier, domain and 
                   14150:     courseid.    
                   14151: 
1.243     albertel 14152: =back
                   14153: 
                   14154: =head2 Resource Subroutines
                   14155: 
                   14156: =over 4
1.191     harris41 14157: 
                   14158: =item *
                   14159: 
1.243     albertel 14160: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 14161: 
                   14162: =item *
                   14163: 
1.243     albertel 14164: repcopy($filename) : subscribes to the requested file, and attempts to
                   14165: replicate from the owning library server, Might return
1.607     raeburn  14166: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   14167: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 14168: resource. Expects the local filesystem pathname
                   14169: (/home/httpd/html/res/....)
                   14170: 
                   14171: =back
                   14172: 
                   14173: =head2 Resource Information
                   14174: 
                   14175: =over 4
1.191     harris41 14176: 
                   14177: =item *
                   14178: 
1.1172.2.28  raeburn  14179: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   14180: and returns the value of a variety of different possible values,
                   14181: $varname should be a request string, and the other parameters can be
                   14182: used to specify who and what one is asking about. Ordinarily, $cid 
                   14183: does not need to be specified, as it is retrived from 
                   14184: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14185: within lonuserstate::loadmap() when initializing a course, before
                   14186: $env{'request.course.id'} has been set, so it needs to be provided
                   14187: in that one case.
1.243     albertel 14188: 
                   14189: Possible values for $varname are environment.lastname (or other item
                   14190: from the envirnment hash), user.name (or someother aspect about the
                   14191: user), resource.0.maxtries (or some other part and parameter of a
                   14192: resource)
1.204     albertel 14193: 
                   14194: =item *
                   14195: 
1.243     albertel 14196: directcondval($number) : get current value of a condition; reads from a state
                   14197: string
1.204     albertel 14198: 
                   14199: =item *
                   14200: 
1.243     albertel 14201: condval($condidx) : value of condition index based on state
1.204     albertel 14202: 
                   14203: =item *
                   14204: 
1.243     albertel 14205: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   14206: resource's metadata, $what should be either a specific key, or either
                   14207: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   14208: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   14209: 
                   14210: this function automatically caches all requests
1.191     harris41 14211: 
                   14212: =item *
                   14213: 
1.243     albertel 14214: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   14215: network of library servers; returns file handle of where SQL and regex results
                   14216: will be stored for query
1.191     harris41 14217: 
                   14218: =item *
                   14219: 
1.1172.2.66  raeburn  14220: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   14221: return symbolic list entry (all arguments optional).
                   14222: 
                   14223: Args: filename is the filename (including path) for the file for which a symb
                   14224: is required; donotrecurse, if true will prevent calls to allowed() being made
                   14225: to check access status if more than one resource was found in the bighash
                   14226: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   14227: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   14228: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   14229: cause possible symbs to be checked to determine if they are subject to content
                   14230: blocking, if so they will not be included as possible symbs; possibles is a
                   14231: ref to a hash, which, as a side effect, will be populated with all possible
                   14232: symbs (content blocking not tested).
                   14233: 
1.243     albertel 14234: returns the data handle
1.191     harris41 14235: 
                   14236: =item *
                   14237: 
1.1172.2.17  raeburn  14238: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  14239: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 14240: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  14241: on failure, user must be in a course, as it assumes the existence of
                   14242: the course initial hash, and uses $env('request.course.id'}.  The third
                   14243: arg is an optional reference to a scalar.  If this arg is passed in the
                   14244: call to symbverify, it will be set to 1 if the symb has been set to be 
                   14245: encrypted; otherwise it will be null.
1.243     albertel 14246: 
1.191     harris41 14247: =item *
                   14248: 
1.243     albertel 14249: symbclean($symb) : removes versions numbers from a symb, returns the
                   14250: cleaned symb
1.191     harris41 14251: 
                   14252: =item *
                   14253: 
1.243     albertel 14254: is_on_map($uri) : checks if the $uri is somewhere on the current
                   14255: course map, user must be in a course for it to work.
1.191     harris41 14256: 
                   14257: =item *
                   14258: 
1.243     albertel 14259: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 14260: 
                   14261: =item *
                   14262: 
1.243     albertel 14263: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   14264: a random seed, all arguments are optional, if they aren't sent it uses the
                   14265: environment to derive them. Note: if symb isn't sent and it can't get one
                   14266: from &symbread it will use the current time as its return value
1.191     harris41 14267: 
                   14268: =item *
                   14269: 
1.243     albertel 14270: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   14271: unfakeable, receipt
1.191     harris41 14272: 
                   14273: =item *
                   14274: 
1.620     albertel 14275: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 14276: 
                   14277: =item *
                   14278: 
1.243     albertel 14279: countacc($url) : count the number of accesses to a given URL
1.191     harris41 14280: 
                   14281: =item *
                   14282: 
1.243     albertel 14283: 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 14284: 
                   14285: =item *
                   14286: 
1.243     albertel 14287: 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 14288: 
                   14289: =item *
                   14290: 
1.243     albertel 14291: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 14292: 
                   14293: =item *
                   14294: 
1.243     albertel 14295: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   14296: forcing spreadsheet to reevaluate the resource scores next time.
                   14297: 
1.1172.2.13  raeburn  14298: =item *
                   14299: 
                   14300: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   14301: when viewing in course context.
                   14302: 
                   14303:  input: six args -- filename (decluttered), course number, course domain,
                   14304:                     url, symb (if registered) and group (if this is a
                   14305:                     group item -- e.g., bulletin board, group page etc.).
                   14306: 
                   14307:  output: array of five scalars --
                   14308:          $cfile -- url for file editing if editable on current server
                   14309:          $home -- homeserver of resource (i.e., for author if published,
                   14310:                                           or course if uploaded.).
                   14311:          $switchserver --  1 if server switch will be needed.
                   14312:          $forceedit -- 1 if icon/link should be to go to edit mode
                   14313:          $forceview -- 1 if icon/link should be to go to view mode
                   14314: 
                   14315: =item *
                   14316: 
                   14317: is_course_upload($file,$cnum,$cdom)
                   14318: 
                   14319: Used in course context to determine if current file was uploaded to
                   14320: the course (i.e., would be found in /userfiles/docs on the course's
                   14321: homeserver.
                   14322: 
                   14323:   input: 3 args -- filename (decluttered), course number and course domain.
                   14324:   output: boolean -- 1 if file was uploaded.
                   14325: 
1.243     albertel 14326: =back
                   14327: 
                   14328: =head2 Storing/Retreiving Data
                   14329: 
                   14330: =over 4
1.191     harris41 14331: 
                   14332: =item *
                   14333: 
1.1172.2.64  raeburn  14334: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   14335: permanently for this url; hashref needs to be given and should be a \%hashname;
                   14336: the remaining args aren't required and if they aren't passed or are '' they will
                   14337: be derived from the env (with the exception of $laststore, which is an
                   14338: optional arg used when a user's submission is stored in grading).
                   14339: $laststore is $version=$timestamp, where $version is the most recent version
                   14340: number retrieved for the corresponding $symb in the $namespace db file, and
                   14341: $timestamp is the timestamp for that transaction (UNIX time).
                   14342: $laststore is currently only passed when cstore() is called by
                   14343: structuretags::finalize_storage().
1.191     harris41 14344: 
                   14345: =item *
                   14346: 
1.1172.2.64  raeburn  14347: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   14348: but uses critical subroutine
1.191     harris41 14349: 
                   14350: =item *
                   14351: 
1.243     albertel 14352: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   14353: all args are optional
1.191     harris41 14354: 
                   14355: =item *
                   14356: 
1.717     albertel 14357: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   14358: dumps the complete (or key matching regexp) namespace into a hash
                   14359: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   14360: normally &store()ed into
                   14361: 
                   14362: $range should be either an integer '100' (give me the first 100
                   14363:                                            matching records)
                   14364:               or be  two integers sperated by a - with no spaces
                   14365:                  '30-50' (give me the 30th through the 50th matching
                   14366:                           records)
                   14367: 
                   14368: 
                   14369: =item *
                   14370: 
1.1172.2.59  raeburn  14371: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 14372: replaces a &store() version of data with a replacement set of data
                   14373: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  14374: reference. If $tolog is true, the transaction is logged in the courselog
                   14375: with an action=PUTSTORE.
1.717     albertel 14376: 
                   14377: =item *
                   14378: 
1.243     albertel 14379: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   14380: works very similar to store/cstore, but all data is stored in a
                   14381: temporary location and can be reset using tmpreset, $storehash should
                   14382: be a hash reference, returns nothing on success
1.191     harris41 14383: 
                   14384: =item *
                   14385: 
1.243     albertel 14386: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   14387: similar to restore, but all data is stored in a temporary location and
                   14388: can be reset using tmpreset. Returns a hash of values on success,
                   14389: error string otherwise.
1.191     harris41 14390: 
                   14391: =item *
                   14392: 
1.243     albertel 14393: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   14394: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 14395: 
                   14396: =item *
                   14397: 
1.243     albertel 14398: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14399: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 14400: 
                   14401: =item *
                   14402: 
1.243     albertel 14403: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   14404: namesp ($udom and $uname are optional)
1.191     harris41 14405: 
                   14406: =item *
                   14407: 
1.702     albertel 14408: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 14409: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 14410: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  14411: 
1.702     albertel 14412: $range should be either an integer '100' (give me the first 100
                   14413:                                            matching records)
                   14414:               or be  two integers sperated by a - with no spaces
                   14415:                  '30-50' (give me the 30th through the 50th matching
                   14416:                           records)
1.449     matthew  14417: =item *
                   14418: 
                   14419: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   14420: $store can be a scalar, an array reference, or if the amount to be 
                   14421: incremented is > 1, a hash reference.
                   14422: 
                   14423: ($udom and $uname are optional)
1.191     harris41 14424: 
                   14425: =item *
                   14426: 
1.243     albertel 14427: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   14428: ($udom and $uname are optional)
1.191     harris41 14429: 
                   14430: =item *
                   14431: 
1.243     albertel 14432: cput($namespace,$storehash,$udom,$uname) : critical put
                   14433: ($udom and $uname are optional)
1.191     harris41 14434: 
                   14435: =item *
                   14436: 
1.748     albertel 14437: newput($namespace,$storehash,$udom,$uname) :
                   14438: 
                   14439: Attempts to store the items in the $storehash, but only if they don't
                   14440: currently exist, if this succeeds you can be certain that you have 
                   14441: successfully created a new key value pair in the $namespace db.
                   14442: 
                   14443: 
                   14444: Args:
                   14445:  $namespace: name of database to store values to
                   14446:  $storehash: hashref to store to the db
                   14447:  $udom: (optional) domain of user containing the db
                   14448:  $uname: (optional) name of user caontaining the db
                   14449: 
                   14450: Returns:
                   14451:  'ok' -> succeeded in storing all keys of $storehash
                   14452:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   14453:                         least <key> already existed in the db (other
                   14454:                         requested keys may also already exist)
1.967     bisitz   14455:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 14456:  'con_lost' -> unable to contact request server
                   14457:  'refused' -> action was not allowed by remote machine
                   14458: 
                   14459: 
                   14460: =item *
                   14461: 
1.243     albertel 14462: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14463: reference filled in from namesp (encrypts the return communication)
                   14464: ($udom and $uname are optional)
1.191     harris41 14465: 
                   14466: =item *
                   14467: 
1.243     albertel 14468: log($udom,$name,$home,$message) : write to permanent log for user; use
                   14469: critical subroutine
                   14470: 
1.806     raeburn  14471: =item *
                   14472: 
1.860     raeburn  14473: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   14474: array reference filled in from namespace found in domain level on either
                   14475: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  14476: 
                   14477: =item *
                   14478: 
1.860     raeburn  14479: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   14480: domain level either on specified domain server ($uhome) or primary domain 
                   14481: server ($udom and $uhome are optional)
1.806     raeburn  14482: 
1.943     raeburn  14483: =item * 
                   14484: 
1.1172.2.35  raeburn  14485: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   14486: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   14487: the target domain.
                   14488: 
                   14489: May also include additional key => value pairs for the following groups:
                   14490: 
                   14491: =over
                   14492: 
                   14493: =item
                   14494: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   14495: 
                   14496: =over
                   14497: 
                   14498: =item defaultquota, authorquota
                   14499: 
                   14500: =back
                   14501: 
                   14502: =item
                   14503: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   14504: portfolio for users).
                   14505: 
                   14506: =over
                   14507: 
                   14508: =item
                   14509: aboutme, blog, webdav, portfolio
                   14510: 
                   14511: =back
                   14512: 
                   14513: =item
                   14514: requestcourses: ability to request courses, and how requests are processed.
                   14515: 
                   14516: =over
                   14517: 
                   14518: =item
1.1172.2.37  raeburn  14519: official, unofficial, community, textbook
1.1172.2.35  raeburn  14520: 
                   14521: =back
                   14522: 
                   14523: =item
                   14524: inststatus: types of institutional affiliation, and order in which they are displayed.
                   14525: 
                   14526: =over
                   14527: 
                   14528: =item
1.1172.2.44  raeburn  14529: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  14530: 
                   14531: =back
                   14532: 
                   14533: =item
                   14534: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   14535: for course's uploaded content.
                   14536: 
                   14537: =over
                   14538: 
                   14539: =item
1.1172.2.68  raeburn  14540: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   14541: communityquota, textbookquota
1.1172.2.35  raeburn  14542: 
                   14543: =back
                   14544: 
                   14545: =item
                   14546: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   14547: on your servers.
                   14548: 
                   14549: =over
                   14550: 
                   14551: =item
                   14552: remotesessions, hostedsessions
                   14553: 
                   14554: =back
                   14555: 
                   14556: =back
                   14557: 
                   14558: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   14559: utility to create a configuration.db file on a domain's primary library server
                   14560: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   14561: -- corresponding values are authentication type (internal, krb4, krb5,
                   14562: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   14563: will be available. Values are retrieved from cache (if current), unless the
                   14564: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   14565: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   14566: 
                   14567: Typical usage:
1.943     raeburn  14568: 
1.1172.2.35  raeburn  14569: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  14570: 
1.243     albertel 14571: =back
                   14572: 
                   14573: =head2 Network Status Functions
                   14574: 
                   14575: =over 4
1.191     harris41 14576: 
                   14577: =item *
                   14578: 
1.1137    raeburn  14579: dirlist() : return directory list based on URI (first arg).
                   14580: 
                   14581: Inputs: 1 required, 5 optional.
                   14582: 
                   14583: =over
                   14584: 
                   14585: =item 
                   14586: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   14587: 
                   14588: =item
                   14589: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   14590: 
                   14591: =item
                   14592: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   14593: 
                   14594: =item
                   14595: $getpropath - boolean: 1 if prepend path using &propath(). 
                   14596: 
                   14597: =item
                   14598: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   14599: 
                   14600: =item 
                   14601: $alternateRoot - path to prepend in place of path from $uri.
                   14602: 
                   14603: =back
                   14604: 
                   14605: Returns: Array of up to two items.
                   14606: 
                   14607: =over
                   14608: 
                   14609: a reference to an array of files/subdirectories
                   14610: 
                   14611: =over
                   14612: 
                   14613: Each element in the array of files/subdirectories is a & separated list of
                   14614: item name and the result of running stat on the item.  If dirlist was requested
                   14615: for a file instead of a directory, the item name will be ''. For a directory 
                   14616: listing, if the item is a metadata file, the element will end &N&M 
                   14617: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   14618: default copyright set (1).  
                   14619: 
                   14620: =back
                   14621: 
                   14622: a scalar containing error condition (if encountered).
                   14623: 
                   14624: =over
                   14625: 
                   14626: =item 
                   14627: no_host (no homeserver identified for $username:$domain).
                   14628: 
                   14629: =item 
                   14630: no_such_host (server contacted for listing not identified as valid host).
                   14631: 
                   14632: =item 
                   14633: con_lost (connection to remote server failed).
                   14634: 
                   14635: =item 
                   14636: refused (invalid $username:$domain received on lond side).
                   14637: 
                   14638: =item 
                   14639: no_such_dir (directory at specified path on lond side does not exist). 
                   14640: 
                   14641: =item 
                   14642: empty (directory at specified path on lond side is empty).
                   14643: 
                   14644: =over
                   14645: 
                   14646: This is currently not encountered because the &ls3, &ls2, 
                   14647: &ls (_handler) routines on the lond side do not filter out
                   14648: . and .. from a directory listing. 
                   14649: 
                   14650: =back
                   14651: 
                   14652: =back
                   14653: 
                   14654: =back
1.191     harris41 14655: 
                   14656: =item *
                   14657: 
1.243     albertel 14658: spareserver() : find server with least workload from spare.tab
                   14659: 
1.986     foxr     14660: 
                   14661: =item *
                   14662: 
                   14663: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   14664: if there is no corresponding loncapa host.
                   14665: 
1.243     albertel 14666: =back
                   14667: 
1.986     foxr     14668: 
1.243     albertel 14669: =head2 Apache Request
                   14670: 
                   14671: =over 4
1.191     harris41 14672: 
                   14673: =item *
                   14674: 
1.243     albertel 14675: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   14676: localhost, posts hash
                   14677: 
                   14678: =back
                   14679: 
                   14680: =head2 Data to String to Data
                   14681: 
                   14682: =over 4
1.191     harris41 14683: 
                   14684: =item *
                   14685: 
1.243     albertel 14686: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   14687: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 14688: 
                   14689: =item *
                   14690: 
1.243     albertel 14691: hashref2str($hashref) : convert a hashref into a string complete with
                   14692: escaping and '=' and '&' separators, supports elements that are
                   14693: arrayrefs and hashrefs
1.191     harris41 14694: 
                   14695: =item *
                   14696: 
1.243     albertel 14697: arrayref2str($arrayref) : convert an arrayref into a string complete
                   14698: with escaping and '&' separators, supports elements that are arrayrefs
                   14699: and hashrefs
1.191     harris41 14700: 
                   14701: =item *
                   14702: 
1.243     albertel 14703: str2hash($string) : convert string to hash using unescaping and
                   14704: splitting on '=' and '&', supports elements that are arrayrefs and
                   14705: hashrefs
1.191     harris41 14706: 
                   14707: =item *
                   14708: 
1.243     albertel 14709: str2array($string) : convert string to hash using unescaping and
                   14710: splitting on '&', supports elements that are arrayrefs and hashrefs
                   14711: 
                   14712: =back
                   14713: 
                   14714: =head2 Logging Routines
                   14715: 
                   14716: 
                   14717: These routines allow one to make log messages in the lonnet.log and
                   14718: lonnet.perm logfiles.
1.191     harris41 14719: 
1.1119    foxr     14720: =over 4
                   14721: 
1.191     harris41 14722: =item *
                   14723: 
1.243     albertel 14724: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 14725: 
                   14726: =item *
                   14727: 
1.243     albertel 14728: logthis() : append message to the normal lonnet.log file, it gets
                   14729: preiodically rolled over and deleted.
1.191     harris41 14730: 
                   14731: =item *
                   14732: 
1.243     albertel 14733: logperm() : append a permanent message to lonnet.perm.log, this log
                   14734: file never gets deleted by any automated portion of the system, only
                   14735: messages of critical importance should go in here.
                   14736: 
1.1119    foxr     14737: 
1.243     albertel 14738: =back
                   14739: 
                   14740: =head2 General File Helper Routines
                   14741: 
                   14742: =over 4
1.191     harris41 14743: 
                   14744: =item *
                   14745: 
1.481     raeburn  14746: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   14747: (a) files in /uploaded
                   14748:   (i) If a local copy of the file exists - 
                   14749:       compares modification date of local copy with last-modified date for 
                   14750:       definitive version stored on home server for course. If local copy is 
                   14751:       stale, requests a new version from the home server and stores it. 
                   14752:       If the original has been removed from the home server, then local copy 
                   14753:       is unlinked.
                   14754:   (ii) If local copy does not exist -
                   14755:       requests the file from the home server and stores it. 
                   14756:   
                   14757:   If $caller is 'uploadrep':  
                   14758:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   14759:     for request for files originally uploaded via DOCS. 
                   14760:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   14761:   
                   14762:   Otherwise:
                   14763:      This indicates a call from the content generation phase of the request.
                   14764:      -  returns the entire contents of the file or -1.
                   14765:      
                   14766: (b) files in /res
                   14767:    - returns the entire contents of a file or -1; 
                   14768:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 14769: 
1.712     albertel 14770: 
                   14771: =item *
                   14772: 
                   14773: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   14774:                   reference
                   14775: 
                   14776: returns either a stat() list of data about the file or an empty list
                   14777: if the file doesn't exist or couldn't find out about it (connection
                   14778: problems or user unknown)
                   14779: 
1.191     harris41 14780: =item *
                   14781: 
1.243     albertel 14782: filelocation($dir,$file) : returns file system location of a file
                   14783: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   14784: directory that relative $file lookups are to looked in ($dir of /a/dir
                   14785: and a file of ../bob will become /a/bob)
1.191     harris41 14786: 
                   14787: =item *
                   14788: 
                   14789: hreflocation($dir,$file) : returns file system location or a URL; same as
                   14790: filelocation except for hrefs
                   14791: 
                   14792: =item *
                   14793: 
1.1172.2.49  raeburn  14794: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   14795: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 14796: 
1.243     albertel 14797: =back
                   14798: 
1.608     albertel 14799: =head2 Usererfile file routines (/uploaded*)
                   14800: 
                   14801: =over 4
                   14802: 
                   14803: =item *
                   14804: 
                   14805: userfileupload(): main rotine for putting a file in a user or course's
                   14806:                   filespace, arguments are,
                   14807: 
1.620     albertel 14808:  formname - required - this is the name of the element in $env where the
1.608     albertel 14809:            filename, and the contents of the file to create/modifed exist
1.620     albertel 14810:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   14811:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  14812:  context - if coursedoc, store the file in the course of the active role
                   14813:              of the current user; 
                   14814:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   14815:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 14816:  subdir - required - subdirectory to put the file in under ../userfiles/
                   14817:          if undefined, it will be placed in "unknown"
                   14818: 
                   14819:  (This routine calls clean_filename() to remove any dangerous
                   14820:  characters from the filename, and then calls finuserfileupload() to
                   14821:  complete the transaction)
                   14822: 
                   14823:  returns either the url of the uploaded file (/uploaded/....) if successful
                   14824:  and /adm/notfound.html if unsuccessful
                   14825: 
                   14826: =item *
                   14827: 
                   14828: clean_filename(): routine for cleaing a filename up for storage in
                   14829:                  userfile space, argument is:
                   14830: 
                   14831:  filename - proposed filename
                   14832: 
                   14833: returns: the new clean filename
                   14834: 
                   14835: =item *
                   14836: 
1.1090    raeburn  14837: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 14838: userspace, probably shouldn't be called directly
                   14839: 
                   14840:   docuname: username or courseid of destination for the file
                   14841:   docudom: domain of user/course of destination for the file
                   14842:   formname: same as for userfileupload()
1.1090    raeburn  14843:   fname: filename (including subdirectories) for the file
                   14844:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   14845:   allfiles: reference to hash used to store objects found by parser
                   14846:   codebase: reference to hash used for codebases of java objects found by parser
                   14847:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   14848:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   14849:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   14850:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   14851:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   14852:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  14853:   mimetype: reference to scalar to accommodate mime type determined
                   14854:             from File::MMagic if $parser = parse.
1.608     albertel 14855: 
                   14856:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  14857:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   14858:  was 'overwrite').
                   14859:  
1.608     albertel 14860: 
                   14861: =item *
                   14862: 
                   14863: renameuserfile(): renames an existing userfile to a new name
                   14864: 
                   14865:   Args:
                   14866:    docuname: username or courseid of destination for the file
                   14867:    docudom: domain of user/course of destination for the file
                   14868:    old: current file name (including any subdirs under userfiles)
                   14869:    new: desired file name (including any subdirs under userfiles)
                   14870: 
                   14871: =item *
                   14872: 
                   14873: mkdiruserfile(): creates a directory is a userfiles dir
                   14874: 
                   14875:   Args:
                   14876:    docuname: username or courseid of destination for the file
                   14877:    docudom: domain of user/course of destination for the file
                   14878:    dir: dir to create (including any subdirs under userfiles)
                   14879: 
                   14880: =item *
                   14881: 
                   14882: removeuserfile(): removes a file that exists in userfiles
                   14883: 
                   14884:   Args:
                   14885:    docuname: username or courseid of destination for the file
                   14886:    docudom: domain of user/course of destination for the file
                   14887:    fname: filname to delete (including any subdirs under userfiles)
                   14888: 
                   14889: =item *
                   14890: 
                   14891: removeuploadedurl(): convience function for removeuserfile()
                   14892: 
                   14893:   Args:
                   14894:    url:  a full /uploaded/... url to delete
                   14895: 
1.747     albertel 14896: =item * 
                   14897: 
                   14898: get_portfile_permissions():
                   14899:   Args:
                   14900:     domain: domain of user or course contain the portfolio files
                   14901:     user: name of user or num of course contain the portfolio files
                   14902:   Returns:
                   14903:     hashref of a dump of the proper file_permissions.db
                   14904:    
                   14905: 
                   14906: =item * 
                   14907: 
                   14908: get_access_controls():
                   14909: 
                   14910: Args:
                   14911:   current_permissions: the hash ref returned from get_portfile_permissions()
                   14912:   group: (optional) the group you want the files associated with
                   14913:   file: (optional) the file you want access info on
                   14914: 
                   14915: Returns:
1.749     raeburn  14916:     a hash (keys are file names) of hashes containing
                   14917:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   14918:         values are XML containing access control settings (see below) 
1.747     albertel 14919: 
                   14920: Internal notes:
                   14921: 
1.749     raeburn  14922:  access controls are stored in file_permissions.db as key=value pairs.
                   14923:     key -> path to file/file_name\0uniqueID:scope_end_start
                   14924:         where scope -> public,guest,course,group,domains or users.
                   14925:               end -> UNIX time for end of access (0 -> no end date)
                   14926:               start -> UNIX time for start of access
                   14927: 
                   14928:     value -> XML description of access control
                   14929:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   14930:             <start></start>
                   14931:             <end></end>
                   14932: 
                   14933:             <password></password>  for scope type = guest
                   14934: 
                   14935:             <domain></domain>     for scope type = course or group
                   14936:             <number></number>
                   14937:             <roles id="">
                   14938:              <role></role>
                   14939:              <access></access>
                   14940:              <section></section>
                   14941:              <group></group>
                   14942:             </roles>
                   14943: 
                   14944:             <dom></dom>         for scope type = domains
                   14945: 
                   14946:             <users>             for scope type = users
                   14947:              <user>
                   14948:               <uname></uname>
                   14949:               <udom></udom>
                   14950:              </user>
                   14951:             </users>
                   14952:            </scope> 
                   14953:               
                   14954:  Access data is also aggregated for each file in an additional key=value pair:
                   14955:  key -> path to file/file_name\0accesscontrol 
                   14956:  value -> reference to hash
                   14957:           hash contains key = value pairs
                   14958:           where key = uniqueID:scope_end_start
                   14959:                 value = UNIX time record was last updated
                   14960: 
                   14961:           Used to improve speed of look-ups of access controls for each file.  
                   14962:  
                   14963:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   14964: 
1.1172.2.13  raeburn  14965: =item *
                   14966: 
1.749     raeburn  14967: modify_access_controls():
                   14968: 
                   14969: Modifies access controls for a portfolio file
                   14970: Args
                   14971: 1. file name
                   14972: 2. reference to hash of required changes,
                   14973: 3. domain
                   14974: 4. username
                   14975:   where domain,username are the domain of the portfolio owner 
                   14976:   (either a user or a course) 
                   14977: 
                   14978: Returns:
                   14979: 1. result of additions or updates ('ok' or 'error', with error message). 
                   14980: 2. result of deletions ('ok' or 'error', with error message).
                   14981: 3. reference to hash of any new or updated access controls.
                   14982: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   14983:    key = integer (inbound ID)
1.1172.2.13  raeburn  14984:    value = uniqueID
                   14985: 
                   14986: =item *
                   14987: 
                   14988: get_timebased_id():
                   14989: 
                   14990: Attempts to get a unique timestamp-based suffix for use with items added to a
                   14991: course via the Course Editor (e.g., folders, composite pages,
                   14992: group bulletin boards).
                   14993: 
                   14994: Args: (first three required; six others optional)
                   14995: 
                   14996: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   14997:    docssequence, or name of group
                   14998: 
                   14999: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15000:    e.g., num, boardids
                   15001: 
                   15002: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   15003:    file will be named nohist_namespace.db
                   15004: 
                   15005: 4. cdom: domain of course; default is current course domain from %env
                   15006: 
                   15007: 5. cnum: course number; default is current course number from %env
                   15008: 
                   15009: 6. idtype: set to concat if an additional digit is to be appended to the
                   15010:    unix timestamp to form the suffix, if the plain timestamp is already
                   15011:    in use.  Default is to not do this, but simply increment the unix
                   15012:    timestamp by 1 until a unique key is obtained.
                   15013: 
                   15014: 7. who: holder of locking key; defaults to user:domain for user.
                   15015: 
                   15016: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   15017:    retrying); default is 3.
                   15018: 
                   15019: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   15020: 
                   15021: Returns:
                   15022: 
                   15023: 1. suffix obtained (numeric)
                   15024: 
                   15025: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15026: 
                   15027: 3. error: contains (localized) error message if an error occurred.
                   15028: 
1.747     albertel 15029: 
1.608     albertel 15030: =back
                   15031: 
1.243     albertel 15032: =head2 HTTP Helper Routines
                   15033: 
                   15034: =over 4
                   15035: 
1.191     harris41 15036: =item *
                   15037: 
                   15038: escape() : unpack non-word characters into CGI-compatible hex codes
                   15039: 
                   15040: =item *
                   15041: 
                   15042: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15043: 
1.243     albertel 15044: =back
                   15045: 
                   15046: =head1 PRIVATE SUBROUTINES
                   15047: 
                   15048: =head2 Underlying communication routines (Shouldn't call)
                   15049: 
                   15050: =over 4
                   15051: 
                   15052: =item *
                   15053: 
                   15054: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15055: 
                   15056: =item *
                   15057: 
                   15058: reply() : uses subreply to send a message to remote machine, logs all failures
                   15059: 
                   15060: =item *
                   15061: 
                   15062: critical() : passes a critical message to another server; if cannot
                   15063: get through then place message in connection buffer directory and
                   15064: returns con_delayed, if incapable of saving message, returns
                   15065: con_failed
                   15066: 
                   15067: =item *
                   15068: 
                   15069: reconlonc() : tries to reconnect lonc client processes.
                   15070: 
                   15071: =back
                   15072: 
                   15073: =head2 Resource Access Logging
                   15074: 
                   15075: =over 4
                   15076: 
                   15077: =item *
                   15078: 
                   15079: flushcourselogs() : flush (save) buffer logs and access logs
                   15080: 
                   15081: =item *
                   15082: 
                   15083: courselog($what) : save message for course in hash
                   15084: 
                   15085: =item *
                   15086: 
                   15087: courseacclog($what) : save message for course using &courselog().  Perform
                   15088: special processing for specific resource types (problems, exams, quizzes, etc).
                   15089: 
1.191     harris41 15090: =item *
                   15091: 
                   15092: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15093: as a PerlChildExitHandler
1.243     albertel 15094: 
                   15095: =back
                   15096: 
                   15097: =head2 Other
                   15098: 
                   15099: =over 4
                   15100: 
                   15101: =item *
                   15102: 
                   15103: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15104: 
                   15105: =back
                   15106: 
                   15107: =cut
1.877     foxr     15108: 

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