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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.93.4  10(raebu    4:18): # $Id: lonnet.pm,v 1.1172.2.93.4.9 2018/04/06 18:20: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.36  raeburn    78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
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.93.4  7(raebur  145:7): 	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.93.4  7(raebur  157:7):     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.93.4  7(raebur  170:7):     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.93.4  7(raebur  439:7):     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.93.4  7(raebur  479:7): 		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.93.4  7(raebur  488:7): 		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.93.4  3(raebur  604:7):     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.93.4  3(raebur  619:7):     if (!-e "$lonidsdir/$handle.id") {
                    620:7):         if ((ref($domref)) && ($name eq 'lonID') &&
                    621:7):             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    622:7):             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    623:7):             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    624:7):                 $$domref = $possudom;
                    625:7):             }
                    626:7):         }
                    627:7):         return undef;
                    628:7):     }
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:         }
                    698:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    699:         if ($opened
                    700: 	    && &timed_flock($env_file,LOCK_EX)
                    701: 	    &&
                    702: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    703: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    704: 	    while (my ($key,$value) = each(%{$newenv})) {
                    705: 	        $disk_env{$key} = $value;
                    706: 	    }
                    707: 	    untie(%disk_env);
1.35      www       708:         }
1.191     harris41  709:     }
1.56      www       710:     return 'ok';
                    711: }
                    712: # ----------------------------------------------------- Delete from Environment
                    713: 
                    714: sub delenv {
1.1104    raeburn   715:     my ($delthis,$regexp,$roles) = @_;
                    716:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    717:         my $refused = 1;
                    718:         if (ref($roles) eq 'ARRAY') {
                    719:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    720:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    721:                 $refused = 0;
                    722:             }
                    723:         }
                    724:         if ($refused) {
                    725:             &logthis("<font color=\"blue\">WARNING: ".
                    726:                      "Attempt to delete from environment ".$delthis);
                    727:             return 'error';
                    728:         }
1.56      www       729:     }
1.917     albertel  730:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    731:     if ($opened
1.915     albertel  732: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  733: 	&&
                    734: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    735: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  736: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   737: 	    if ($regexp) {
                    738:                 if ($key=~/^$delthis/) {
                    739:                     delete($env{$key});
                    740:                     delete($disk_env{$key});
                    741:                 } 
                    742:             } else {
                    743:                 if ($key=~/^\Q$delthis\E/) {
                    744: 		    delete($env{$key});
                    745: 		    delete($disk_env{$key});
                    746: 	        }
                    747:             }
1.448     albertel  748: 	}
1.783     albertel  749: 	untie(%disk_env);
1.5       www       750:     }
                    751:     return 'ok';
1.369     albertel  752: }
                    753: 
1.790     albertel  754: sub get_env_multiple {
                    755:     my ($name) = @_;
                    756:     my @values;
                    757:     if (defined($env{$name})) {
                    758:         # exists is it an array
                    759:         if (ref($env{$name})) {
                    760:             @values=@{ $env{$name} };
                    761:         } else {
                    762:             $values[0]=$env{$name};
                    763:         }
                    764:     }
                    765:     return(@values);
                    766: }
                    767: 
1.958     www       768: # ------------------------------------------------------------------- Locking
                    769: 
                    770: sub set_lock {
                    771:     my ($text)=@_;
                    772:     $locknum++;
                    773:     my $id=$$.'-'.$locknum;
                    774:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    775:              'session.lock.'.$id => $text});
                    776:     return $id;
                    777: }
                    778: 
                    779: sub get_locks {
                    780:     my $num=0;
                    781:     my %texts=();
                    782:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    783:        if ($lock=~/\w/) {
                    784:           $num++;
                    785:           $texts{$lock}=$env{'session.lock.'.$lock};
                    786:        }
                    787:    }
                    788:    return ($num,%texts);
                    789: }
                    790: 
                    791: sub remove_lock {
                    792:     my ($id)=@_;
                    793:     my $newlocks='';
                    794:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    795:        if (($lock=~/\w/) && ($lock ne $id)) {
                    796:           $newlocks.=','.$lock;
                    797:        }
                    798:     }
                    799:     &appenv({'session.locks' => $newlocks});
                    800:     &delenv('session.lock.'.$id);
                    801: }
                    802: 
                    803: sub remove_all_locks {
                    804:     my $activelocks=$env{'session.locks'};
                    805:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    806:        if ($lock=~/\w/) {
                    807:           &remove_lock($lock);
                    808:        }
                    809:     }
                    810: }
                    811: 
                    812: 
1.369     albertel  813: # ------------------------------------------ Find out current server userload
                    814: sub userload {
                    815:     my $numusers=0;
                    816:     {
                    817: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    818: 	my $filename;
                    819: 	my $curtime=time;
                    820: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  821: 	    next if ($filename eq '.' || $filename eq '..');
                    822: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  823: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  824: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  825: 	}
                    826: 	closedir(LONIDS);
                    827:     }
                    828:     my $userloadpercent=0;
                    829:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    830:     if ($maxuserload) {
1.371     albertel  831: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  832:     }
1.372     albertel  833:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  834:     return $userloadpercent;
1.283     www       835: }
                    836: 
1.1       albertel  837: # ------------------------------ Find server with least workload from spare.tab
1.11      www       838: 
1.1       albertel  839: sub spareserver {
1.1083    raeburn   840:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  841:     my $spare_server;
1.370     albertel  842:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  843:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    844:                                                      :  $userloadpercent;
1.1083    raeburn   845:     my ($uint_dom,$remotesessions);
                    846:     if (($udom ne '') && (&domain($udom) ne '')) {
                    847:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    848:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    849:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    850:         $remotesessions = $udomdefaults{'remotesessions'};
                    851:     }
1.1123    raeburn   852:     my $spareshash = &this_host_spares($udom);
                    853:     if (ref($spareshash) eq 'HASH') {
                    854:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    855:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62  raeburn   856:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    857:                                              $try_server));
1.1123    raeburn   858: 	        ($spare_server, $lowest_load) =
                    859: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    860:             }
1.1083    raeburn   861:         }
1.784     albertel  862: 
1.1123    raeburn   863:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    864: 
                    865:         if (!$found_server) {
                    866:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    867: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62  raeburn   868:                     next unless (&spare_can_host($udom,$uint_dom,
                    869:                                                  $remotesessions,$try_server));
1.1123    raeburn   870: 	            ($spare_server, $lowest_load) =
                    871: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    872:                 }
                    873: 	    }
                    874:         }
1.784     albertel  875:     }
                    876: 
                    877:     if (!$want_server_name) {
1.968     raeburn   878:         my $protocol = 'http';
                    879:         if ($protocol{$spare_server} eq 'https') {
                    880:             $protocol = $protocol{$spare_server};
                    881:         }
1.1001    raeburn   882:         if (defined($spare_server)) {
                    883:             my $hostname = &hostname($spare_server);
1.1083    raeburn   884:             if (defined($hostname)) {
1.1001    raeburn   885: 	        $spare_server = $protocol.'://'.$hostname;
                    886:             }
                    887:         }
1.784     albertel  888:     }
                    889:     return $spare_server;
                    890: }
                    891: 
                    892: sub compare_server_load {
1.1172.2.41  raeburn   893:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    894: 
                    895:     if ($required) {
                    896:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    897:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    898:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    899:         if (($major eq '' && $minor eq '') ||
                    900:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    901:             return ($spare_server,$lowest_load);
                    902:         }
                    903:     }
1.784     albertel  904: 
                    905:     my $loadans     = &reply('load',    $try_server);
                    906:     my $userloadans = &reply('userload',$try_server);
                    907: 
                    908:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   909: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  910:     }
                    911: 
                    912:     my $load;
                    913:     if ($loadans =~ /\d/) {
                    914: 	if ($userloadans =~ /\d/) {
                    915: 	    #both are numbers, pick the bigger one
                    916: 	    $load = ($loadans > $userloadans) ? $loadans 
                    917: 		                              : $userloadans;
1.411     albertel  918: 	} else {
1.784     albertel  919: 	    $load = $loadans;
1.411     albertel  920: 	}
1.784     albertel  921:     } else {
                    922: 	$load = $userloadans;
                    923:     }
                    924: 
                    925:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    926: 	$spare_server = $try_server;
                    927: 	$lowest_load  = $load;
1.370     albertel  928:     }
1.784     albertel  929:     return ($spare_server,$lowest_load);
1.202     matthew   930: }
1.914     albertel  931: 
                    932: # --------------------------- ask offload servers if user already has a session
                    933: sub find_existing_session {
                    934:     my ($udom,$uname) = @_;
1.1123    raeburn   935:     my $spareshash = &this_host_spares($udom);
                    936:     if (ref($spareshash) eq 'HASH') {
                    937:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    938:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    939:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    940:             }
                    941:         }
                    942:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    943:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    944:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    945:             }
                    946:         }
1.914     albertel  947:     }
                    948:     return;
                    949: }
                    950: 
                    951: # -------------------------------- ask if server already has a session for user
                    952: sub has_user_session {
                    953:     my ($lonid,$udom,$uname) = @_;
                    954:     my $result = &reply(join(':','userhassession',
                    955: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    956:     return 1 if ($result eq 'ok');
                    957: 
                    958:     return 0;
                    959: }
                    960: 
1.1076    raeburn   961: # --------- determine least loaded server in a user's domain which allows login
                    962: 
                    963: sub choose_server {
1.1172.2.47  raeburn   964:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn   965:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   966:     my %servers = &get_servers($udom);
1.1076    raeburn   967:     my $lowest_load = 30000;
1.1172.2.47  raeburn   968:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                    969:     if ($skiploadbal) {
                    970:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                    971:         unless (defined($cached)) {
                    972:             my $cachetime = 60*60*24;
                    973:             my %domconfig =
                    974:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                    975:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                    976:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                    977:                                            $cachetime);
                    978:             }
                    979:         }
                    980:     }
1.1076    raeburn   981:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   982:         my $loginvia;
1.1172.2.47  raeburn   983:         if ($skiploadbal) {
                    984:             if (ref($balancers) eq 'HASH') {
                    985:                 next if (exists($balancers->{$lonhost}));
                    986:             }
                    987:         }
1.1115    raeburn   988:         if ($checkloginvia) {
                    989:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   990:             if ($loginvia) {
                    991:                 my ($server,$path) = split(/:/,$loginvia);
                    992:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn   993:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn   994:                 if ($login_host eq $server) {
                    995:                     $portal_path = $path;
1.1151    raeburn   996:                     $isredirect = 1;
1.1116    raeburn   997:                 }
                    998:             } else {
                    999:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1000:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1001:                 if ($login_host eq $lonhost) {
                   1002:                     $portal_path = '';
1.1151    raeburn  1003:                     $isredirect = ''; 
1.1116    raeburn  1004:                 }
                   1005:             }
                   1006:         } else {
1.1076    raeburn  1007:             ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1008:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1009:         }
                   1010:     }
                   1011:     if ($login_host ne '') {
1.1116    raeburn  1012:         $hostname = &hostname($login_host);
1.1076    raeburn  1013:     }
1.1172.2.88  raeburn  1014:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1015: }
                   1016: 
1.202     matthew  1017: # --------------------------------------------- Try to change a user's password
                   1018: 
                   1019: sub changepass {
1.799     raeburn  1020:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1021:     $currentpass = &escape($currentpass);
                   1022:     $newpass     = &escape($newpass);
1.1030    raeburn  1023:     my $lonhost = $perlvar{'lonHostID'};
                   1024:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1025: 		       $server);
                   1026:     if (! $answer) {
                   1027: 	&logthis("No reply on password change request to $server ".
                   1028: 		 "by $uname in domain $udom.");
                   1029:     } elsif ($answer =~ "^ok") {
                   1030:         &logthis("$uname in $udom successfully changed their password ".
                   1031: 		 "on $server.");
                   1032:     } elsif ($answer =~ "^pwchange_failure") {
                   1033: 	&logthis("$uname in $udom was unable to change their password ".
                   1034: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1035: 		 "or pwchange");
                   1036:     } elsif ($answer =~ "^non_authorized") {
                   1037:         &logthis("$uname in $udom did not get their password correct when ".
                   1038: 		 "attempting to change it on $server.");
                   1039:     } elsif ($answer =~ "^auth_mode_error") {
                   1040:         &logthis("$uname in $udom attempted to change their password despite ".
                   1041: 		 "not being locally or internally authenticated on $server.");
                   1042:     } elsif ($answer =~ "^unknown_user") {
                   1043:         &logthis("$uname in $udom attempted to change their password ".
                   1044: 		 "on $server but were unable to because $server is not ".
                   1045: 		 "their home server.");
                   1046:     } elsif ($answer =~ "^refused") {
                   1047: 	&logthis("$server refused to change $uname in $udom password because ".
                   1048: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1049:     } elsif ($answer =~ "invalid_client") {
                   1050:         &logthis("$server refused to change $uname in $udom password because ".
                   1051:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1052:     }
                   1053:     return $answer;
1.1       albertel 1054: }
                   1055: 
1.169     harris41 1056: # ----------------------- Try to determine user's current authentication scheme
                   1057: 
                   1058: sub queryauthenticate {
                   1059:     my ($uname,$udom)=@_;
1.456     albertel 1060:     my $uhome=&homeserver($uname,$udom);
                   1061:     if (!$uhome) {
                   1062: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1063: 	return 'no_host';
                   1064:     }
                   1065:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1066:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1067: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1068:     }
1.456     albertel 1069:     return $answer;
1.169     harris41 1070: }
                   1071: 
1.1       albertel 1072: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1073: 
1.1       albertel 1074: sub authenticate {
1.1073    raeburn  1075:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1076:     $upass=&escape($upass);
                   1077:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1078:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1079:     my $newhome;
1.836     www      1080:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1081: # Maybe the machine was offline and only re-appeared again recently?
                   1082:         &reconlonc();
                   1083: # One more
1.952     raeburn  1084: 	$uhome=&homeserver($uname,$udom,1);
                   1085:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1086:             if (defined(&domain($udom,'primary'))) {
                   1087:                 $newhome=&domain($udom,'primary');
                   1088:             }
                   1089:             if ($newhome ne '') {
                   1090:                 $uhome = $newhome;
                   1091:             }
                   1092:         }
1.836     www      1093: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1094: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1095: 	    return 'no_host';
                   1096:         }
1.1       albertel 1097:     }
1.1073    raeburn  1098:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1099:     if ($answer eq 'authorized') {
1.952     raeburn  1100:         if ($newhome) {
                   1101:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1102:             return 'no_account_on_host'; 
                   1103:         } else {
                   1104:             &logthis("User $uname at $udom authorized by $uhome");
                   1105:             return $uhome;
                   1106:         }
1.471     albertel 1107:     }
                   1108:     if ($answer eq 'non_authorized') {
                   1109: 	&logthis("User $uname at $udom rejected by $uhome");
                   1110: 	return 'no_host'; 
1.9       www      1111:     }
1.471     albertel 1112:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1113:     return 'no_host';
                   1114: }
                   1115: 
1.1073    raeburn  1116: sub can_host_session {
1.1074    raeburn  1117:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1118:     my $canhost = 1;
1.1074    raeburn  1119:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1120:     if (ref($remotesessions) eq 'HASH') {
                   1121:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1122:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1123:                 $canhost = 0;
                   1124:             } else {
                   1125:                 $canhost = 1;
                   1126:             }
                   1127:         }
                   1128:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1129:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1130:                 $canhost = 1;
                   1131:             } else {
                   1132:                 $canhost = 0;
                   1133:             }
                   1134:         }
                   1135:         if ($canhost) {
                   1136:             if ($remotesessions->{'version'} ne '') {
                   1137:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1138:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1139:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1140:                         my $major = $1;
                   1141:                         my $minor = $2;
                   1142:                         if (($major < $reqmajor ) ||
                   1143:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1144:                             $canhost = 0;
                   1145:                         }
                   1146:                     } else {
                   1147:                         $canhost = 0;
                   1148:                     }
                   1149:                 }
                   1150:             }
                   1151:         }
                   1152:     }
                   1153:     if ($canhost) {
                   1154:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1155:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1156:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1157:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1158:                 if (($uint_dom ne '') && 
                   1159:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1160:                     $canhost = 0;
                   1161:                 } else {
                   1162:                     $canhost = 1;
                   1163:                 }
                   1164:             }
                   1165:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1166:                 if (($uint_dom ne '') && 
                   1167:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1168:                     $canhost = 1;
                   1169:                 } else {
                   1170:                     $canhost = 0;
                   1171:                 }
                   1172:             }
                   1173:         }
                   1174:     }
                   1175:     return $canhost;
                   1176: }
                   1177: 
1.1083    raeburn  1178: sub spare_can_host {
                   1179:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1180:     my $canhost=1;
1.1172.2.62  raeburn  1181:     my $try_server_hostname = &hostname($try_server);
                   1182:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1183:     my $serverhomedom = &host_domain($serverhomeID);
                   1184:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1185:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1186:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1187:             $canhost = 0;
                   1188:         }
                   1189:     }
                   1190:     if (($canhost) && ($uint_dom)) {
                   1191:         my @intdoms;
                   1192:         my $internet_names = &get_internet_names($try_server);
                   1193:         if (ref($internet_names) eq 'ARRAY') {
                   1194:             @intdoms = @{$internet_names};
                   1195:         }
                   1196:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1197:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1198:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1199:                                          $remotesessions,
                   1200:                                          $defdomdefaults{'hostedsessions'});
                   1201:         }
1.1083    raeburn  1202:     }
                   1203:     return $canhost;
                   1204: }
                   1205: 
1.1123    raeburn  1206: sub this_host_spares {
                   1207:     my ($dom) = @_;
1.1126    raeburn  1208:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1209:     my @hosts = &current_machine_ids();
                   1210:     foreach my $lonhost (@hosts) {
                   1211:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1212:             $dom_in_use = $dom;
                   1213:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1214:             last;
                   1215:         }
                   1216:     }
1.1126    raeburn  1217:     if ($dom_in_use ne '') {
                   1218:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1219:     }
                   1220:     if (ref($result) ne 'HASH') {
                   1221:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1222:         $dom_in_use = &host_domain($lonhost_in_use);
                   1223:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1224:         if (ref($result) ne 'HASH') {
                   1225:             $result = \%spareid;
                   1226:         }
                   1227:     }
                   1228:     return $result;
                   1229: }
                   1230: 
                   1231: sub spares_for_offload  {
                   1232:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1233:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1234:     if (defined($cached)) {
                   1235:         return $result;
                   1236:     } else {
1.1126    raeburn  1237:         my $cachetime = 60*60*24;
                   1238:         my %domconfig =
                   1239:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1240:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1241:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1242:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1243:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1244:                 }
                   1245:             }
                   1246:         }
                   1247:     }
1.1126    raeburn  1248:     return;
1.1123    raeburn  1249: }
                   1250: 
1.1129    raeburn  1251: sub get_lonbalancer_config {
                   1252:     my ($servers) = @_;
                   1253:     my ($currbalancer,$currtargets);
                   1254:     if (ref($servers) eq 'HASH') {
                   1255:         foreach my $server (keys(%{$servers})) {
                   1256:             my %what = (
                   1257:                          spareid => 1,
                   1258:                          perlvar => 1,
                   1259:                        );
                   1260:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1261:             if ($result eq 'ok') {
                   1262:                 if (ref($returnhash) eq 'HASH') {
                   1263:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1264:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1265:                             $currbalancer = $server;
                   1266:                             $currtargets = {};
                   1267:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1268:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1269:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1270:                                 }
                   1271:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1272:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1273:                                 }
                   1274:                             }
                   1275:                             last;
                   1276:                         }
                   1277:                     }
                   1278:                 }
                   1279:             }
                   1280:         }
                   1281:     }
                   1282:     return ($currbalancer,$currtargets);
                   1283: }
                   1284: 
                   1285: sub check_loadbalancing {
1.1172.2.88  raeburn  1286:     my ($uname,$udom,$caller) = @_;
1.1172.2.12  raeburn  1287:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1288:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1289:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1290:     my @hosts = &current_machine_ids();
1.1129    raeburn  1291:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1292:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1293:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1294:     my $serverhomedom = &host_domain($lonhost);
1.1172.2.75  raeburn  1295:     my $domneedscache; 
1.1129    raeburn  1296:     my $cachetime = 60*60*24;
                   1297: 
                   1298:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1299:         $dom_in_use = $udom;
                   1300:         $homeintdom = 1;
                   1301:     } else {
                   1302:         $dom_in_use = $serverhomedom;
                   1303:     }
                   1304:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1305:     unless (defined($cached)) {
                   1306:         my %domconfig =
                   1307:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1308:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1309:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75  raeburn  1310:         } else {
                   1311:             $domneedscache = $dom_in_use;
1.1129    raeburn  1312:         }
                   1313:     }
                   1314:     if (ref($result) eq 'HASH') {
1.1172.2.12  raeburn  1315:         ($is_balancer,$currtargets,$currrules) =
                   1316:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1317:         if ($is_balancer) {
                   1318:             if (ref($currrules) eq 'HASH') {
                   1319:                 if ($homeintdom) {
                   1320:                     if ($uname ne '') {
                   1321:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1322:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1323:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1324:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1325:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1326:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1327:                             }
                   1328:                         }
                   1329:                         if ($rule_in_effect eq '') {
                   1330:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1331:                             if ($userenv{'inststatus'} ne '') {
                   1332:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1333:                                 my ($othertitle,$usertypes,$types) =
                   1334:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1335:                                 if (ref($types) eq 'ARRAY') {
                   1336:                                     foreach my $type (@{$types}) {
                   1337:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1338:                                             if (exists($currrules->{$type})) {
                   1339:                                                 $rule_in_effect = $currrules->{$type};
                   1340:                                             }
                   1341:                                         }
                   1342:                                     }
                   1343:                                 }
                   1344:                             } else {
                   1345:                                 if (exists($currrules->{'default'})) {
                   1346:                                     $rule_in_effect = $currrules->{'default'};
                   1347:                                 }
                   1348:                             }
                   1349:                         }
                   1350:                     } else {
                   1351:                         if (exists($currrules->{'default'})) {
                   1352:                             $rule_in_effect = $currrules->{'default'};
                   1353:                         }
                   1354:                     }
                   1355:                 } else {
                   1356:                     if ($currrules->{'_LC_external'} ne '') {
                   1357:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1358:                     }
                   1359:                 }
                   1360:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1361:                                                        $uname,$udom);
                   1362:             }
                   1363:         }
                   1364:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35  raeburn  1365:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1366:         unless (defined($cached)) {
                   1367:             my %domconfig =
                   1368:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1369:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75  raeburn  1370:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1371:             } else {
                   1372:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1373:             }
                   1374:         }
                   1375:         if (ref($result) eq 'HASH') {
1.1172.2.12  raeburn  1376:             ($is_balancer,$currtargets,$currrules) =
                   1377:                 &check_balancer_result($result,@hosts);
                   1378:             if ($is_balancer) {
1.1129    raeburn  1379:                 if (ref($currrules) eq 'HASH') {
                   1380:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1381:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1382:                     }
                   1383:                 }
                   1384:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1385:                                                        $uname,$udom);
                   1386:             }
                   1387:         } else {
                   1388:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1389:                 $is_balancer = 1;
                   1390:                 $offloadto = &this_host_spares($dom_in_use);
                   1391:             }
1.1172.2.75  raeburn  1392:             unless (defined($cached)) {
                   1393:                 $domneedscache = $serverhomedom;
                   1394:             }
1.1129    raeburn  1395:         }
                   1396:     } else {
                   1397:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1398:             $is_balancer = 1;
                   1399:             $offloadto = &this_host_spares($dom_in_use);
                   1400:         }
1.1172.2.75  raeburn  1401:         unless (defined($cached)) {
                   1402:             $domneedscache = $serverhomedom;
                   1403:         }
                   1404:     }
                   1405:     if ($domneedscache) {
                   1406:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1407:     }
1.1172.2.5  raeburn  1408:     if ($is_balancer) {
                   1409:         my $lowest_load = 30000;
                   1410:         if (ref($offloadto) eq 'HASH') {
                   1411:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1412:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1413:                     ($otherserver,$lowest_load) =
                   1414:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1415:                 }
1.1129    raeburn  1416:             }
1.1172.2.5  raeburn  1417:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1418: 
1.1172.2.5  raeburn  1419:             if (!$found_server) {
                   1420:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1421:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1422:                         ($otherserver,$lowest_load) =
                   1423:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1424:                     }
                   1425:                 }
                   1426:             }
                   1427:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1428:             if (@{$offloadto} == 1) {
                   1429:                 $otherserver = $offloadto->[0];
                   1430:             } elsif (@{$offloadto} > 1) {
                   1431:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1432:                     ($otherserver,$lowest_load) =
                   1433:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1434:                 }
                   1435:             }
                   1436:         }
1.1172.2.88  raeburn  1437:         unless ($caller eq 'login') {
                   1438:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1439:                 $is_balancer = 0;
                   1440:                 if ($uname ne '' && $udom ne '') {
                   1441:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1172.2.5  raeburn  1442: 
1.1172.2.88  raeburn  1443:                         &appenv({'user.loadbalexempt'     => $lonhost,
                   1444:                                  'user.loadbalcheck.time' => time});
                   1445:                     }
1.1172.2.5  raeburn  1446:                 }
1.1129    raeburn  1447:             }
                   1448:         }
                   1449:     }
                   1450:     return ($is_balancer,$otherserver);
                   1451: }
                   1452: 
1.1172.2.12  raeburn  1453: sub check_balancer_result {
                   1454:     my ($result,@hosts) = @_;
                   1455:     my ($is_balancer,$currtargets,$currrules);
                   1456:     if (ref($result) eq 'HASH') {
                   1457:         if ($result->{'lonhost'} ne '') {
                   1458:             my $currbalancer = $result->{'lonhost'};
                   1459:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1460:                 $is_balancer = 1;
                   1461:                 $currtargets = $result->{'targets'};
                   1462:                 $currrules = $result->{'rules'};
                   1463:             }
                   1464:         } else {
                   1465:             foreach my $key (keys(%{$result})) {
                   1466:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1467:                     (ref($result->{$key}) eq 'HASH')) {
                   1468:                     $is_balancer = 1;
                   1469:                     $currrules = $result->{$key}{'rules'};
                   1470:                     $currtargets = $result->{$key}{'targets'};
                   1471:                     last;
                   1472:                 }
                   1473:             }
                   1474:         }
                   1475:     }
                   1476:     return ($is_balancer,$currtargets,$currrules);
                   1477: }
                   1478: 
1.1129    raeburn  1479: sub get_loadbalancer_targets {
                   1480:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1481:     my $offloadto;
1.1172.2.4  raeburn  1482:     if ($rule_in_effect eq 'none') {
                   1483:         return [$perlvar{'lonHostID'}];
                   1484:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1485:         $offloadto = $currtargets;
                   1486:     } else {
                   1487:         if ($rule_in_effect eq 'homeserver') {
                   1488:             my $homeserver = &homeserver($uname,$udom);
                   1489:             if ($homeserver ne 'no_host') {
                   1490:                 $offloadto = [$homeserver];
                   1491:             }
                   1492:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1493:             my %domconfig =
                   1494:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1495:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1496:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1497:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1498:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1499:                     }
                   1500:                 }
                   1501:             } else {
1.1172.2.7  raeburn  1502:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1503:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1504:                 if (&hostname($remotebalancer) ne '') {
                   1505:                     $offloadto = [$remotebalancer];
                   1506:                 }
                   1507:             }
                   1508:         } elsif (&hostname($rule_in_effect) ne '') {
                   1509:             $offloadto = [$rule_in_effect];
                   1510:         }
                   1511:     }
                   1512:     return $offloadto;
                   1513: }
                   1514: 
1.1127    raeburn  1515: sub internet_dom_servers {
                   1516:     my ($dom) = @_;
                   1517:     my (%uniqservers,%servers);
                   1518:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1519:     my @machinedoms = &machine_domains($primaryserver);
                   1520:     foreach my $mdom (@machinedoms) {
                   1521:         my %currservers = %servers;
                   1522:         my %server = &get_servers($mdom);
                   1523:         %servers = (%currservers,%server);
                   1524:     }
                   1525:     my %by_hostname;
                   1526:     foreach my $id (keys(%servers)) {
                   1527:         push(@{$by_hostname{$servers{$id}}},$id);
                   1528:     }
                   1529:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1530:         if (@{$by_hostname{$hostname}} > 1) {
                   1531:             my $match = 0;
                   1532:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1533:                 if (&host_domain($id) eq $dom) {
                   1534:                     $uniqservers{$id} = $hostname;
                   1535:                     $match = 1;
                   1536:                 }
                   1537:             }
                   1538:             unless ($match) {
                   1539:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1540:             }
                   1541:         } else {
                   1542:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1543:         }
                   1544:     }
                   1545:     return %uniqservers;
                   1546: }
                   1547: 
1.1       albertel 1548: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1549: 
1.599     albertel 1550: my %homecache;
1.1       albertel 1551: sub homeserver {
1.230     stredwic 1552:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1553:     my $index="$uname:$udom";
1.426     albertel 1554: 
1.599     albertel 1555:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1556: 
                   1557:     my %servers = &get_servers($udom,'library');
                   1558:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1559:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1560: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1561: 
                   1562: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1563: 	if ($answer eq 'found') {
                   1564: 	    delete($badServerCache{$tryserver}); 
                   1565: 	    return $homecache{$index}=$tryserver;
                   1566: 	} elsif ($answer eq 'no_host') {
                   1567: 	    $badServerCache{$tryserver}=1;
                   1568: 	}
1.1       albertel 1569:     }    
                   1570:     return 'no_host';
1.70      www      1571: }
                   1572: 
                   1573: # ------------------------------------- Find the usernames behind a list of IDs
                   1574: 
                   1575: sub idget {
                   1576:     my ($udom,@ids)=@_;
                   1577:     my %returnhash=();
                   1578:     
1.841     albertel 1579:     my %servers = &get_servers($udom,'library');
                   1580:     foreach my $tryserver (keys(%servers)) {
1.1172.2.73  raeburn  1581: 	my $idlist=join('&', map { &escape($_); } @ids);
1.841     albertel 1582: 	$idlist=~tr/A-Z/a-z/; 
                   1583: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1584: 	my @answer=();
                   1585: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1586: 	    @answer=split(/\&/,$reply);
                   1587: 	}                    ;
                   1588: 	my $i;
                   1589: 	for ($i=0;$i<=$#ids;$i++) {
                   1590: 	    if ($answer[$i]) {
1.1172.2.73  raeburn  1591: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841     albertel 1592: 	    } 
                   1593: 	}
                   1594:     } 
1.70      www      1595:     return %returnhash;
                   1596: }
                   1597: 
                   1598: # ------------------------------------- Find the IDs behind a list of usernames
                   1599: 
                   1600: sub idrget {
                   1601:     my ($udom,@unames)=@_;
                   1602:     my %returnhash=();
1.800     albertel 1603:     foreach my $uname (@unames) {
                   1604:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1605:     }
1.70      www      1606:     return %returnhash;
                   1607: }
                   1608: 
                   1609: # ------------------------------- Store away a list of names and associated IDs
                   1610: 
                   1611: sub idput {
                   1612:     my ($udom,%ids)=@_;
                   1613:     my %servers=();
1.800     albertel 1614:     foreach my $uname (keys(%ids)) {
                   1615: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1616:         my $uhom=&homeserver($uname,$udom);
1.70      www      1617:         if ($uhom ne 'no_host') {
1.800     albertel 1618:             my $id=&escape($ids{$uname});
1.70      www      1619:             $id=~tr/A-Z/a-z/;
1.800     albertel 1620:             my $esc_unam=&escape($uname);
1.70      www      1621: 	    if ($servers{$uhom}) {
1.800     albertel 1622: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1623:             } else {
1.800     albertel 1624:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1625:             }
                   1626:         }
1.191     harris41 1627:     }
1.800     albertel 1628:     foreach my $server (keys(%servers)) {
                   1629:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1630:     }
1.344     www      1631: }
                   1632: 
1.1172.2.30  raeburn  1633: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1634: 
                   1635: sub iddel {
                   1636:     my ($udom,$idshashref,$uhome)=@_;
                   1637:     my %result=();
                   1638:     unless (ref($idshashref) eq 'HASH') {
                   1639:         return %result;
                   1640:     }
                   1641:     my %servers=();
                   1642:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1643:         my $uhom;
                   1644:         if ($uhome) {
                   1645:             $uhom = $uhome;
                   1646:         } else {
                   1647:             $uhom=&homeserver($uname,$udom);
                   1648:         }
                   1649:         if ($uhom ne 'no_host') {
                   1650:             if ($servers{$uhom}) {
                   1651:                 $servers{$uhom}.='&'.&escape($id);
                   1652:             } else {
                   1653:                 $servers{$uhom}=&escape($id);
                   1654:             }
                   1655:         }
                   1656:     }
                   1657:     foreach my $server (keys(%servers)) {
                   1658:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1659:     }
                   1660:     return %result;
                   1661: }
                   1662: 
1.1023    raeburn  1663: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1664: sub dump_dom {
1.1165    droeschl 1665:     my ($namespace, $udom, $regexp) = @_;
                   1666: 
                   1667:     $udom ||= $env{'user.domain'};
                   1668: 
                   1669:     return () unless $udom;
                   1670: 
                   1671:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1672: }
                   1673: 
1.1023    raeburn  1674: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1675: 
                   1676: sub get_dom {
1.860     raeburn  1677:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57  raeburn  1678:     return if ($udom eq 'public');
1.806     raeburn  1679:     my $items='';
                   1680:     foreach my $item (@$storearr) {
                   1681:         $items.=&escape($item).'&';
                   1682:     }
                   1683:     $items=~s/\&$//;
1.860     raeburn  1684:     if (!$udom) {
                   1685:         $udom=$env{'user.domain'};
1.1172.2.57  raeburn  1686:         return if ($udom eq 'public');
1.860     raeburn  1687:         if (defined(&domain($udom,'primary'))) {
                   1688:             $uhome=&domain($udom,'primary');
                   1689:         } else {
1.874     albertel 1690:             undef($uhome);
1.860     raeburn  1691:         }
                   1692:     } else {
                   1693:         if (!$uhome) {
                   1694:             if (defined(&domain($udom,'primary'))) {
                   1695:                 $uhome=&domain($udom,'primary');
                   1696:             }
                   1697:         }
                   1698:     }
                   1699:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1172.2.93.4  2(raebur 1700:7):         my $rep;
                   1701:7):         if ($namespace =~ /^enc/) {
                   1702:7):             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   1703:7):         } else {
                   1704:7):             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   1705:7):         }
1.866     raeburn  1706:         my %returnhash;
1.875     albertel 1707:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1708:             return %returnhash;
                   1709:         }
1.806     raeburn  1710:         my @pairs=split(/\&/,$rep);
                   1711:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1712:             return @pairs;
                   1713:         }
                   1714:         my $i=0;
                   1715:         foreach my $item (@$storearr) {
                   1716:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1717:             $i++;
                   1718:         }
                   1719:         return %returnhash;
                   1720:     } else {
1.880     banghart 1721:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1722:     }
                   1723: }
                   1724: 
                   1725: # -------------------------------------------- put items in domain db files 
                   1726: 
                   1727: sub put_dom {
1.860     raeburn  1728:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1729:     if (!$udom) {
                   1730:         $udom=$env{'user.domain'};
                   1731:         if (defined(&domain($udom,'primary'))) {
                   1732:             $uhome=&domain($udom,'primary');
                   1733:         } else {
1.874     albertel 1734:             undef($uhome);
1.860     raeburn  1735:         }
                   1736:     } else {
                   1737:         if (!$uhome) {
                   1738:             if (defined(&domain($udom,'primary'))) {
                   1739:                 $uhome=&domain($udom,'primary');
                   1740:             }
                   1741:         }
                   1742:     } 
                   1743:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1744:         my $items='';
                   1745:         foreach my $item (keys(%$storehash)) {
                   1746:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1747:         }
                   1748:         $items=~s/\&$//;
1.1172.2.93.4  2(raebur 1749:7):         if ($namespace =~ /^enc/) {
                   1750:7):             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   1751:7):         } else {
                   1752:7):             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1753:7):         }
1.806     raeburn  1754:     } else {
1.860     raeburn  1755:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1756:     }
                   1757: }
                   1758: 
1.1023    raeburn  1759: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1760: sub newput_dom {
1.1023    raeburn  1761:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1762:     my $result;
                   1763:     if (!$udom) {
                   1764:         $udom=$env{'user.domain'};
                   1765:     }
1.1023    raeburn  1766:     if ($udom) {
                   1767:         my $uname = &get_domainconfiguser($udom);
                   1768:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1769:     }
                   1770:     return $result;
                   1771: }
                   1772: 
1.1023    raeburn  1773: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1774: sub del_dom {
1.1023    raeburn  1775:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1776:     if (ref($storearr) eq 'ARRAY') {
                   1777:         if (!$udom) {
                   1778:             $udom=$env{'user.domain'};
                   1779:         }
1.1023    raeburn  1780:         if ($udom) {
                   1781:             my $uname = &get_domainconfiguser($udom); 
                   1782:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1783:         }
                   1784:     }
                   1785: }
                   1786: 
1.1023    raeburn  1787: # ----------------------------------construct domainconfig user for a domain 
                   1788: sub get_domainconfiguser {
                   1789:     my ($udom) = @_;
                   1790:     return $udom.'-domainconfig';
                   1791: }
                   1792: 
1.837     raeburn  1793: sub retrieve_inst_usertypes {
                   1794:     my ($udom) = @_;
                   1795:     my (%returnhash,@order);
1.989     raeburn  1796:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1797:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1798:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  1799:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1800:     } else {
                   1801:         if (defined(&domain($udom,'primary'))) {
                   1802:             my $uhome=&domain($udom,'primary');
                   1803:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1804:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  1805:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1806:                 return (\%returnhash,\@order);
                   1807:             }
                   1808:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1809:             my @pairs=split(/\&/,$hashitems);
                   1810:             foreach my $item (@pairs) {
                   1811:                 my ($key,$value)=split(/=/,$item,2);
                   1812:                 $key = &unescape($key);
                   1813:                 next if ($key =~ /^error: 2 /);
                   1814:                 $returnhash{$key}=&thaw_unescape($value);
                   1815:             }
                   1816:             my @esc_order = split(/\&/,$orderitems);
                   1817:             foreach my $item (@esc_order) {
                   1818:                 push(@order,&unescape($item));
                   1819:             }
                   1820:         } else {
1.1172.2.44  raeburn  1821:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1822:         }
1.1172.2.44  raeburn  1823:         return (\%returnhash,\@order);
1.837     raeburn  1824:     }
                   1825: }
                   1826: 
1.868     raeburn  1827: sub is_domainimage {
                   1828:     my ($url) = @_;
1.1172.2.74  raeburn  1829:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  1830:         if (&domain($1) ne '') {
                   1831:             return '1';
                   1832:         }
                   1833:     }
                   1834:     return;
                   1835: }
                   1836: 
1.899     raeburn  1837: sub inst_directory_query {
                   1838:     my ($srch) = @_;
                   1839:     my $udom = $srch->{'srchdomain'};
                   1840:     my %results;
                   1841:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1842:     my $outcome;
1.899     raeburn  1843:     if ($homeserver ne '') {
1.1172.2.93.4  4(raebur 1844:7):         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   1845:7):             if ($srch->{'srchby'} eq 'email') {
                   1846:7):                 my $lcrev = &get_server_loncaparev(undef,$homeserver);
                   1847:7):                 my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.([\w.\-]+)\'?$/);
                   1848:7):                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   1849:7):                     (($major == 2) && ($minor < 11)) || 
                   1850:7):                     (($major == 2) && ($minor == 11) && ($subver !~ /^2\.B/))) {
                   1851:7):                     return;
                   1852:7):                 }
                   1853:7):             }
                   1854:7):         }
1.904     albertel 1855: 	my $queryid=&reply("querysend:instdirsearch:".
                   1856: 			   &escape($srch->{'srchby'}).':'.
                   1857: 			   &escape($srch->{'srchterm'}).':'.
                   1858: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1859: 	my $host=&hostname($homeserver);
                   1860: 	if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.93.4  1(raebur 1861:7): 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 1862: 	    return;
                   1863: 	}
                   1864: 	my $response = &get_query_reply($queryid);
                   1865: 	my $maxtries = 5;
                   1866: 	my $tries = 1;
                   1867: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1868: 	    $response = &get_query_reply($queryid);
                   1869: 	    $tries ++;
                   1870: 	}
                   1871: 
                   1872:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1873:             if ($response eq 'unavailable') {
                   1874:                 $outcome = $response;
                   1875:             } else {
                   1876:                 $outcome = 'ok';
                   1877:                 my @matches = split(/\n/,$response);
                   1878:                 foreach my $match (@matches) {
                   1879:                     my ($key,$value) = split(/=/,$match);
                   1880:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1881:                 }
1.899     raeburn  1882:             }
                   1883:         }
                   1884:     }
1.909     raeburn  1885:     return ($outcome,%results);
1.899     raeburn  1886: }
                   1887: 
                   1888: sub usersearch {
                   1889:     my ($srch) = @_;
                   1890:     my $dom = $srch->{'srchdomain'};
                   1891:     my %results;
                   1892:     my %libserv = &all_library();
                   1893:     my $query = 'usersearch';
                   1894:     foreach my $tryserver (keys(%libserv)) {
                   1895:         if (&host_domain($tryserver) eq $dom) {
1.1172.2.93.4  4(raebur 1896:7):             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   1897:7):                 if ($srch->{'srchby'} eq 'email') {
                   1898:7):                     my $lcrev = &get_server_loncaparev(undef,$tryserver);
                   1899:7):                     my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.([\w.\-]+)\'?$/);
                   1900:7):                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   1901:7):                              (($major == 2) && ($minor < 11)) || 
          6(raebur 1902:7):                              (($major == 2) && ($minor == 11) && ($subver !~ /^2\.B/)));
          4(raebur 1903:7):                 }
                   1904:7):             }
1.899     raeburn  1905:             my $host=&hostname($tryserver);
                   1906:             my $queryid=
1.911     raeburn  1907:                 &reply("querysend:".&escape($query).':'.
                   1908:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1909:                        &escape($srch->{'srchtype'}).':'.
                   1910:                        &escape($srch->{'srchterm'}),$tryserver);
                   1911:             if ($queryid !~/^\Q$host\E\_/) {
                   1912:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1913:                 next;
1.899     raeburn  1914:             }
                   1915:             my $reply = &get_query_reply($queryid);
                   1916:             my $maxtries = 1;
                   1917:             my $tries = 1;
                   1918:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1919:                 $reply = &get_query_reply($queryid);
                   1920:                 $tries ++;
                   1921:             }
                   1922:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1923:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1924:             } else {
1.911     raeburn  1925:                 my @matches;
                   1926:                 if ($reply =~ /\n/) {
                   1927:                     @matches = split(/\n/,$reply);
                   1928:                 } else {
                   1929:                     @matches = split(/\&/,$reply);
                   1930:                 }
1.899     raeburn  1931:                 foreach my $match (@matches) {
                   1932:                     my ($uname,$udom,%userhash);
1.911     raeburn  1933:                     foreach my $entry (split(/:/,$match)) {
                   1934:                         my ($key,$value) =
                   1935:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1936:                         $userhash{$key} = $value;
                   1937:                         if ($key eq 'username') {
                   1938:                             $uname = $value;
                   1939:                         } elsif ($key eq 'domain') {
                   1940:                             $udom = $value;
1.911     raeburn  1941:                         }
1.899     raeburn  1942:                     }
                   1943:                     $results{$uname.':'.$udom} = \%userhash;
                   1944:                 }
                   1945:             }
                   1946:         }
                   1947:     }
                   1948:     return %results;
                   1949: }
                   1950: 
1.912     raeburn  1951: sub get_instuser {
                   1952:     my ($udom,$uname,$id) = @_;
                   1953:     my $homeserver = &domain($udom,'primary');
                   1954:     my ($outcome,%results);
                   1955:     if ($homeserver ne '') {
                   1956:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1957:                            &escape($id).':'.&escape($udom),$homeserver);
                   1958:         my $host=&hostname($homeserver);
                   1959:         if ($queryid !~/^\Q$host\E\_/) {
                   1960:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1961:             return;
                   1962:         }
                   1963:         my $response = &get_query_reply($queryid);
                   1964:         my $maxtries = 5;
                   1965:         my $tries = 1;
                   1966:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1967:             $response = &get_query_reply($queryid);
                   1968:             $tries ++;
                   1969:         }
                   1970:         if (!&error($response) && $response ne 'refused') {
                   1971:             if ($response eq 'unavailable') {
                   1972:                 $outcome = $response;
                   1973:             } else {
                   1974:                 $outcome = 'ok';
                   1975:                 my @matches = split(/\n/,$response);
                   1976:                 foreach my $match (@matches) {
                   1977:                     my ($key,$value) = split(/=/,$match);
                   1978:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1979:                 }
                   1980:             }
                   1981:         }
                   1982:     }
                   1983:     my %userinfo;
                   1984:     if (ref($results{$uname}) eq 'HASH') {
                   1985:         %userinfo = %{$results{$uname}};
                   1986:     } 
                   1987:     return ($outcome,%userinfo);
                   1988: }
                   1989: 
1.1172.2.69  raeburn  1990: sub get_multiple_instusers {
                   1991:     my ($udom,$users,$caller) = @_;
                   1992:     my ($outcome,$results);
                   1993:     if (ref($users) eq 'HASH') {
                   1994:         my $count = keys(%{$users});
                   1995:         my $requested = &freeze_escape($users);
                   1996:         my $homeserver = &domain($udom,'primary');
                   1997:         if ($homeserver ne '') {
                   1998:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   1999:             my $host=&hostname($homeserver);
                   2000:             if ($queryid !~/^\Q$host\E\_/) {
                   2001:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2002:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2003:                 return ($outcome,$results);
                   2004:             }
                   2005:             my $response = &get_query_reply($queryid);
                   2006:             my $maxtries = 5;
                   2007:             if ($count > 100) {
                   2008:                 $maxtries = 1+int($count/20);
                   2009:             }
                   2010:             my $tries = 1;
                   2011:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2012:                 $response = &get_query_reply($queryid);
                   2013:                 $tries ++;
                   2014:             }
                   2015:             if ($response eq '') {
                   2016:                 $results = {};
                   2017:                 foreach my $key (keys(%{$users})) {
                   2018:                     my ($uname,$id);
                   2019:                     if ($caller eq 'id') {
                   2020:                         $id = $key;
                   2021:                     } else {
                   2022:                         $uname = $key;
                   2023:                     }
                   2024:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
                   2025:                     $outcome = $resp;
                   2026:                     if ($resp eq 'ok') {
                   2027:                         %{$results} = (%{$results}, %info);
                   2028:                     } else {
                   2029:                         last;
                   2030:                     }
                   2031:                 }
                   2032:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2033:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2034:                     $outcome = $response;
                   2035:                 } else {
                   2036:                     ($outcome,my $userdata) = split(/=/,$response,2);
                   2037:                     if ($outcome eq 'ok') {
                   2038:                         $results = &thaw_unescape($userdata);
                   2039:                     }
                   2040:                 }
                   2041:             }
                   2042:         }
                   2043:     }
                   2044:     return ($outcome,$results);
                   2045: }
                   2046: 
1.912     raeburn  2047: sub inst_rulecheck {
1.923     raeburn  2048:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2049:     my %returnhash;
                   2050:     if ($udom ne '') {
                   2051:         if (ref($rules) eq 'ARRAY') {
                   2052:             @{$rules} = map {&escape($_);} (@{$rules});
                   2053:             my $rulestr = join(':',@{$rules});
                   2054:             my $homeserver=&domain($udom,'primary');
                   2055:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2056:                 my $response;
                   2057:                 if ($item eq 'username') {                
                   2058:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2059:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2060:                                               $homeserver));
1.923     raeburn  2061:                 } elsif ($item eq 'id') {
                   2062:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2063:                                               ':'.&escape($id).':'.$rulestr,
                   2064:                                               $homeserver));
1.945     raeburn  2065:                 } elsif ($item eq 'selfcreate') {
                   2066:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2067:                                                &escape($udom).':'.&escape($uname).
                   2068:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2069:                 }
1.912     raeburn  2070:                 if ($response ne 'refused') {
                   2071:                     my @pairs=split(/\&/,$response);
                   2072:                     foreach my $item (@pairs) {
                   2073:                         my ($key,$value)=split(/=/,$item,2);
                   2074:                         $key = &unescape($key);
                   2075:                         next if ($key =~ /^error: 2 /);
                   2076:                         $returnhash{$key}=&thaw_unescape($value);
                   2077:                     }
                   2078:                 }
                   2079:             }
                   2080:         }
                   2081:     }
                   2082:     return %returnhash;
                   2083: }
                   2084: 
                   2085: sub inst_userrules {
1.923     raeburn  2086:     my ($udom,$check) = @_;
1.912     raeburn  2087:     my (%ruleshash,@ruleorder);
                   2088:     if ($udom ne '') {
                   2089:         my $homeserver=&domain($udom,'primary');
                   2090:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2091:             my $response;
                   2092:             if ($check eq 'id') {
                   2093:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2094:                                  $homeserver);
1.943     raeburn  2095:             } elsif ($check eq 'email') {
                   2096:                 $response=&reply('instemailrules:'.&escape($udom),
                   2097:                                  $homeserver);
1.923     raeburn  2098:             } else {
                   2099:                 $response=&reply('instuserrules:'.&escape($udom),
                   2100:                                  $homeserver);
                   2101:             }
1.912     raeburn  2102:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2103:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2104:                 ($response ne 'no_such_host')) {
                   2105:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2106:                 my @pairs=split(/\&/,$hashitems);
                   2107:                 foreach my $item (@pairs) {
                   2108:                     my ($key,$value)=split(/=/,$item,2);
                   2109:                     $key = &unescape($key);
                   2110:                     next if ($key =~ /^error: 2 /);
                   2111:                     $ruleshash{$key}=&thaw_unescape($value);
                   2112:                 }
                   2113:                 my @esc_order = split(/\&/,$orderitems);
                   2114:                 foreach my $item (@esc_order) {
                   2115:                     push(@ruleorder,&unescape($item));
                   2116:                 }
                   2117:             }
                   2118:         }
                   2119:     }
                   2120:     return (\%ruleshash,\@ruleorder);
                   2121: }
                   2122: 
1.976     raeburn  2123: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2124: 
                   2125: sub get_domain_defaults {
1.1172.2.35  raeburn  2126:     my ($domain,$ignore_cache) = @_;
                   2127:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2128:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2129:     unless ($ignore_cache) {
                   2130:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2131:         if (defined($cached)) {
                   2132:             if (ref($result) eq 'HASH') {
                   2133:                 return %{$result};
                   2134:             }
1.943     raeburn  2135:         }
                   2136:     }
                   2137:     my %domdefaults;
                   2138:     my %domconfig =
1.989     raeburn  2139:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2140:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2141:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2142:                                   'requestauthor','selfenrollment',
1.1172.2.89  raeburn  2143:                                   'coursecategories','autoenroll',
                   2144:                                   'helpsettings'],$domain);
1.1172.2.41  raeburn  2145:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2146:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2147:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2148:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2149:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2150:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2151:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2152:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91  raeburn  2153:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2154:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2155:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2156:     } else {
                   2157:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2158:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2159:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2160:     }
1.976     raeburn  2161:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2162:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2163:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2164:         } else {
                   2165:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2166:         }
1.1172.2.6  raeburn  2167:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2168:         foreach my $item (@usertools) {
                   2169:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2170:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2171:             }
                   2172:         }
1.1172.2.29  raeburn  2173:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2174:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2175:         }
1.976     raeburn  2176:     }
1.985     raeburn  2177:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2178:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2179:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2180:         }
                   2181:     }
1.1172.2.9  raeburn  2182:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2183:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2184:     }
1.989     raeburn  2185:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2186:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2187:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2188:         }
                   2189:     }
1.1047    raeburn  2190:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2191:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2192:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2193:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2194:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2195:         }
1.1172.2.41  raeburn  2196:         foreach my $type (@coursetypes) {
                   2197:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2198:                 unless ($type eq 'community') {
                   2199:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2200:                 }
                   2201:             }
                   2202:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2203:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2204:             }
1.1172.2.60  raeburn  2205:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2206:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2207:                     $domdefaults{$type.'postsubtimeout'} =
                   2208:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2209:                 }
                   2210:             }
1.1172.2.30  raeburn  2211:         }
1.1172.2.67  raeburn  2212:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2213:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2214:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2215:                 if (@clonecodes) {
                   2216:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2217:                 }
                   2218:             }
                   2219:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2220:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2221:         }
1.1047    raeburn  2222:     }
1.1073    raeburn  2223:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2224:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2225:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2226:         }
                   2227:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2228:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2229:         }
1.1172.2.62  raeburn  2230:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2231:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2232:         }
1.1073    raeburn  2233:     }
1.1172.2.41  raeburn  2234:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2235:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2236:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2237:                             'approval','limit');
                   2238:             foreach my $type (@coursetypes) {
                   2239:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2240:                     my @mgrdc = ();
                   2241:                     foreach my $item (@settings) {
                   2242:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2243:                             push(@mgrdc,$item);
                   2244:                         }
                   2245:                     }
                   2246:                     if (@mgrdc) {
                   2247:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2248:                     }
                   2249:                 }
                   2250:             }
                   2251:         }
                   2252:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2253:             foreach my $type (@coursetypes) {
                   2254:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2255:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2256:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2257:                     }
                   2258:                 }
                   2259:             }
                   2260:         }
                   2261:     }
1.1172.2.46  raeburn  2262:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2263:         $domdefaults{'catauth'} = 'std';
                   2264:         $domdefaults{'catunauth'} = 'std';
                   2265:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2266:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2267:         }
                   2268:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2269:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2270:         }
                   2271:     }
1.1172.2.76  raeburn  2272:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2273:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2274:     }
1.1172.2.89  raeburn  2275:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2276:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2277:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2278:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2279:         }
                   2280:     }
1.1172.2.23  raeburn  2281:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2282:     return %domdefaults;
                   2283: }
                   2284: 
1.1172.2.93.4  2(raebur 2285:7): sub course_portal_url {
                   2286:7):     my ($cnum,$cdom) = @_;
                   2287:7):     my $chome = &homeserver($cnum,$cdom);
                   2288:7):     my $hostname = &hostname($chome);
                   2289:7):     my $protocol = $protocol{$chome};
                   2290:7):     $protocol = 'http' if ($protocol ne 'https');
                   2291:7):     my %domdefaults = &get_domain_defaults($cdom);
                   2292:7):     my $firsturl;
                   2293:7):     if ($domdefaults{'portal_def'}) {
                   2294:7):         $firsturl = $domdefaults{'portal_def'};
                   2295:7):     } else {
                   2296:7):         $firsturl = $protocol.'://'.$hostname;
                   2297:7):     }
                   2298:7):     return $firsturl;
                   2299:7): }
                   2300:7): 
1.344     www      2301: # --------------------------------------------------- Assign a key to a student
                   2302: 
                   2303: sub assign_access_key {
1.364     www      2304: #
                   2305: # a valid key looks like uname:udom#comments
                   2306: # comments are being appended
                   2307: #
1.498     www      2308:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2309:     $kdom=
1.620     albertel 2310:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2311:     $knum=
1.620     albertel 2312:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2313:     $cdom=
1.620     albertel 2314:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2315:     $cnum=
1.620     albertel 2316:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2317:     $udom=$env{'user.name'} unless (defined($udom));
                   2318:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2319:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2320:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2321:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2322:                                                   # assigned to this person
                   2323:                                                   # - this should not happen,
1.345     www      2324:                                                   # unless something went wrong
                   2325:                                                   # the first time around
                   2326: # ready to assign
1.364     www      2327:         $logentry=$1.'; '.$logentry;
1.496     www      2328:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2329:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2330: # key now belongs to user
1.346     www      2331: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2332:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2333:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2334:                 return 'ok';
                   2335:             } else {
                   2336:                 return 
                   2337:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2338: 	    }
                   2339:         } else {
                   2340:             return 'error: Could not assign key, try again later.';
                   2341:         }
1.364     www      2342:     } elsif (!$existing{$ckey}) {
1.345     www      2343: # the key does not exist
                   2344: 	return 'error: The key does not exist';
                   2345:     } else {
                   2346: # the key is somebody else's
                   2347: 	return 'error: The key is already in use';
                   2348:     }
1.344     www      2349: }
                   2350: 
1.364     www      2351: # ------------------------------------------ put an additional comment on a key
                   2352: 
                   2353: sub comment_access_key {
                   2354: #
                   2355: # a valid key looks like uname:udom#comments
                   2356: # comments are being appended
                   2357: #
                   2358:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2359:     $cdom=
1.620     albertel 2360:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2361:     $cnum=
1.620     albertel 2362:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2363:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2364:     if ($existing{$ckey}) {
                   2365:         $existing{$ckey}.='; '.$logentry;
                   2366: # ready to assign
1.367     www      2367:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2368:                                                  $cdom,$cnum) eq 'ok') {
                   2369: 	    return 'ok';
                   2370:         } else {
                   2371: 	    return 'error: Count not store comment.';
                   2372:         }
                   2373:     } else {
                   2374: # the key does not exist
                   2375: 	return 'error: The key does not exist';
                   2376:     }
                   2377: }
                   2378: 
1.344     www      2379: # ------------------------------------------------------ Generate a set of keys
                   2380: 
                   2381: sub generate_access_keys {
1.364     www      2382:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2383:     $cdom=
1.620     albertel 2384:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2385:     $cnum=
1.620     albertel 2386:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2387:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2388:     unless (($cdom) && ($cnum)) { return 0; }
                   2389:     if ($number>10000) { return 0; }
                   2390:     sleep(2); # make sure don't get same seed twice
                   2391:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2392:     my $total=0;
                   2393:     for (my $i=1;$i<=$number;$i++) {
                   2394:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2395:                   sprintf("%lx",int(100000*rand)).'-'.
                   2396:                   sprintf("%lx",int(100000*rand));
                   2397:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2398:        $newkey=~s/0/h/g; # and also 0 and O
                   2399:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2400:        if ($existing{$newkey}) {
                   2401:            $i--;
                   2402:        } else {
1.364     www      2403: 	  if (&put('accesskeys',
                   2404:               { $newkey => '# generated '.localtime().
1.620     albertel 2405:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2406:                            '; '.$logentry },
                   2407: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2408:               $total++;
                   2409: 	  }
                   2410:        }
                   2411:     }
1.620     albertel 2412:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2413:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2414:     return $total;
                   2415: }
                   2416: 
                   2417: # ------------------------------------------------------- Validate an accesskey
                   2418: 
                   2419: sub validate_access_key {
                   2420:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2421:     $cdom=
1.620     albertel 2422:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2423:     $cnum=
1.620     albertel 2424:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2425:     $udom=$env{'user.domain'} unless (defined($udom));
                   2426:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2427:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2428:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2429: }
                   2430: 
                   2431: # ------------------------------------- Find the section of student in a course
1.652     albertel 2432: sub devalidate_getsection_cache {
                   2433:     my ($udom,$unam,$courseid)=@_;
                   2434:     my $hashid="$udom:$unam:$courseid";
                   2435:     &devalidate_cache_new('getsection',$hashid);
                   2436: }
1.298     matthew  2437: 
1.815     albertel 2438: sub courseid_to_courseurl {
                   2439:     my ($courseid) = @_;
                   2440:     #already url style courseid
                   2441:     return $courseid if ($courseid =~ m{^/});
                   2442: 
                   2443:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2444: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2445: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2446: 	return "/$cdom/$cnum";
                   2447:     }
                   2448: 
                   2449:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2450:     if (exists($courseinfo{'num'})) {
                   2451: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2452:     }
                   2453: 
                   2454:     return undef;
                   2455: }
                   2456: 
1.298     matthew  2457: sub getsection {
                   2458:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2459:     my $cachetime=1800;
1.551     albertel 2460: 
                   2461:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2462:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2463:     if (defined($cached)) { return $result; }
                   2464: 
1.298     matthew  2465:     my %Pending; 
                   2466:     my %Expired;
                   2467:     #
                   2468:     # Each role can either have not started yet (pending), be active, 
                   2469:     #    or have expired.
                   2470:     #
                   2471:     # If there is an active role, we are done.
                   2472:     #
                   2473:     # If there is more than one role which has not started yet, 
                   2474:     #     choose the one which will start sooner
                   2475:     # If there is one role which has not started yet, return it.
                   2476:     #
                   2477:     # If there is more than one expired role, choose the one which ended last.
                   2478:     # If there is a role which has expired, return it.
                   2479:     #
1.815     albertel 2480:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2481:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2482:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2483:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2484:         my $section=$1;
                   2485:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2486:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2487:         my $now=time;
1.548     albertel 2488:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2489:             $Expired{$end}=$section;
                   2490:             next;
                   2491:         }
1.548     albertel 2492:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2493:             $Pending{$start}=$section;
                   2494:             next;
                   2495:         }
1.599     albertel 2496:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2497:     }
                   2498:     #
                   2499:     # Presumedly there will be few matching roles from the above
                   2500:     # loop and the sorting time will be negligible.
                   2501:     if (scalar(keys(%Pending))) {
                   2502:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2503:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2504:     } 
                   2505:     if (scalar(keys(%Expired))) {
                   2506:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2507:         my $time = pop(@sorted);
1.599     albertel 2508:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2509:     }
1.599     albertel 2510:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2511: }
1.70      www      2512: 
1.599     albertel 2513: sub save_cache {
                   2514:     &purge_remembered();
1.722     albertel 2515:     #&Apache::loncommon::validate_page();
1.620     albertel 2516:     undef(%env);
1.780     albertel 2517:     undef($env_loaded);
1.599     albertel 2518: }
1.452     albertel 2519: 
1.599     albertel 2520: my $to_remember=-1;
                   2521: my %remembered;
                   2522: my %accessed;
                   2523: my $kicks=0;
                   2524: my $hits=0;
1.849     albertel 2525: sub make_key {
                   2526:     my ($name,$id) = @_;
1.872     albertel 2527:     if (length($id) > 65 
                   2528: 	&& length(&escape($id)) > 200) {
                   2529: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2530:     }
1.849     albertel 2531:     return &escape($name.':'.$id);
                   2532: }
                   2533: 
1.599     albertel 2534: sub devalidate_cache_new {
                   2535:     my ($name,$id,$debug) = @_;
                   2536:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  2537:     my $remembered_id=$name.':'.$id;
1.849     albertel 2538:     $id=&make_key($name,$id);
1.599     albertel 2539:     $memcache->delete($id);
1.1172.2.81  raeburn  2540:     delete($remembered{$remembered_id});
                   2541:     delete($accessed{$remembered_id});
1.599     albertel 2542: }
                   2543: 
                   2544: sub is_cached_new {
                   2545:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  2546:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   2547:                                      # keys in %remembered hash, which persists for
                   2548:                                      # duration of request (no restriction on key length).
                   2549:     if (exists($remembered{$remembered_id})) {
                   2550: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2551: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2552: 	$hits++;
1.1172.2.81  raeburn  2553: 	return ($remembered{$remembered_id},1);
1.599     albertel 2554:     }
1.1172.2.81  raeburn  2555:     $id=&make_key($name,$id);
1.599     albertel 2556:     my $value = $memcache->get($id);
                   2557:     if (!(defined($value))) {
                   2558: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2559: 	return (undef,undef);
1.416     albertel 2560:     }
1.599     albertel 2561:     if ($value eq '__undef__') {
                   2562: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2563: 	$value=undef;
                   2564:     }
1.1172.2.81  raeburn  2565:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2566:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2567:     return ($value,1);
                   2568: }
                   2569: 
                   2570: sub do_cache_new {
                   2571:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  2572:     my $remembered_id=$name.':'.$id;
1.849     albertel 2573:     $id=&make_key($name,$id);
1.599     albertel 2574:     my $setvalue=$value;
                   2575:     if (!defined($setvalue)) {
                   2576: 	$setvalue='__undef__';
                   2577:     }
1.623     albertel 2578:     if (!defined($time) ) {
                   2579: 	$time=600;
                   2580:     }
1.599     albertel 2581:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2582:     my $result = $memcache->set($id,$setvalue,$time);
                   2583:     if (! $result) {
1.872     albertel 2584: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2585: 	$memcache->disconnect_all();
1.872     albertel 2586:     }
1.600     albertel 2587:     # need to make a copy of $value
1.1172.2.81  raeburn  2588:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2589:     return $value;
                   2590: }
                   2591: 
                   2592: sub make_room {
1.1172.2.81  raeburn  2593:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2594: 
1.1172.2.81  raeburn  2595:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2596:                                     : $value;
1.599     albertel 2597:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  2598:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2599:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2600:     my $to_kick;
                   2601:     my $max_time=0;
                   2602:     foreach my $other (keys(%accessed)) {
                   2603: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2604: 	    $to_kick=$other;
                   2605: 	    $max_time=&tv_interval($accessed{$other});
                   2606: 	}
                   2607:     }
                   2608:     delete($remembered{$to_kick});
                   2609:     delete($accessed{$to_kick});
                   2610:     $kicks++;
                   2611:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2612:     return;
                   2613: }
                   2614: 
1.599     albertel 2615: sub purge_remembered {
1.604     albertel 2616:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2617:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2618:     undef(%remembered);
                   2619:     undef(%accessed);
1.428     albertel 2620: }
1.70      www      2621: # ------------------------------------- Read an entry from a user's environment
                   2622: 
                   2623: sub userenvironment {
                   2624:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2625:     my $items;
                   2626:     foreach my $item (@what) {
                   2627:         $items.=&escape($item).'&';
                   2628:     }
                   2629:     $items=~s/\&$//;
1.70      www      2630:     my %returnhash=();
1.1009    raeburn  2631:     my $uhome = &homeserver($unam,$udom);
                   2632:     unless ($uhome eq 'no_host') {
                   2633:         my @answer=split(/\&/, 
                   2634:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2635:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2636:             return %returnhash;
                   2637:         }
1.1009    raeburn  2638:         my $i;
                   2639:         for ($i=0;$i<=$#what;$i++) {
                   2640: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2641:         }
1.70      www      2642:     }
                   2643:     return %returnhash;
1.1       albertel 2644: }
                   2645: 
1.617     albertel 2646: # ---------------------------------------------------------- Get a studentphoto
                   2647: sub studentphoto {
                   2648:     my ($udom,$unam,$ext) = @_;
                   2649:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2650:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2651:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2652:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2653:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2654:             } else {
                   2655:                 my ($result,$perm_reqd)=
1.707     albertel 2656: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2657:                 if ($result eq 'ok') {
                   2658:                     if (!($perm_reqd eq 'yes')) {
                   2659:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2660:                     }
                   2661:                 }
                   2662:             }
                   2663:         }
                   2664:     } else {
                   2665:         my ($result,$perm_reqd) = 
1.707     albertel 2666: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2667:         if ($result eq 'ok') {
                   2668:             if (!($perm_reqd eq 'yes')) {
                   2669:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2670:             }
                   2671:         }
                   2672:     }
                   2673:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2674: }
                   2675: 
                   2676: sub retrievestudentphoto {
                   2677:     my ($udom,$unam,$ext,$type) = @_;
                   2678:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2679:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2680:     if ($ret eq 'ok') {
                   2681:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2682:         if ($type eq 'thumbnail') {
                   2683:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2684:         }
                   2685:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2686:         return $tokenurl;
                   2687:     } else {
                   2688:         if ($type eq 'thumbnail') {
                   2689:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2690:         } else { 
                   2691:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2692:         }
1.617     albertel 2693:     }
                   2694: }
                   2695: 
1.263     www      2696: # -------------------------------------------------------------------- New chat
                   2697: 
                   2698: sub chatsend {
1.724     raeburn  2699:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2700:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2701:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2702:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2703:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2704: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2705: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2706: }
                   2707: 
                   2708: # ------------------------------------------ Find current version of a resource
                   2709: 
                   2710: sub getversion {
                   2711:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2712:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2713:     return &currentversion(&filelocation('',$fname));
                   2714: }
                   2715: 
                   2716: sub currentversion {
                   2717:     my $fname=shift;
                   2718:     my $author=$fname;
                   2719:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2720:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2721:     my $home=&homeserver($uname,$udom);
1.292     www      2722:     if ($home eq 'no_host') { 
                   2723:         return -1; 
                   2724:     }
1.1112    www      2725:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2726:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2727: 	return -1;
                   2728:     }
1.1112    www      2729:     return $answer;
1.263     www      2730: }
                   2731: 
1.1111    www      2732: #
                   2733: # Return special version number of resource if set by override, empty otherwise
                   2734: #
                   2735: sub usedversion {
                   2736:     my $fname=shift;
                   2737:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2738:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2739:     if ($urlversion) { return $urlversion; }
                   2740:     return '';
                   2741: }
                   2742: 
1.1       albertel 2743: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2744: 
1.1       albertel 2745: sub subscribe {
                   2746:     my $fname=shift;
1.761     raeburn  2747:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2748:     $fname=~s/[\n\r]//g;
1.1       albertel 2749:     my $author=$fname;
                   2750:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2751:     my ($udom,$uname)=split(/\//,$author);
                   2752:     my $home=homeserver($uname,$udom);
1.335     albertel 2753:     if ($home eq 'no_host') {
                   2754:         return 'not_found';
1.1       albertel 2755:     }
                   2756:     my $answer=reply("sub:$fname",$home);
1.64      www      2757:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2758: 	$answer.=' by '.$home;
                   2759:     }
1.1       albertel 2760:     return $answer;
                   2761: }
                   2762:     
1.8       www      2763: # -------------------------------------------------------------- Replicate file
                   2764: 
                   2765: sub repcopy {
                   2766:     my $filename=shift;
1.23      www      2767:     $filename=~s/\/+/\//g;
1.1142    raeburn  2768:     my $londocroot = $perlvar{'lonDocRoot'};
                   2769:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2770:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2771:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2772: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2773: 	return &repcopy_userfile($filename);
                   2774:     }
1.532     albertel 2775:     $filename=~s/[\n\r]//g;
1.8       www      2776:     my $transname="$filename.in.transfer";
1.828     www      2777: # FIXME: this should flock
1.607     raeburn  2778:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2779:     my $remoteurl=subscribe($filename);
1.64      www      2780:     if ($remoteurl =~ /^con_lost by/) {
                   2781: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2782:            return 'unavailable';
1.8       www      2783:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2784: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2785: 	   return 'not_found';
1.64      www      2786:     } elsif ($remoteurl =~ /^rejected by/) {
                   2787: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2788:            return 'forbidden';
1.20      www      2789:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2790:            return 'ok';
1.8       www      2791:     } else {
1.290     www      2792:         my $author=$filename;
                   2793:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2794:         my ($udom,$uname)=split(/\//,$author);
                   2795:         my $home=homeserver($uname,$udom);
                   2796:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2797:            my @parts=split(/\//,$filename);
                   2798:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2799:            if ($path ne "$londocroot/res") {
1.8       www      2800:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2801: 	       return 'bad_request';
1.8       www      2802:            }
                   2803:            my $count;
                   2804:            for ($count=5;$count<$#parts;$count++) {
                   2805:                $path.="/$parts[$count]";
                   2806:                if ((-e $path)!=1) {
                   2807: 		   mkdir($path,0777);
                   2808:                }
                   2809:            }
                   2810:            my $ua=new LWP::UserAgent;
                   2811:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2812:            my $response=$ua->request($request,$transname);
                   2813:            if ($response->is_error()) {
                   2814: 	       unlink($transname);
                   2815:                my $message=$response->status_line;
1.672     albertel 2816:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2817:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2818:                return 'unavailable';
1.8       www      2819:            } else {
1.16      www      2820: 	       if ($remoteurl!~/\.meta$/) {
                   2821:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2822:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2823:                   if ($mresponse->is_error()) {
                   2824: 		      unlink($filename.'.meta');
                   2825:                       &logthis(
1.672     albertel 2826:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2827:                   }
                   2828: 	       }
1.8       www      2829:                rename($transname,$filename);
1.607     raeburn  2830:                return 'ok';
1.8       www      2831:            }
1.290     www      2832:        }
1.8       www      2833:     }
1.330     www      2834: }
                   2835: 
                   2836: # ------------------------------------------------ Get server side include body
                   2837: sub ssi_body {
1.381     albertel 2838:     my ($filelink,%form)=@_;
1.606     matthew  2839:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2840:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2841:     }
1.953     www      2842:     my $output='';
                   2843:     my $response;
1.980     raeburn  2844:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2845:        ($output,$response)=&externalssi($filelink);
1.953     www      2846:     } else {
1.1004    droeschl 2847:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2848:        $filelink .= 'inhibitmenu=yes';
1.953     www      2849:        ($output,$response)=&ssi($filelink,%form);
                   2850:     }
1.778     albertel 2851:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2852:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2853:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2854:     if (wantarray) {
                   2855:         return ($output, $response);
                   2856:     } else {
                   2857:         return $output;
                   2858:     }
1.8       www      2859: }
                   2860: 
1.15      www      2861: # --------------------------------------------------------- Server Side Include
                   2862: 
1.782     albertel 2863: sub absolute_url {
                   2864:     my ($host_name) = @_;
                   2865:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2866:     if ($host_name eq '') {
                   2867: 	$host_name = $ENV{'SERVER_NAME'};
                   2868:     }
                   2869:     return $protocol.$host_name;
                   2870: }
                   2871: 
1.942     foxr     2872: #
                   2873: #   Server side include.
                   2874: # Parameters:
                   2875: #  fn     Possibly encrypted resource name/id.
                   2876: #  form   Hash that describes how the rendering should be done
                   2877: #         and other things.
1.944     foxr     2878: # Returns:
1.950     raeburn  2879: #   Scalar context: The content of the response.
                   2880: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2881: #     
1.15      www      2882: sub ssi {
                   2883: 
1.944     foxr     2884:     my ($fn,%form)=@_;
1.15      www      2885:     my $ua=new LWP::UserAgent;
1.23      www      2886:     my $request;
1.711     albertel 2887: 
                   2888:     $form{'no_update_last_known'}=1;
1.895     albertel 2889:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2890:     if (%form) {
1.782     albertel 2891:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58  raeburn  2892:       $request->content(join('&',map {
                   2893:             my $name = escape($_);
                   2894:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   2895:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   2896:             : &escape($form{$_}) );
                   2897:         } keys(%form)));
1.23      www      2898:     } else {
1.782     albertel 2899:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2900:     }
                   2901: 
1.15      www      2902:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2  raeburn  2903:     my $response= $ua->request($request);
1.944     foxr     2904:     if (wantarray) {
1.1172.2.3  raeburn  2905: 	return ($response->content, $response);
1.944     foxr     2906:     } else {
1.1172.2.3  raeburn  2907: 	return $response->content;
1.942     foxr     2908:     }
1.324     www      2909: }
                   2910: 
                   2911: sub externalssi {
                   2912:     my ($url)=@_;
                   2913:     my $ua=new LWP::UserAgent;
                   2914:     my $request=new HTTP::Request('GET',$url);
                   2915:     my $response=$ua->request($request);
1.954     raeburn  2916:     if (wantarray) {
                   2917:         return ($response->content, $response);
                   2918:     } else {
                   2919:         return $response->content;
                   2920:     }
1.15      www      2921: }
1.254     www      2922: 
1.492     albertel 2923: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2924: 
                   2925: sub allowuploaded {
                   2926:     my ($srcurl,$url)=@_;
                   2927:     $url=&clutter(&declutter($url));
                   2928:     my $dir=$url;
                   2929:     $dir=~s/\/[^\/]+$//;
                   2930:     my %httpref=();
                   2931:     my $httpurl=&hreflocation('',$url);
                   2932:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2933:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2934: }
1.477     raeburn  2935: 
1.1172.2.13  raeburn  2936: #
                   2937: # Determine if the current user should be able to edit a particular resource,
                   2938: # when viewing in course context.
                   2939: # (a) When viewing resource used to determine if "Edit" item is included in
                   2940: #     Functions.
                   2941: # (b) When displaying folder contents in course editor, used to determine if
                   2942: #     "Edit" link will be displayed alongside resource.
                   2943: #
                   2944: #  input: six args -- filename (decluttered), course number, course domain,
                   2945: #                   url, symb (if registered) and group (if this is a group
                   2946: #                   item -- e.g., bulletin board, group page etc.).
                   2947: #  output: array of five scalars --
                   2948: #          $cfile -- url for file editing if editable on current server
                   2949: #          $home -- homeserver of resource (i.e., for author if published,
                   2950: #                                           or course if uploaded.).
                   2951: #          $switchserver --  1 if server switch will be needed.
                   2952: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   2953: #          $forceview -- 1 if icon/link should be to go to view mode
                   2954: #
                   2955: 
                   2956: sub can_edit_resource {
                   2957:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   2958:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   2959: #
                   2960: # For aboutme pages user can only edit his/her own.
                   2961: #
                   2962:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   2963:         my ($sdom,$sname) = ($1,$2);
                   2964:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   2965:             $home = $env{'user.home'};
                   2966:             $cfile = $resurl;
                   2967:             if ($env{'form.forceedit'}) {
                   2968:                 $forceview = 1;
                   2969:             } else {
                   2970:                 $forceedit = 1;
                   2971:             }
                   2972:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2973:         } else {
                   2974:             return;
                   2975:         }
                   2976:     }
                   2977: 
                   2978:     if ($env{'request.course.id'}) {
                   2979:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   2980:         if ($group ne '') {
                   2981: # if this is a group homepage or group bulletin board, check group privs
                   2982:             my $allowed = 0;
                   2983:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   2984:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   2985:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2986:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2987:                     $allowed = 1;
                   2988:                 }
                   2989:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   2990:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2991:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2992:                     $allowed = 1;
                   2993:                 }
                   2994:             }
                   2995:             if ($allowed) {
                   2996:                 $home=&homeserver($cnum,$cdom);
                   2997:                 if ($env{'form.forceedit'}) {
                   2998:                     $forceview = 1;
                   2999:                 } else {
                   3000:                     $forceedit = 1;
                   3001:                 }
                   3002:                 $cfile = $resurl;
                   3003:             } else {
                   3004:                 return;
                   3005:             }
                   3006:         } else {
1.1172.2.15  raeburn  3007:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3008:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3009:                     return;
                   3010:                 }
                   3011:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  3012: #
                   3013: # No edit allowed where CC has switched to student role.
                   3014: #
                   3015:                 return;
                   3016:             }
                   3017:         }
                   3018:     }
                   3019: 
                   3020:     if ($file ne '') {
                   3021:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   3022:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3023:                 $uploaded = 1;
                   3024:                 $incourse = 1;
                   3025:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3026:                     $cfile = &hreflocation('',$file);
                   3027:                     if ($env{'form.forceedit'}) {
                   3028:                         $forceview = 1;
                   3029:                     } else {
                   3030:                         $forceedit = 1;
                   3031:                     }
                   3032:                 }
                   3033:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3034:                 $incourse = 1;
                   3035:                 if ($env{'form.forceedit'}) {
                   3036:                     $forceview = 1;
                   3037:                 } else {
                   3038:                     $forceedit = 1;
                   3039:                 }
                   3040:                 $cfile = $resurl;
                   3041:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3042:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3043:                     $incourse = 1;
                   3044:                     if ($env{'form.forceedit'}) {
                   3045:                         $forceview = 1;
                   3046:                     } else {
                   3047:                         $forceedit = 1;
                   3048:                     }
                   3049:                     $cfile = $resurl;
                   3050:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3051:                     $incourse = 1;
                   3052:                     $cfile = $resurl.'/smpedit';
                   3053:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3054:                     $incourse = 1;
                   3055:                     if ($env{'form.forceedit'}) {
                   3056:                         $forceview = 1;
                   3057:                     } else {
                   3058:                         $forceedit = 1;
                   3059:                     }
                   3060:                     $cfile = $resurl;
1.1172.2.93.4  2(raebur 3061:7):                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3062:7):                     $incourse = 1;
                   3063:7):                     if ($env{'form.forceedit'}) {
                   3064:7):                         $forceview = 1;
                   3065:7):                     } else {
                   3066:7):                         $forceedit = 1;
                   3067:7):                     }
                   3068:7):                     $cfile = $resurl;
1.1172.2.15  raeburn  3069:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3070:                     $incourse = 1;
                   3071:                     if ($env{'form.forceedit'}) {
                   3072:                         $forceview = 1;
                   3073:                     } else {
                   3074:                         $forceedit = 1;
                   3075:                     }
                   3076:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3077:                 }
                   3078:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3079:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3080:                 if (&is_on_map($template)) {
                   3081:                     $incourse = 1;
                   3082:                     $forceview = 1;
                   3083:                     $cfile = $template;
                   3084:                 }
                   3085:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3086:                     $incourse = 1;
                   3087:                     if ($env{'form.forceedit'}) {
                   3088:                         $forceview = 1;
                   3089:                     } else {
                   3090:                         $forceedit = 1;
                   3091:                     }
                   3092:                     $cfile = $resurl;
1.1172.2.93.4  2(raebur 3093:7):             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3094:7):                 $incourse = 1;
                   3095:7):                 if ($env{'form.forceedit'}) {
                   3096:7):                     $forceview = 1;
                   3097:7):                 } else {
                   3098:7):                     $forceedit = 1;
                   3099:7):                 }
                   3100:7):                 $cfile = $resurl;
1.1172.2.13  raeburn  3101:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3102:                 $incourse = 1;
                   3103:                 $forceview = 1;
                   3104:                 if ($symb) {
                   3105:                     my ($map,$id,$res)=&decode_symb($symb);
                   3106:                     $env{'request.symb'} = $symb;
                   3107:                     $cfile = &clutter($res);
                   3108:                 } else {
                   3109:                     $cfile = $env{'form.suppurl'};
1.1172.2.93.4  1(raebur 3110:7):                     my $escfile = &unescape($cfile);
          2(raebur 3111:7):                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3112:7):                         $cfile = '/adm/wrapper'.$escfile;
                   3113:7):                     } else {
                   3114:7):                         $escfile =~ s{^http://}{};
                   3115:7):                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3116:7):                     }
1.1172.2.13  raeburn  3117:                 }
1.1172.2.31  raeburn  3118:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3119:                 if ($env{'form.forceedit'}) {
                   3120:                     $forceview = 1;
                   3121:                 } else {
                   3122:                     $forceedit = 1;
                   3123:                 }
                   3124:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3125:             }
                   3126:         }
                   3127:         if ($uploaded || $incourse) {
                   3128:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3129:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3130:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3131:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3132:             # Check that the user has permission to edit this resource
                   3133:             my $setpriv = 1;
                   3134:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3135:             if (defined($cfudom)) {
                   3136:                 $home=&homeserver($cfuname,$cfudom);
                   3137:                 $cfile=$file;
                   3138:             }
                   3139:         }
                   3140:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3141:             (($home ne '') && ($home ne 'no_host'))) {
                   3142:             my @ids=&current_machine_ids();
                   3143:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3144:                 $switchserver=1;
                   3145:             }
                   3146:         }
                   3147:     }
                   3148:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3149: }
                   3150: 
                   3151: sub is_course_upload {
                   3152:     my ($file,$cnum,$cdom) = @_;
                   3153:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3154:     $uploadpath =~ s{^\/}{};
                   3155:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3156:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3157:         return 1;
                   3158:     }
                   3159:     return;
                   3160: }
                   3161: 
                   3162: sub in_course {
                   3163:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3164:     if ($hideprivileged) {
                   3165:         my $skipuser;
1.1172.2.23  raeburn  3166:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3167:         my @possdoms = ($cdom);
                   3168:         if ($coursehash{'checkforpriv'}) {
                   3169:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3170:         }
                   3171:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3172:             $skipuser = 1;
                   3173:             if ($coursehash{'nothideprivileged'}) {
                   3174:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3175:                     my $user;
                   3176:                     if ($item =~ /:/) {
                   3177:                         $user = $item;
                   3178:                     } else {
                   3179:                         $user = join(':',split(/[\@]/,$item));
                   3180:                     }
                   3181:                     if ($user eq $uname.':'.$udom) {
                   3182:                         undef($skipuser);
                   3183:                         last;
                   3184:                     }
                   3185:                 }
                   3186:             }
                   3187:             if ($skipuser) {
                   3188:                 return 0;
                   3189:             }
                   3190:         }
                   3191:     }
                   3192:     $type ||= 'any';
                   3193:     if (!defined($cdom) || !defined($cnum)) {
                   3194:         my $cid  = $env{'request.course.id'};
                   3195:         $cdom = $env{'course.'.$cid.'.domain'};
                   3196:         $cnum = $env{'course.'.$cid.'.num'};
                   3197:     }
                   3198:     my $typesref;
                   3199:     if (($type eq 'any') || ($type eq 'all')) {
                   3200:         $typesref = ['active','previous','future'];
                   3201:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3202:         $typesref = [$type];
                   3203:     }
                   3204:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3205:                               $typesref,undef,[$cdom]);
                   3206:     my ($tmp) = keys(%roles);
                   3207:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3208:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3209:     if (@course_roles > 0) {
                   3210:         return 1;
                   3211:     }
                   3212:     return 0;
                   3213: }
                   3214: 
1.478     albertel 3215: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3216: # input: action, courseID, current domain, intended
1.637     raeburn  3217: #        path to file, source of file, instruction to parse file for objects,
                   3218: #        ref to hash for embedded objects,
                   3219: #        ref to hash for codebase of java objects.
1.1095    raeburn  3220: #        reference to scalar to accommodate mime type determined
                   3221: #          from File::MMagic if $parser = parse.
1.637     raeburn  3222: #
1.485     raeburn  3223: # output: url to file (if action was uploaddoc), 
                   3224: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3225: #
1.478     albertel 3226: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3227: # course.
1.477     raeburn  3228: #
1.478     albertel 3229: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3230: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3231: #          course's home server.
1.477     raeburn  3232: #
1.478     albertel 3233: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3234: #          be copied from $source (current location) to 
                   3235: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3236: #         and will then be copied to
                   3237: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3238: #         course's home server.
1.485     raeburn  3239: #
1.481     raeburn  3240: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3241: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3242: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3243: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3244: #         in course's home server.
1.637     raeburn  3245: #
1.477     raeburn  3246: 
                   3247: sub process_coursefile {
1.1095    raeburn  3248:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3249:         $mimetype)=@_;
1.477     raeburn  3250:     my $fetchresult;
1.638     albertel 3251:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3252:     if ($action eq 'propagate') {
1.638     albertel 3253:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3254: 			     $home);
1.481     raeburn  3255:     } else {
1.477     raeburn  3256:         my $fpath = '';
                   3257:         my $fname = $file;
1.478     albertel 3258:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3259:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3260:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3261:         if ($action eq 'copy') {
                   3262:             if ($source eq '') {
                   3263:                 $fetchresult = 'no source file';
                   3264:                 return $fetchresult;
                   3265:             } else {
                   3266:                 my $destination = $filepath.'/'.$fname;
                   3267:                 rename($source,$destination);
                   3268:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3269:                                  $home);
1.481     raeburn  3270:             }
                   3271:         } elsif ($action eq 'uploaddoc') {
1.1172.2.93.4  7(raebur 3272:7):             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3273:             print $fh $env{'form.'.$source};
1.481     raeburn  3274:             close($fh);
1.637     raeburn  3275:             if ($parser eq 'parse') {
1.1024    raeburn  3276:                 my $mm = new File::MMagic;
1.1095    raeburn  3277:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3278:                 if ($type eq 'text/html') {
1.1024    raeburn  3279:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3280:                     unless ($parse_result eq 'ok') {
                   3281:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3282:                     }
1.637     raeburn  3283:                 }
1.1095    raeburn  3284:                 if (ref($mimetype)) {
                   3285:                     $$mimetype = $type;
                   3286:                 } 
1.637     raeburn  3287:             }
1.477     raeburn  3288:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3289:                                  $home);
1.481     raeburn  3290:             if ($fetchresult eq 'ok') {
                   3291:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3292:             } else {
                   3293:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3294:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3295:                 return '/adm/notfound.html';
                   3296:             }
1.477     raeburn  3297:         }
                   3298:     }
1.485     raeburn  3299:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3300:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3301:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3302:     }
                   3303:     return $fetchresult;
                   3304: }
                   3305: 
1.637     raeburn  3306: sub build_filepath {
                   3307:     my ($fpath) = @_;
                   3308:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3309:     unless ($fpath eq '') {
                   3310:         my @parts=split('/',$fpath);
                   3311:         foreach my $part (@parts) {
                   3312:             $filepath.= '/'.$part;
                   3313:             if ((-e $filepath)!=1) {
                   3314:                 mkdir($filepath,0777);
                   3315:             }
                   3316:         }
                   3317:     }
                   3318:     return $filepath;
                   3319: }
                   3320: 
                   3321: sub store_edited_file {
1.638     albertel 3322:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3323:     my $file = $primary_url;
                   3324:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3325:     my $fpath = '';
                   3326:     my $fname = $file;
                   3327:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3328:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3329:     my $filepath = &build_filepath($fpath);
1.1172.2.93.4  7(raebur 3330:7):     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3331:     print $fh $content;
                   3332:     close($fh);
1.638     albertel 3333:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3334:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3335: 			  $home);
1.637     raeburn  3336:     if ($$fetchresult eq 'ok') {
                   3337:         return '/uploaded/'.$fpath.'/'.$fname;
                   3338:     } else {
1.638     albertel 3339:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3340: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3341:         return '/adm/notfound.html';
                   3342:     }
                   3343: }
                   3344: 
1.531     albertel 3345: sub clean_filename {
1.831     albertel 3346:     my ($fname,$args)=@_;
1.315     www      3347: # Replace Windows backslashes by forward slashes
1.257     www      3348:     $fname=~s/\\/\//g;
1.831     albertel 3349:     if (!$args->{'keep_path'}) {
                   3350:         # Get rid of everything but the actual filename
                   3351: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3352:     }
1.315     www      3353: # Replace spaces by underscores
                   3354:     $fname=~s/\s+/\_/g;
                   3355: # Replace all other weird characters by nothing
1.831     albertel 3356:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3357: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3358: # numbers
                   3359:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3360:     return $fname;
                   3361: }
1.1051    raeburn  3362: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3363: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3364: # image with the same aspect ratio as the original, but with dimensions which do 
                   3365: # not exceed $resizewidth and $resizeheight.
                   3366:  
1.984     neumanie 3367: sub resizeImage {
1.1051    raeburn  3368:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3369:     my $ima = Image::Magick->new;
                   3370:     my $resized;
                   3371:     if (-e $img_path) {
                   3372:         $ima->Read($img_path);
                   3373:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3374:             my $width = $ima->Get('width');
                   3375:             my $height = $ima->Get('height');
                   3376:             if ($width > $resizewidth) {
                   3377: 	        my $factor = $width/$resizewidth;
                   3378:                 my $newheight = $height/$factor;
                   3379:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3380:                 $resized = 1;
                   3381:             }
                   3382:         }
                   3383:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3384:             my $width = $ima->Get('width');
                   3385:             my $height = $ima->Get('height');
                   3386:             if ($height > $resizeheight) {
                   3387:                 my $factor = $height/$resizeheight;
                   3388:                 my $newwidth = $width/$factor;
                   3389:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3390:                 $resized = 1;
                   3391:             }
                   3392:         }
                   3393:         if ($resized) {
                   3394:             $ima->Write($img_path);
                   3395:         }
                   3396:     }
                   3397:     return;
1.977     amueller 3398: }
                   3399: 
1.608     albertel 3400: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3401: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3402: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3403: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3404: #                                    canceloverwrite, or ''. 
                   3405: #                   if 'coursedoc': upload to the current course
                   3406: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3407: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3408: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3409: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3410: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3411: #        $allfiles - reference to hash for embedded objects
                   3412: #        $codebase - reference to hash for codebase of java objects
                   3413: #        $desuname - username for permanent storage of uploaded file
                   3414: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3415: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3416: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3417: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3418: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3419: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3420: #                    from File::MMagic.
1.858     raeburn  3421: # 
1.686     albertel 3422: # output: url of file in userspace, or error: <message> 
                   3423: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3424: 
1.531     albertel 3425: sub userfileupload {
1.1090    raeburn  3426:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3427:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3428:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3429:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3430:     $fname=&clean_filename($fname);
1.1090    raeburn  3431:     # See if there is anything left
1.257     www      3432:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3433:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3434:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3435:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3436:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3437:         my $now = time;
1.1090    raeburn  3438:         my $filepath;
1.1095    raeburn  3439:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3440:              $filepath = 'tmp/helprequests/'.$now;
                   3441:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3442:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3443:                          '_'.$env{'user.domain'}.'/pending';
                   3444:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3445:             my ($docuname,$docudom);
1.1172.2.93.4  5(raebur 3446:7):             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3447:                 $docudom = $destudom;
                   3448:             } else {
                   3449:                 $docudom = $env{'user.domain'};
                   3450:             }
1.1172.2.93.4  5(raebur 3451:7):             if ($destuname =~ /^$match_username$/) {
1.1090    raeburn  3452:                 $docuname = $destuname;
                   3453:             } else {
                   3454:                 $docuname = $env{'user.name'};
                   3455:             }
                   3456:             if (exists($env{'form.group'})) {
                   3457:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3458:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3459:             }
                   3460:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3461:             if ($context eq 'canceloverwrite') {
                   3462:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3463:                 if (-e  $tempfile) {
                   3464:                     my @info = stat($tempfile);
                   3465:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3466:                         unlink($tempfile);
                   3467:                     }
                   3468:                 }
                   3469:                 return;
1.523     raeburn  3470:             }
                   3471:         }
1.1090    raeburn  3472:         # Create the directory if not present
1.741     raeburn  3473:         my @parts=split(/\//,$filepath);
                   3474:         my $fullpath = $perlvar{'lonDaemons'};
                   3475:         for (my $i=0;$i<@parts;$i++) {
                   3476:             $fullpath .= '/'.$parts[$i];
                   3477:             if ((-e $fullpath)!=1) {
                   3478:                 mkdir($fullpath,0777);
                   3479:             }
                   3480:         }
1.1172.2.93.4  7(raebur 3481:7):         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3482:         print $fh $env{'form.'.$formname};
                   3483:         close($fh);
1.1090    raeburn  3484:         if ($context eq 'existingfile') {
                   3485:             my @info = stat($fullpath.'/'.$fname);
                   3486:             return ($fullpath.'/'.$fname,$info[9]);
                   3487:         } else {
                   3488:             return $fullpath.'/'.$fname;
                   3489:         }
1.523     raeburn  3490:     }
1.995     raeburn  3491:     if ($subdir eq 'scantron') {
                   3492:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3493:     } else {
1.995     raeburn  3494:         $fname="$subdir/$fname";
                   3495:     }
1.1090    raeburn  3496:     if ($context eq 'coursedoc') {
1.638     albertel 3497: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3498: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3499:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3500:             return &finishuserfileupload($docuname,$docudom,
                   3501: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3502: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3503:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3504:         } else {
1.1172.2.21  raeburn  3505:             if ($env{'form.folder'}) {
                   3506:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3507:             }
1.638     albertel 3508:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3509: 				       $fname,$formname,$parser,
1.1095    raeburn  3510: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3511:         }
1.719     banghart 3512:     } elsif (defined($destuname)) {
                   3513:         my $docuname=$destuname;
                   3514:         my $docudom=$destudom;
1.860     raeburn  3515: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3516: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3517:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3518:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3519:     } else {
1.638     albertel 3520:         my $docuname=$env{'user.name'};
                   3521:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3522:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3523:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3524:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3525:         }
1.860     raeburn  3526: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3527: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3528:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3529:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3530:     }
1.271     www      3531: }
                   3532: 
                   3533: sub finishuserfileupload {
1.860     raeburn  3534:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3535:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3536:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3537:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3538:   
1.860     raeburn  3539:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3540:     $file=$fname;
                   3541:     if ($fname=~m|/|) {
                   3542:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3543: 	$path.=$fnamepath.'/';
                   3544:     }
1.259     www      3545:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3546:     my $count;
                   3547:     for ($count=4;$count<=$#parts;$count++) {
                   3548:         $filepath.="/$parts[$count]";
                   3549:         if ((-e $filepath)!=1) {
                   3550: 	    mkdir($filepath,0777);
                   3551:         }
                   3552:     }
1.984     neumanie 3553: 
1.258     www      3554: # Save the file
                   3555:     {
1.1172.2.93.4  7(raebur 3556:7): 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 3557: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3558: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3559: 	    return '/adm/notfound.html';
                   3560: 	}
1.1090    raeburn  3561:         if ($context eq 'overwrite') {
1.1117    foxr     3562:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3563:             my $target = $filepath.'/'.$file;
                   3564:             if (-e $source) {
                   3565:                 my @info = stat($source);
                   3566:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3567:                     unless (&File::Copy::move($source,$target)) {
                   3568:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3569:                         return "Moving from $source failed";
                   3570:                     }
                   3571:                 } else {
                   3572:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3573:                 }
                   3574:             } else {
                   3575:                 return "Temporary file: $source missing";
                   3576:             }
                   3577:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3578: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3579: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3580: 	    return '/adm/notfound.html';
                   3581: 	}
1.570     albertel 3582: 	close(FH);
1.1051    raeburn  3583:         if ($resizewidth && $resizeheight) {
                   3584:             my $mm = new File::MMagic;
                   3585:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3586:             if ($mime_type =~ m{^image/}) {
                   3587: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3588:             }  
1.977     amueller 3589: 	}
1.258     www      3590:     }
1.1152    raeburn  3591:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3592:         if (ref($mimetype)) {
                   3593:             if ($$mimetype eq '') {
                   3594:                 my $mm = new File::MMagic;
                   3595:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3596:                 $$mimetype = $type;
                   3597:             }
                   3598:         }
                   3599:     }
1.637     raeburn  3600:     if ($parser eq 'parse') {
1.1152    raeburn  3601:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3602:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3603:                                                        $allfiles,$codebase);
                   3604:             unless ($parse_result eq 'ok') {
                   3605:                 &logthis('Failed to parse '.$filepath.$file.
                   3606: 	   	         ' for embedded media: '.$parse_result); 
                   3607:             }
1.637     raeburn  3608:         }
                   3609:     }
1.860     raeburn  3610:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3611:         my $input = $filepath.'/'.$file;
                   3612:         my $output = $filepath.'/'.'tn-'.$file;
                   3613:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.93.4  7(raebur 3614:7):         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   3615:7):         system({$args[0]} @args);
1.860     raeburn  3616:         if (-e $filepath.'/'.'tn-'.$file) {
                   3617:             $fetchthumb  = 1; 
                   3618:         }
                   3619:     }
1.858     raeburn  3620:  
1.259     www      3621: # Notify homeserver to grep it
                   3622: #
1.984     neumanie 3623:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3624:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3625:     if ($fetchresult eq 'ok') {
1.860     raeburn  3626:         if ($fetchthumb) {
                   3627:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3628:             if ($thumbresult ne 'ok') {
                   3629:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3630:                          $docuhome.': '.$thumbresult);
                   3631:             }
                   3632:         }
1.259     www      3633: #
1.258     www      3634: # Return the URL to it
1.494     albertel 3635:         return '/uploaded/'.$path.$file;
1.263     www      3636:     } else {
1.494     albertel 3637:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3638: 		 ': '.$fetchresult);
1.263     www      3639:         return '/adm/notfound.html';
1.858     raeburn  3640:     }
1.493     albertel 3641: }
                   3642: 
1.637     raeburn  3643: sub extract_embedded_items {
1.961     raeburn  3644:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3645:     my @state = ();
1.1164    raeburn  3646:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3647:     my %javafiles = (
                   3648:                       codebase => '',
                   3649:                       code => '',
                   3650:                       archive => ''
                   3651:                     );
                   3652:     my %mediafiles = (
                   3653:                       src => '',
                   3654:                       movie => '',
                   3655:                      );
1.648     raeburn  3656:     my $p;
                   3657:     if ($content) {
                   3658:         $p = HTML::LCParser->new($content);
                   3659:     } else {
1.961     raeburn  3660:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3661:     }
1.641     albertel 3662:     while (my $t=$p->get_token()) {
1.640     albertel 3663: 	if ($t->[0] eq 'S') {
                   3664: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3665: 	    push(@state, $tagname);
1.648     raeburn  3666:             if (lc($tagname) eq 'allow') {
                   3667:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3668:             }
1.640     albertel 3669: 	    if (lc($tagname) eq 'img') {
                   3670: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3671: 	    }
1.886     albertel 3672: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  3673:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   3674: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   3675:                 }
1.886     albertel 3676: 	    }
1.645     raeburn  3677:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3678:                 my $src;
1.645     raeburn  3679:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3680:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3681:                 } else {
1.1164    raeburn  3682:                     if ($attr->{'src'} ne '') {
                   3683:                         $src = $attr->{'src'};
                   3684:                         &add_filetype($allfiles,$src,'src');
                   3685:                     }
                   3686:                 }
                   3687:                 my $text = $p->get_trimmed_text();
                   3688:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3689:                     my @swfargs = split(/,/,$1);
                   3690:                     foreach my $item (@swfargs) {
                   3691:                         $item =~ s/["']//g;
                   3692:                         $item =~ s/^\s+//;
                   3693:                         $item =~ s/\s+$//;
                   3694:                     }
                   3695:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3696:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3697:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3698:                         } else {
                   3699:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3700:                         }
                   3701:                     }
1.645     raeburn  3702:                 }
                   3703:             }
                   3704:             if (lc($tagname) eq 'link') {
                   3705:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3706:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3707:                 }
                   3708:             }
1.640     albertel 3709: 	    if (lc($tagname) eq 'object' ||
                   3710: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3711: 		foreach my $item (keys(%javafiles)) {
                   3712: 		    $javafiles{$item} = '';
                   3713: 		}
1.1164    raeburn  3714:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3715:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3716:                 }
1.640     albertel 3717: 	    }
                   3718: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3719: 		my $name = lc($attr->{'name'});
                   3720: 		foreach my $item (keys(%javafiles)) {
                   3721: 		    if ($name eq $item) {
                   3722: 			$javafiles{$item} = $attr->{'value'};
                   3723: 			last;
                   3724: 		    }
                   3725: 		}
1.1164    raeburn  3726:                 my $pathfrom;
1.640     albertel 3727: 		foreach my $item (keys(%mediafiles)) {
                   3728: 		    if ($name eq $item) {
1.1164    raeburn  3729:                         $pathfrom = $attr->{'value'};
                   3730:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3731: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3732: 			last;
                   3733: 		    }
                   3734: 		}
1.1164    raeburn  3735:                 if ($name eq 'flashvars') {
                   3736:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3737:                 }
                   3738:                 if ($pathfrom ne '') {
                   3739:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3740:                                          $pathfrom);
                   3741:                 }
1.640     albertel 3742: 	    }
                   3743: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3744: 		foreach my $item (keys(%javafiles)) {
                   3745: 		    if ($attr->{$item}) {
                   3746: 			$javafiles{$item} = $attr->{$item};
                   3747: 			last;
                   3748: 		    }
                   3749: 		}
                   3750: 		foreach my $item (keys(%mediafiles)) {
                   3751: 		    if ($attr->{$item}) {
                   3752: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3753: 			last;
                   3754: 		    }
                   3755: 		}
1.1164    raeburn  3756:                 if (lc($tagname) eq 'embed') {
                   3757:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3758:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3759:                                              $attr->{'src'});
                   3760:                     }
                   3761:                 }
1.640     albertel 3762: 	    }
1.1172.2.35  raeburn  3763:             if (lc($tagname) eq 'iframe') {
                   3764:                 my $src = $attr->{'src'} ;
                   3765:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   3766:                     &add_filetype($allfiles,$src,'src');
                   3767:                 } elsif ($src =~ m{^/}) {
                   3768:                     if ($env{'request.course.id'}) {
                   3769:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3770:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3771:                         my $url = &hreflocation('',$fullpath);
                   3772:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   3773:                             my $relpath = $1;
                   3774:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   3775:                                 &add_filetype($allfiles,$1,'src');
                   3776:                             }
                   3777:                         }
                   3778:                     }
                   3779:                 }
                   3780:             }
1.1164    raeburn  3781:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  3782:                 pop(@state);
1.1164    raeburn  3783:             }
1.640     albertel 3784: 	} elsif ($t->[0] eq 'E') {
                   3785: 	    my ($tagname) = ($t->[1]);
                   3786: 	    if ($javafiles{'codebase'} ne '') {
                   3787: 		$javafiles{'codebase'} .= '/';
                   3788: 	    }  
                   3789: 	    if (lc($tagname) eq 'applet' ||
                   3790: 		lc($tagname) eq 'object' ||
                   3791: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3792: 		) {
                   3793: 		foreach my $item (keys(%javafiles)) {
                   3794: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3795: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3796: 			&add_filetype($allfiles,$file,$item);
                   3797: 		    }
                   3798: 		}
                   3799: 	    } 
                   3800: 	    pop @state;
                   3801: 	}
                   3802:     }
1.1164    raeburn  3803:     foreach my $id (sort(keys(%flashvars))) {
                   3804:         if ($shockwave{$id} ne '') {
                   3805:             my @pairs = split(/\&/,$flashvars{$id});
                   3806:             foreach my $pair (@pairs) {
                   3807:                 my ($key,$value) = split(/\=/,$pair);
                   3808:                 if ($key eq 'thumb') {
                   3809:                     &add_filetype($allfiles,$value,$key);
                   3810:                 } elsif ($key eq 'content') {
                   3811:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3812:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3813:                     if ($ext ne '') {
                   3814:                         &add_filetype($allfiles,$path.$value,$ext);
                   3815:                     }
                   3816:                 }
                   3817:             }
                   3818:         }
                   3819:     }
1.637     raeburn  3820:     return 'ok';
                   3821: }
                   3822: 
1.639     albertel 3823: sub add_filetype {
                   3824:     my ($allfiles,$file,$type)=@_;
                   3825:     if (exists($allfiles->{$file})) {
                   3826: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3827: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3828: 	}
                   3829:     } else {
                   3830: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3831:     }
                   3832: }
                   3833: 
1.1164    raeburn  3834: sub embedded_dependency {
                   3835:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3836:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3837:         if (($identifier ne '') &&
                   3838:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3839:             ($pathfrom ne '')) {
                   3840:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3841:             foreach my $dep (@{$related->{$identifier}}) {
                   3842:                 &add_filetype($allfiles,$path.$dep,'object');
                   3843:             }
                   3844:         }
                   3845:     }
                   3846:     return;
                   3847: }
                   3848: 
1.493     albertel 3849: sub removeuploadedurl {
1.984     neumanie 3850:     my ($url)=@_;	
                   3851:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3852:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3853: }
                   3854: 
                   3855: sub removeuserfile {
                   3856:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3857:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3858:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3859:     if ($result eq 'ok') {	
1.798     raeburn  3860:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3861:             my $metafile = $fname.'.meta';
                   3862:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3863: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3864:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3865:             my $sqlresult = 
1.823     albertel 3866:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3867:                                         'portfolio_metadata',$group,
                   3868:                                         'delete');
1.798     raeburn  3869:         }
                   3870:     }
                   3871:     return $result;
1.257     www      3872: }
1.15      www      3873: 
1.530     albertel 3874: sub mkdiruserfile {
                   3875:     my ($docuname,$docudom,$dir)=@_;
                   3876:     my $home=&homeserver($docuname,$docudom);
                   3877:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3878: }
                   3879: 
1.531     albertel 3880: sub renameuserfile {
                   3881:     my ($docuname,$docudom,$old,$new)=@_;
                   3882:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3883:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3884:                         &escape("$old").':'.&escape("$new"),$home);
                   3885:     if ($result eq 'ok') {
                   3886:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3887:             my $oldmeta = $old.'.meta';
                   3888:             my $newmeta = $new.'.meta';
                   3889:             my $metaresult = 
                   3890:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3891: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3892:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3893:             my $sqlresult = 
1.823     albertel 3894:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3895:                                         'portfolio_metadata',$group,
                   3896:                                         'delete');
1.798     raeburn  3897:         }
                   3898:     }
                   3899:     return $result;
1.531     albertel 3900: }
                   3901: 
1.14      www      3902: # ------------------------------------------------------------------------- Log
                   3903: 
                   3904: sub log {
                   3905:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3906:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3907: }
                   3908: 
                   3909: # ------------------------------------------------------------------ Course Log
1.352     www      3910: #
                   3911: # This routine flushes several buffers of non-mission-critical nature
                   3912: #
1.157     www      3913: 
                   3914: sub flushcourselogs {
1.352     www      3915:     &logthis('Flushing log buffers');
                   3916: #
                   3917: # course logs
                   3918: # This is a log of all transactions in a course, which can be used
                   3919: # for data mining purposes
                   3920: #
                   3921: # It also collects the courseid database, which lists last transaction
                   3922: # times and course titles for all courseids
                   3923: #
                   3924:     my %courseidbuffer=();
1.921     raeburn  3925:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3926:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3927: 		          &escape($courselogs{$crsid}),
                   3928: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3929: 	    delete $courselogs{$crsid};
                   3930:         } else {
                   3931:             &logthis('Failed to flush log buffer for '.$crsid);
                   3932:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3933:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3934:                         " exceeded maximum size, deleting.</font>");
                   3935:                delete $courselogs{$crsid};
                   3936:             }
1.352     www      3937:         }
1.920     raeburn  3938:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3939:             'description' => $coursedescrbuf{$crsid},
                   3940:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3941:             'type'        => $coursetypebuf{$crsid},
                   3942:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3943:         };
1.191     harris41 3944:     }
1.352     www      3945: #
                   3946: # Write course id database (reverse lookup) to homeserver of courses 
                   3947: # Is used in pickcourse
                   3948: #
1.840     albertel 3949:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3950:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3951:                                     $courseidbuffer{$crs_home},
                   3952:                                     $crs_home,'timeonly');
1.352     www      3953:     }
                   3954: #
                   3955: # File accesses
                   3956: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3957: #
1.449     matthew  3958:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3959:         if ($entry =~ /___count$/) {
                   3960:             my ($dom,$name);
1.807     albertel 3961:             ($dom,$name,undef)=
1.811     albertel 3962: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3963:             if (! defined($dom) || $dom eq '' || 
                   3964:                 ! defined($name) || $name eq '') {
1.620     albertel 3965:                 my $cid = $env{'request.course.id'};
                   3966:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3967:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3968:             }
1.450     matthew  3969:             my $value = $accesshash{$entry};
                   3970:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3971:             my %temphash=($url => $value);
1.449     matthew  3972:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3973:             if ($result eq 'ok') {
                   3974:                 delete $accesshash{$entry};
                   3975:             }
                   3976:         } else {
1.811     albertel 3977:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3978:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3979:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3980:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3981:                 delete $accesshash{$entry};
                   3982:             }
1.185     www      3983:         }
1.191     harris41 3984:     }
1.352     www      3985: #
                   3986: # Roles
                   3987: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3988: #
1.800     albertel 3989:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3990:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3991: 	    split(/\:/,$entry);
                   3992:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3993:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3994:                 $rudom,$runame) eq 'ok') {
                   3995: 	    delete $userrolehash{$entry};
                   3996:         }
                   3997:     }
1.662     raeburn  3998: #
1.1172.2.90  raeburn  3999: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4000: #
                   4001:     my %domrolebuffer = ();
1.1000    raeburn  4002:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4003:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4004:         if ($domrolebuffer{$rudom}) {
                   4005:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4006:                       '='.&escape($domainrolehash{$entry});
                   4007:         } else {
                   4008:             $domrolebuffer{$rudom}.=&escape($entry).
                   4009:                       '='.&escape($domainrolehash{$entry});
                   4010:         }
                   4011:         delete $domainrolehash{$entry};
                   4012:     }
                   4013:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  4014:         my %servers;
                   4015:         if (defined(&domain($dom,'primary'))) {
                   4016:             my $primary=&domain($dom,'primary');
                   4017:             my $hostname=&hostname($primary);
                   4018:             $servers{$primary} = $hostname;
                   4019:         } else {
                   4020:             %servers = &get_servers($dom,'library');
                   4021:         }
1.841     albertel 4022: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  4023: 	    if (&reply('domroleput:'.$dom.':'.
                   4024: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4025: 	        last;
                   4026: 	    } else {
1.841     albertel 4027: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4028: 	    }
1.662     raeburn  4029:         }
                   4030:     }
1.186     www      4031:     $dumpcount++;
1.157     www      4032: }
                   4033: 
                   4034: sub courselog {
                   4035:     my $what=shift;
1.158     www      4036:     $what=time.':'.$what;
1.620     albertel 4037:     unless ($env{'request.course.id'}) { return ''; }
                   4038:     $coursedombuf{$env{'request.course.id'}}=
                   4039:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4040:     $coursenumbuf{$env{'request.course.id'}}=
                   4041:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4042:     $coursehombuf{$env{'request.course.id'}}=
                   4043:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4044:     $coursedescrbuf{$env{'request.course.id'}}=
                   4045:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4046:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4047:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4048:     $courseownerbuf{$env{'request.course.id'}}=
                   4049:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4050:     $coursetypebuf{$env{'request.course.id'}}=
                   4051:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4052:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4053: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4054:     } else {
1.620     albertel 4055: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4056:     }
1.620     albertel 4057:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4058: 	&flushcourselogs();
                   4059:     }
1.158     www      4060: }
                   4061: 
                   4062: sub courseacclog {
                   4063:     my $fnsymb=shift;
1.620     albertel 4064:     unless ($env{'request.course.id'}) { return ''; }
                   4065:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4066:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4067:         $what.=':POST';
1.583     matthew  4068:         # FIXME: Probably ought to escape things....
1.800     albertel 4069: 	foreach my $key (keys(%env)) {
                   4070:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4071:                 my $formitem = $1;
                   4072:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4073:                     $what.=':'.$formitem.'='.$env{$key};
                   4074:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4075:                     $what.=':'.$formitem.'='.$env{$key};
                   4076:                 }
1.158     www      4077:             }
1.191     harris41 4078:         }
1.583     matthew  4079:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4080:         # FIXME: We should not be depending on a form parameter that someone
                   4081:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4082:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4083:             $what.= ':POST';
                   4084:             # FIXME: Probably ought to escape things....
                   4085:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4086:                                  'crsdiscuss') {
1.620     albertel 4087:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4088:             }
                   4089:         }
1.158     www      4090:     }
                   4091:     &courselog($what);
1.149     www      4092: }
                   4093: 
1.185     www      4094: sub countacc {
                   4095:     my $url=&declutter(shift);
1.458     matthew  4096:     return if (! defined($url) || $url eq '');
1.620     albertel 4097:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4098: #
                   4099: # Mark that this url was used in this course
                   4100: #
1.620     albertel 4101:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4102: #
                   4103: # Increase the access count for this resource in this child process
                   4104: #
1.281     www      4105:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4106:     $accesshash{$key}++;
1.185     www      4107: }
1.349     www      4108: 
1.361     www      4109: sub linklog {
                   4110:     my ($from,$to)=@_;
                   4111:     $from=&declutter($from);
                   4112:     $to=&declutter($to);
                   4113:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4114:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4115: }
1.1160    www      4116: 
                   4117: sub statslog {
                   4118:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4119:     if ($users<2) { return; }
                   4120:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4121:             'course'       => $env{'request.course.id'},
                   4122:             'sections'     => '"all"',
                   4123:             'num_students' => $users,
                   4124:             'part'         => $part,
                   4125:             'symb'         => $symb,
                   4126:             'mean_tries'   => $av_attempts,
                   4127:             'deg_of_diff'  => $degdiff});
                   4128:     foreach my $key (keys(%dynstore)) {
                   4129:         $accesshash{$key}=$dynstore{$key};
                   4130:     }
                   4131: }
1.361     www      4132:   
1.349     www      4133: sub userrolelog {
                   4134:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4135:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4136:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4137:        $userrolehash
                   4138:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4139:                     =$tend.':'.$tstart;
1.662     raeburn  4140:     }
1.1169    droeschl 4141:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4142:        $userrolehash
                   4143:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4144:                     =$tend.':'.$tstart;
                   4145:     }
1.1172.2.90  raeburn  4146:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4147:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4148:        $domainrolehash
                   4149:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4150:                     = $tend.':'.$tstart;
                   4151:     }
1.351     www      4152: }
                   4153: 
1.957     raeburn  4154: sub courserolelog {
                   4155:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4156:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4157:         my $cdom = $1;
                   4158:         my $cnum = $2;
                   4159:         my $sec = $3;
                   4160:         my $namespace = 'rolelog';
                   4161:         my %storehash = (
                   4162:                            role    => $trole,
                   4163:                            start   => $tstart,
                   4164:                            end     => $tend,
                   4165:                            selfenroll => $selfenroll,
                   4166:                            context    => $context,
                   4167:                         );
                   4168:         if ($trole eq 'gr') {
                   4169:             $namespace = 'groupslog';
                   4170:             $storehash{'group'} = $sec;
                   4171:         } else {
                   4172:             $storehash{'section'} = $sec;
                   4173:         }
                   4174:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4175:                    $domain,$cnum,$cdom);
                   4176:         if (($trole ne 'st') || ($sec ne '')) {
                   4177:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4178:         }
                   4179:     }
                   4180:     return;
                   4181: }
                   4182: 
1.1172.2.9  raeburn  4183: sub domainrolelog {
                   4184:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4185:     if ($area =~ m{^/($match_domain)/$}) {
                   4186:         my $cdom = $1;
                   4187:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4188:         my $namespace = 'rolelog';
                   4189:         my %storehash = (
                   4190:                            role    => $trole,
                   4191:                            start   => $tstart,
                   4192:                            end     => $tend,
                   4193:                            context => $context,
                   4194:                         );
                   4195:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4196:                    $domain,$domconfiguser,$cdom);
                   4197:     }
                   4198:     return;
                   4199: 
                   4200: }
                   4201: 
                   4202: sub coauthorrolelog {
                   4203:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4204:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4205:         my $audom = $1;
                   4206:         my $auname = $2;
                   4207:         my $namespace = 'rolelog';
                   4208:         my %storehash = (
                   4209:                            role    => $trole,
                   4210:                            start   => $tstart,
                   4211:                            end     => $tend,
                   4212:                            context => $context,
                   4213:                         );
                   4214:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4215:                    $domain,$auname,$audom);
                   4216:     }
                   4217:     return;
                   4218: }
                   4219: 
1.351     www      4220: sub get_course_adv_roles {
1.948     raeburn  4221:     my ($cid,$codes) = @_;
1.620     albertel 4222:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4223:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4224:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4225:     my %nothide=();
1.800     albertel 4226:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4227:         if ($user !~ /:/) {
                   4228: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4229:         } else {
                   4230:             $nothide{$user}=1;
                   4231:         }
1.470     www      4232:     }
1.1172.2.23  raeburn  4233:     my @possdoms = ($coursehash{'domain'});
                   4234:     if ($coursehash{'checkforpriv'}) {
                   4235:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4236:     }
1.351     www      4237:     my %returnhash=();
                   4238:     my %dumphash=
                   4239:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4240:     my $now=time;
1.997     raeburn  4241:     my %privileged;
1.1000    raeburn  4242:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4243: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4244:         if (($tstart) && ($tstart<0)) { next; }
                   4245:         if (($tend) && ($tend<$now)) { next; }
                   4246:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4247:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4248: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4249:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4250:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4251: 	if ($role eq 'cr') { next; }
1.948     raeburn  4252:         if ($codes) {
                   4253:             if ($section) { $role .= ':'.$section; }
                   4254:             if ($returnhash{$role}) {
                   4255:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4256:             } else {
                   4257:                 $returnhash{$role}=$username.':'.$domain;
                   4258:             }
1.351     www      4259:         } else {
1.988     raeburn  4260:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4261:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4262:             if ($returnhash{$key}) {
                   4263: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4264:             } else {
                   4265:                 $returnhash{$key}=$username.':'.$domain;
                   4266:             }
1.351     www      4267:         }
1.948     raeburn  4268:     }
1.400     www      4269:     return %returnhash;
                   4270: }
                   4271: 
                   4272: sub get_my_roles {
1.937     raeburn  4273:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4274:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4275:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4276:     my (%dumphash,%nothide);
1.1086    raeburn  4277:     if ($context eq 'userroles') {
1.1166    raeburn  4278:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4279:     } else {
1.1172.2.23  raeburn  4280:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4281:         if ($hidepriv) {
                   4282:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4283:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4284:                 if ($user !~ /:/) {
                   4285:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4286:                 } else {
                   4287:                     $nothide{$user} = 1;
                   4288:                 }
                   4289:             }
                   4290:         }
1.858     raeburn  4291:     }
1.400     www      4292:     my %returnhash=();
                   4293:     my $now=time;
1.999     raeburn  4294:     my %privileged;
1.800     albertel 4295:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4296:         my ($role,$tend,$tstart);
                   4297:         if ($context eq 'userroles') {
1.1149    raeburn  4298:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4299: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4300:         } else {
                   4301:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4302:         }
1.400     www      4303:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4304:         my $status = 'active';
1.939     raeburn  4305:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4306:             $status = 'previous';
                   4307:         } 
                   4308:         if (($tstart) && ($now<$tstart)) {
                   4309:             $status = 'future';
                   4310:         }
                   4311:         if (ref($types) eq 'ARRAY') {
                   4312:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4313:                 next;
                   4314:             } 
                   4315:         } else {
                   4316:             if ($status ne 'active') {
                   4317:                 next;
                   4318:             }
                   4319:         }
1.867     raeburn  4320:         my ($rolecode,$username,$domain,$section,$area);
                   4321:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  4322:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4323:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4324:         } else {
                   4325:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4326:         }
1.832     raeburn  4327:         if (ref($roledoms) eq 'ARRAY') {
                   4328:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4329:                 next;
                   4330:             }
                   4331:         }
                   4332:         if (ref($roles) eq 'ARRAY') {
                   4333:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4334:                 if ($role =~ /^cr\//) {
                   4335:                     if (!grep(/^cr$/,@{$roles})) {
                   4336:                         next;
                   4337:                     }
1.1104    raeburn  4338:                 } elsif ($role =~ /^gr\//) {
                   4339:                     if (!grep(/^gr$/,@{$roles})) {
                   4340:                         next;
                   4341:                     }
1.922     raeburn  4342:                 } else {
                   4343:                     next;
                   4344:                 }
1.832     raeburn  4345:             }
1.867     raeburn  4346:         }
1.937     raeburn  4347:         if ($hidepriv) {
1.1172.2.23  raeburn  4348:             my @privroles = ('dc','su');
1.999     raeburn  4349:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  4350:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4351:             } else {
1.1172.2.23  raeburn  4352:                 my $possdoms = [$domain];
                   4353:                 if (ref($roledoms) eq 'ARRAY') {
                   4354:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  4355:                 }
1.1172.2.23  raeburn  4356:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4357:                     if (!$nothide{$username.':'.$domain}) {
                   4358:                         next;
                   4359:                     }
                   4360:                 }
1.937     raeburn  4361:             }
                   4362:         }
1.933     raeburn  4363:         if ($withsec) {
                   4364:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4365:                 $tstart.':'.$tend;
                   4366:         } else {
                   4367:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4368:         }
1.832     raeburn  4369:     }
1.373     www      4370:     return %returnhash;
1.399     www      4371: }
                   4372: 
1.1172.2.89  raeburn  4373: sub get_all_adhocroles {
                   4374:     my ($dom) = @_;
                   4375:     my @roles_by_num = ();
                   4376:     my %domdefaults = &get_domain_defaults($dom);
                   4377:     my (%description,%access_in_dom,%access_info);
                   4378:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   4379:         my $count = 0;
                   4380:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   4381:         my %ordered;
                   4382:         foreach my $role (sort(keys(%domcurrent))) {
                   4383:             my ($order,$desc,$access_in_dom);
                   4384:             if (ref($domcurrent{$role}) eq 'HASH') {
                   4385:                 $order = $domcurrent{$role}{'order'};
                   4386:                 $desc = $domcurrent{$role}{'desc'};
                   4387:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   4388:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   4389:             }
                   4390:             if ($order eq '') {
                   4391:                 $order = $count;
                   4392:             }
                   4393:             $ordered{$order} = $role;
                   4394:             if ($desc ne '') {
                   4395:                 $description{$role} = $desc;
                   4396:             } else {
                   4397:                 $description{$role}= $role;
                   4398:             }
                   4399:             $count++;
                   4400:         }
                   4401:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   4402:             push(@roles_by_num,$ordered{$item});
                   4403:         }
                   4404:     }
                   4405:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   4406: }
                   4407: 
                   4408: sub get_my_adhocroles {
                   4409:     my ($cid,$checkreg) = @_;
                   4410:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   4411:     if ($env{'request.course.id'} eq $cid) {
                   4412:         $cdom = $env{'course.'.$cid.'.domain'};
                   4413:         $cnum = $env{'course.'.$cid.'.num'};
                   4414:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   4415:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   4416:         $cdom = $1;
                   4417:         $cnum = $2;
                   4418:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   4419:                                      $cdom,$cnum);
                   4420:     }
                   4421:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   4422:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4423:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   4424:         if ($rosterhash{$user} ne '') {
                   4425:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   4426:             return ([],{}) if ($type eq 'auto');
                   4427:         }
                   4428:     }
                   4429:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  4430:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  4431:             my $then=$env{'user.login.time'};
                   4432:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  4433:             if (!$update) {
                   4434:                 $update = $then;
                   4435:             }
                   4436:             my @liveroles;
                   4437:             foreach my $role ('dh','da') {
                   4438:                 if ($env{"user.role.$role./$cdom/"}) {
                   4439:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   4440:                     my $limit = $update;
                   4441:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   4442:                         $limit = $then;
                   4443:                     }
                   4444:                     my $activerole = 1;
                   4445:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   4446:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   4447:                     if ($activerole) {
                   4448:                         push(@liveroles,$role);
                   4449:                     }
                   4450:                 }
                   4451:             }
                   4452:             if (@liveroles) {
1.1172.2.89  raeburn  4453:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   4454:                     my ($accessref,$accessinfo,%access_in_dom);
                   4455:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   4456:                     if (ref($roles_by_num) eq 'ARRAY') {
                   4457:                         if (@{$roles_by_num}) {
                   4458:                             my %settings;
                   4459:                             if ($env{'request.course.id'} eq $cid) {
                   4460:                                 foreach my $envkey (keys(%env)) {
                   4461:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   4462:                                         $settings{$1} = $env{$envkey};
                   4463:                                     }
                   4464:                                 }
                   4465:                             } else {
                   4466:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   4467:                             }
                   4468:                             my %setincrs;
                   4469:                             if ($settings{'internal.adhocaccess'}) {
                   4470:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   4471:                             }
                   4472:                             my @statuses;
                   4473:                             if ($env{'environment.inststatus'}) {
                   4474:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   4475:                             }
                   4476:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4477:                             if (ref($accessref) eq 'HASH') {
                   4478:                                 %access_in_dom = %{$accessref};
                   4479:                             }
                   4480:                             foreach my $role (@{$roles_by_num}) {
                   4481:                                 my ($curraccess,@okstatus,@personnel);
                   4482:                                 if ($setincrs{$role}) {
                   4483:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   4484:                                     if ($curraccess eq 'status') {
                   4485:                                         @okstatus = split(/\&/,$rest);
                   4486:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4487:                                         @personnel = split(/\&/,$rest);
                   4488:                                     }
                   4489:                                 } else {
                   4490:                                     $curraccess = $access_in_dom{$role};
                   4491:                                     if (ref($accessinfo) eq 'HASH') {
                   4492:                                         if ($curraccess eq 'status') {
                   4493:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4494:                                                 @okstatus = @{$accessinfo->{$role}};
                   4495:                                             }
                   4496:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4497:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4498:                                                 @personnel = @{$accessinfo->{$role}};
                   4499:                                             }
                   4500:                                         }
                   4501:                                     }
                   4502:                                 }
                   4503:                                 if ($curraccess eq 'none') {
                   4504:                                     next;
                   4505:                                 } elsif ($curraccess eq 'all') {
                   4506:                                     push(@possroles,$role);
1.1172.2.90  raeburn  4507:                                 } elsif ($curraccess eq 'dh') {
                   4508:                                     if (grep(/^dh$/,@liveroles)) {
                   4509:                                         push(@possroles,$role);
                   4510:                                     } else {
                   4511:                                         next;
                   4512:                                     }
                   4513:                                 } elsif ($curraccess eq 'da') {
                   4514:                                     if (grep(/^da$/,@liveroles)) {
                   4515:                                         push(@possroles,$role);
                   4516:                                     } else {
                   4517:                                         next;
                   4518:                                     }
1.1172.2.89  raeburn  4519:                                 } elsif ($curraccess eq 'status') {
                   4520:                                     if (@okstatus) {
                   4521:                                         if (!@statuses) {
                   4522:                                             if (grep(/^default$/,@okstatus)) {
                   4523:                                                 push(@possroles,$role);
                   4524:                                             }
                   4525:                                         } else {
                   4526:                                             foreach my $status (@okstatus) {
                   4527:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   4528:                                                     push(@possroles,$role);
                   4529:                                                     last;
                   4530:                                                 }
                   4531:                                             }
                   4532:                                         }
                   4533:                                     }
                   4534:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4535:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   4536:                                         if ($curraccess eq 'exc') {
                   4537:                                             push(@possroles,$role);
                   4538:                                         }
                   4539:                                     } elsif ($curraccess eq 'inc') {
                   4540:                                         push(@possroles,$role);
                   4541:                                     }
                   4542:                                 }
                   4543:                             }
                   4544:                         }
                   4545:                     }
                   4546:                 }
                   4547:             }
                   4548:         }
                   4549:     }
                   4550:     unless (ref($description) eq 'HASH') {
                   4551:         if (ref($roles_by_num) eq 'ARRAY') {
                   4552:             my %desc;
                   4553:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   4554:             $description = \%desc;
                   4555:         } else {
                   4556:             $description = {};
                   4557:         }
                   4558:     }
                   4559:     return (\@possroles,$description);
                   4560: }
                   4561: 
1.399     www      4562: # ----------------------------------------------------- Frontpage Announcements
                   4563: #
                   4564: #
                   4565: 
                   4566: sub postannounce {
                   4567:     my ($server,$text)=@_;
1.844     albertel 4568:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4569:     unless ($text=~/\w/) { $text=''; }
                   4570:     return &reply('setannounce:'.&escape($text),$server);
                   4571: }
                   4572: 
                   4573: sub getannounce {
1.448     albertel 4574: 
1.1172.2.93.4  7(raebur 4575:7):     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4576: 	my $announcement='';
1.800     albertel 4577: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4578: 	close($fh);
1.399     www      4579: 	if ($announcement=~/\w/) { 
                   4580: 	    return 
                   4581:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4582:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4583: 	} else {
                   4584: 	    return '';
                   4585: 	}
                   4586:     } else {
                   4587: 	return '';
                   4588:     }
1.351     www      4589: }
1.353     www      4590: 
                   4591: # ---------------------------------------------------------- Course ID routines
                   4592: # Deal with domain's nohist_courseid.db files
                   4593: #
                   4594: 
                   4595: sub courseidput {
1.921     raeburn  4596:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4597:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4598:     my $outcome;
                   4599:     if ($caller eq 'timeonly') {
                   4600:         my $cids = '';
                   4601:         foreach my $item (keys(%$storehash)) {
                   4602:             $cids.=&escape($item).'&';
                   4603:         }
                   4604:         $cids=~s/\&$//;
                   4605:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4606:                           $coursehome);       
                   4607:     } else {
                   4608:         my $items = '';
                   4609:         foreach my $item (keys(%$storehash)) {
                   4610:             $items.= &escape($item).'='.
                   4611:                      &freeze_escape($$storehash{$item}).'&';
                   4612:         }
                   4613:         $items=~s/\&$//;
                   4614:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4615:                           $coursehome);
1.918     raeburn  4616:     }
                   4617:     if ($outcome eq 'unknown_cmd') {
                   4618:         my $what;
                   4619:         foreach my $cid (keys(%$storehash)) {
                   4620:             $what .= &escape($cid).'=';
1.921     raeburn  4621:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4622:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4623:             }
                   4624:             $what =~ s/\:$/&/;
                   4625:         }
                   4626:         $what =~ s/\&$//;  
                   4627:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4628:     } else {
                   4629:         return $outcome;
                   4630:     }
1.353     www      4631: }
                   4632: 
                   4633: sub courseiddump {
1.921     raeburn  4634:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4635:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4636:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  4637:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  4638:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  4639:     my $as_hash = 1;
                   4640:     my %returnhash;
                   4641:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4642:     my %libserv = &all_library();
                   4643:     foreach my $tryserver (keys(%libserv)) {
                   4644:         if ( (  $hostidflag == 1 
                   4645: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4646: 	     || (!defined($hostidflag)) ) {
                   4647: 
1.918     raeburn  4648: 	    if (($domfilter eq '') ||
                   4649: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  4650:                 my $rep;
                   4651:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   4652:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   4653:                         join(":", (&host_domain($tryserver), $sincefilter,
                   4654:                                 &escape($descfilter), &escape($instcodefilter),
                   4655:                                 &escape($ownerfilter), &escape($coursefilter),
                   4656:                                 &escape($typefilter), &escape($regexp_ok),
                   4657:                                 $as_hash, &escape($selfenrollonly),
                   4658:                                 &escape($catfilter), $showhidden, $caller,
                   4659:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   4660:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  4661:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   4662:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  4663:                 } else {
                   4664:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4665:                              $sincefilter.':'.&escape($descfilter).':'.
                   4666:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4667:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4668:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4669:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4670:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4671:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4672:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  4673:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   4674:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  4675:                 }
                   4676: 
1.918     raeburn  4677:                 my @pairs=split(/\&/,$rep);
                   4678:                 foreach my $item (@pairs) {
                   4679:                     my ($key,$value)=split(/\=/,$item,2);
                   4680:                     $key = &unescape($key);
                   4681:                     next if ($key =~ /^error: 2 /);
                   4682:                     my $result = &thaw_unescape($value);
                   4683:                     if (ref($result) eq 'HASH') {
                   4684:                         $returnhash{$key}=$result;
                   4685:                     } else {
1.921     raeburn  4686:                         my @responses = split(/:/,$value);
                   4687:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4688:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4689:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4690:                         }
1.1008    raeburn  4691:                     }
1.353     www      4692:                 }
                   4693:             }
                   4694:         }
                   4695:     }
                   4696:     return %returnhash;
                   4697: }
                   4698: 
1.1055    raeburn  4699: sub courselastaccess {
                   4700:     my ($cdom,$cnum,$hostidref) = @_;
                   4701:     my %returnhash;
                   4702:     if ($cdom && $cnum) {
                   4703:         my $chome = &homeserver($cnum,$cdom);
                   4704:         if ($chome ne 'no_host') {
                   4705:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4706:             &extract_lastaccess(\%returnhash,$rep);
                   4707:         }
                   4708:     } else {
                   4709:         if (!$cdom) { $cdom=''; }
                   4710:         my %libserv = &all_library();
                   4711:         foreach my $tryserver (keys(%libserv)) {
                   4712:             if (ref($hostidref) eq 'ARRAY') {
                   4713:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4714:             } 
                   4715:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4716:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4717:                 &extract_lastaccess(\%returnhash,$rep);
                   4718:             }
                   4719:         }
                   4720:     }
                   4721:     return %returnhash;
                   4722: }
                   4723: 
                   4724: sub extract_lastaccess {
                   4725:     my ($returnhash,$rep) = @_;
                   4726:     if (ref($returnhash) eq 'HASH') {
                   4727:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4728:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4729:                  $rep eq '') {
                   4730:             my @pairs=split(/\&/,$rep);
                   4731:             foreach my $item (@pairs) {
                   4732:                 my ($key,$value)=split(/\=/,$item,2);
                   4733:                 $key = &unescape($key);
                   4734:                 next if ($key =~ /^error: 2 /);
                   4735:                 $returnhash->{$key} = &thaw_unescape($value);
                   4736:             }
                   4737:         }
                   4738:     }
                   4739:     return;
                   4740: }
                   4741: 
1.658     raeburn  4742: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4743: 
                   4744: sub dcmailput {
1.685     raeburn  4745:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4746:     my $status = &Apache::lonnet::critical(
1.740     www      4747:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4748:        &escape($message),$server);
1.662     raeburn  4749:     return $status;
                   4750: }
                   4751: 
1.658     raeburn  4752: sub dcmaildump {
                   4753:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4754:     my %returnhash=();
1.846     albertel 4755: 
                   4756:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4757:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4758:                                                          &escape($enddate).':';
                   4759: 	my @esc_senders=map { &escape($_)} @$senders;
                   4760: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4761: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4762:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4763:             if (($key) && ($value)) {
                   4764:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4765:             }
                   4766:         }
                   4767:     }
                   4768:     return %returnhash;
                   4769: }
1.662     raeburn  4770: # ---------------------------------------------------------- Domain roles
                   4771: 
                   4772: sub get_domain_roles {
                   4773:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4774:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4775:         $startdate = '.';
                   4776:     }
1.1018    raeburn  4777:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4778:         $enddate = '.';
                   4779:     }
1.922     raeburn  4780:     my $rolelist;
                   4781:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  4782:         $rolelist = join('&',@{$roles});
1.922     raeburn  4783:     }
1.662     raeburn  4784:     my %personnel = ();
1.841     albertel 4785: 
                   4786:     my %servers = &get_servers($dom,'library');
                   4787:     foreach my $tryserver (keys(%servers)) {
                   4788: 	%{$personnel{$tryserver}}=();
                   4789: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4790: 					    &escape($startdate).':'.
                   4791: 					    &escape($enddate).':'.
                   4792: 					    &escape($rolelist), $tryserver))) {
                   4793: 	    my ($key,$value) = split(/\=/,$line,2);
                   4794: 	    if (($key) && ($value)) {
                   4795: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4796: 	    }
                   4797: 	}
1.662     raeburn  4798:     }
                   4799:     return %personnel;
                   4800: }
1.658     raeburn  4801: 
1.1172.2.89  raeburn  4802: sub get_active_domroles {
                   4803:     my ($dom,$roles) = @_;
                   4804:     return () unless (ref($roles) eq 'ARRAY');
                   4805:     my $now = time;
                   4806:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   4807:     my %domroles;
                   4808:     foreach my $server (keys(%dompersonnel)) {
                   4809:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   4810:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   4811:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   4812:         }
                   4813:     }
                   4814:     return %domroles;
                   4815: }
                   4816: 
1.1057    www      4817: # ----------------------------------------------------------- Interval timing 
1.149     www      4818: 
1.1153    www      4819: {
                   4820: # Caches needed for speedup of navmaps
                   4821: # We don't want to cache this for very long at all (5 seconds at most)
                   4822: # 
                   4823: # The user for whom we cache
                   4824: my $cachedkey='';
                   4825: # The cached times for this user
                   4826: my %cachedtimes=();
                   4827: # When this was last done
1.1172.2.66  raeburn  4828: my $cachedtime='';
1.1153    www      4829: 
                   4830: sub load_all_first_access {
1.1172.2.93.4  1(raebur 4831:7):     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      4832:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.93.4  1(raebur 4833:7):         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   4834:7):         (!$ignorecache)) {
1.1154    raeburn  4835:         return;
                   4836:     }
                   4837:     $cachedtime=time;
                   4838:     $cachedkey=$uname.':'.$udom;
                   4839:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4840: }
                   4841: 
1.504     albertel 4842: sub get_first_access {
1.1172.2.93.4  1(raebur 4843:7):     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 4844:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4845:     if ($argsymb) { $symb=$argsymb; }
                   4846:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4847:     if ($argmap) { $map = $argmap; }
1.926     albertel 4848:     if ($type eq 'course') {
                   4849: 	$res='course';
                   4850:     } elsif ($type eq 'map') {
1.588     albertel 4851: 	$res=&symbread($map);
                   4852:     } else {
                   4853: 	$res=$symb;
                   4854:     }
1.1172.2.93.4  1(raebur 4855:7):     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      4856:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4857: }
                   4858: 
                   4859: sub set_first_access {
1.1162    raeburn  4860:     my ($type,$interval)=@_;
1.790     albertel 4861:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4862:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4863:     if ($type eq 'course') {
                   4864: 	$res='course';
                   4865:     } elsif ($type eq 'map') {
1.588     albertel 4866: 	$res=&symbread($map);
                   4867:     } else {
                   4868: 	$res=$symb;
                   4869:     }
1.1153    www      4870:     $cachedkey='';
1.1162    raeburn  4871:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4872:     if (!$firstaccess) {
1.1162    raeburn  4873:         my $start = time;
                   4874: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4875:                           $udom,$uname);
                   4876:         if ($putres eq 'ok') {
                   4877:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4878:                  $udom,$uname); 
                   4879:             &appenv(
                   4880:                      {
                   4881:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4882:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4883:                      }
                   4884:                   );
                   4885:         }
                   4886:         return $putres;
1.505     albertel 4887:     }
                   4888:     return 'already_set';
1.504     albertel 4889: }
1.1153    www      4890: }
1.1172.2.32  raeburn  4891: 
                   4892: sub checkout {
                   4893:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   4894:     my $now=time;
                   4895:     my $lonhost=$perlvar{'lonHostID'};
                   4896:     my $infostr=&escape(
                   4897:                  'CHECKOUTTOKEN&'.
                   4898:                  $tuname.'&'.
                   4899:                  $tudom.'&'.
                   4900:                  $tcrsid.'&'.
                   4901:                  $symb.'&'.
                   4902:                  $now.'&'.$ENV{'REMOTE_ADDR'});
                   4903:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   4904:     if ($token=~/^error\:/) {
                   4905:         &logthis("<font color=\"blue\">WARNING: ".
                   4906:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4907:                  "</font>");
                   4908:         return '';
                   4909:     }
                   4910: 
                   4911:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   4912:     $token=~tr/a-z/A-Z/;
                   4913: 
                   4914:     my %infohash=('resource.0.outtoken' => $token,
                   4915:                   'resource.0.checkouttime' => $now,
                   4916:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
                   4917: 
                   4918:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   4919:        return '';
                   4920:     } else {
                   4921:         &logthis("<font color=\"blue\">WARNING: ".
                   4922:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4923:                  "</font>");
                   4924:     }
                   4925: 
                   4926:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   4927:                          &escape('Checkout '.$infostr.' - '.
                   4928:                                                  $token)) ne 'ok') {
                   4929:         return '';
                   4930:     } else {
                   4931:         &logthis("<font color=\"blue\">WARNING: ".
                   4932:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4933:                  "</font>");
                   4934:     }
                   4935:     return $token;
                   4936: }
                   4937: 
                   4938: # ------------------------------------------------------------ Check in an item
                   4939: 
                   4940: sub checkin {
                   4941:     my $token=shift;
                   4942:     my $now=time;
                   4943:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   4944:     $lonhost=~tr/A-Z/a-z/;
                   4945:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   4946:     $dtoken=~s/\W/\_/g;
                   4947:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   4948:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   4949: 
                   4950:     unless (($tuname) && ($tudom)) {
                   4951:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   4952:         return '';
                   4953:     }
                   4954: 
                   4955:     unless (&allowed('mgr',$tcrsid)) {
                   4956:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   4957:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   4958:         return '';
                   4959:     }
                   4960: 
                   4961:     my %infohash=('resource.0.intoken' => $token,
                   4962:                   'resource.0.checkintime' => $now,
                   4963:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
                   4964: 
                   4965:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   4966:        return '';
                   4967:     }
                   4968: 
                   4969:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   4970:                          &escape('Checkin - '.$token)) ne 'ok') {
                   4971:         return '';
                   4972:     }
                   4973: 
                   4974:     return ($symb,$tuname,$tudom,$tcrsid);
                   4975: }
                   4976: 
1.110     www      4977: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4978: 
                   4979: sub expirespread {
                   4980:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4981:     my $cid=$env{'request.course.id'}; 
1.110     www      4982:     if ($cid) {
                   4983:        my $now=time;
                   4984:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4985:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4986:                             $env{'course.'.$cid.'.num'}.
1.110     www      4987: 	        	    ':nohist_expirationdates:'.
                   4988:                             &escape($key).'='.$now,
1.620     albertel 4989:                             $env{'course.'.$cid.'.home'})
1.110     www      4990:     }
                   4991:     return 'ok';
1.14      www      4992: }
                   4993: 
1.109     www      4994: # ----------------------------------------------------- Devalidate Spreadsheets
                   4995: 
                   4996: sub devalidate {
1.325     www      4997:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4998:     my $cid=$env{'request.course.id'}; 
1.109     www      4999:     if ($cid) {
1.391     matthew  5000:         # delete the stored spreadsheets for
                   5001:         # - the student level sheet of this user in course's homespace
                   5002:         # - the assessment level sheet for this resource 
                   5003:         #   for this user in user's homespace
1.553     albertel 5004: 	# - current conditional state info
1.325     www      5005: 	my $key=$uname.':'.$udom.':';
1.109     www      5006:         my $status=
1.299     matthew  5007: 	    &del('nohist_calculatedsheets',
1.391     matthew  5008: 		 [$key.'studentcalc:'],
1.620     albertel 5009: 		 $env{'course.'.$cid.'.domain'},
                   5010: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5011: 		.' '.
                   5012: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5013: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5014:         unless ($status eq 'ok ok') {
                   5015:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5016:                     $uname.' at '.$udom.' for '.
1.109     www      5017: 		    $symb.': '.$status);
1.133     albertel 5018:         }
1.553     albertel 5019: 	&delenv('user.state.'.$cid);
1.109     www      5020:     }
                   5021: }
                   5022: 
1.265     albertel 5023: sub get_scalar {
                   5024:     my ($string,$end) = @_;
                   5025:     my $value;
                   5026:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5027: 	$value = $1;
                   5028:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5029: 	$value = $1;
                   5030:     }
                   5031:     return &unescape($value);
                   5032: }
                   5033: 
                   5034: sub array2str {
                   5035:   my (@array) = @_;
                   5036:   my $result=&arrayref2str(\@array);
                   5037:   $result=~s/^__ARRAY_REF__//;
                   5038:   $result=~s/__END_ARRAY_REF__$//;
                   5039:   return $result;
                   5040: }
                   5041: 
1.204     albertel 5042: sub arrayref2str {
                   5043:   my ($arrayref) = @_;
1.265     albertel 5044:   my $result='__ARRAY_REF__';
1.204     albertel 5045:   foreach my $elem (@$arrayref) {
1.265     albertel 5046:     if(ref($elem) eq 'ARRAY') {
                   5047:       $result.=&arrayref2str($elem).'&';
                   5048:     } elsif(ref($elem) eq 'HASH') {
                   5049:       $result.=&hashref2str($elem).'&';
                   5050:     } elsif(ref($elem)) {
                   5051:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5052:     } else {
                   5053:       $result.=&escape($elem).'&';
                   5054:     }
                   5055:   }
                   5056:   $result=~s/\&$//;
1.265     albertel 5057:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5058:   return $result;
                   5059: }
                   5060: 
1.168     albertel 5061: sub hash2str {
1.204     albertel 5062:   my (%hash) = @_;
                   5063:   my $result=&hashref2str(\%hash);
1.265     albertel 5064:   $result=~s/^__HASH_REF__//;
                   5065:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5066:   return $result;
                   5067: }
                   5068: 
                   5069: sub hashref2str {
                   5070:   my ($hashref)=@_;
1.265     albertel 5071:   my $result='__HASH_REF__';
1.800     albertel 5072:   foreach my $key (sort(keys(%$hashref))) {
                   5073:     if (ref($key) eq 'ARRAY') {
                   5074:       $result.=&arrayref2str($key).'=';
                   5075:     } elsif (ref($key) eq 'HASH') {
                   5076:       $result.=&hashref2str($key).'=';
                   5077:     } elsif (ref($key)) {
1.265     albertel 5078:       $result.='=';
1.800     albertel 5079:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5080:     } else {
1.1132    raeburn  5081: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5082:     }
                   5083: 
1.800     albertel 5084:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5085:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5086:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5087:       $result.=&hashref2str($hashref->{$key}).'&';
                   5088:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5089:        $result.='&';
1.800     albertel 5090:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5091:     } else {
1.800     albertel 5092:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5093:     }
                   5094:   }
1.168     albertel 5095:   $result=~s/\&$//;
1.265     albertel 5096:   $result .= '__END_HASH_REF__';
1.168     albertel 5097:   return $result;
                   5098: }
                   5099: 
                   5100: sub str2hash {
1.265     albertel 5101:     my ($string)=@_;
                   5102:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5103:     return %$hash;
                   5104: }
                   5105: 
                   5106: sub str2hashref {
1.168     albertel 5107:   my ($string) = @_;
1.265     albertel 5108: 
                   5109:   my %hash;
                   5110: 
                   5111:   if($string !~ /^__HASH_REF__/) {
                   5112:       if (! ($string eq '' || !defined($string))) {
                   5113: 	  $hash{'error'}='Not hash reference';
                   5114:       }
                   5115:       return (\%hash, $string);
                   5116:   }
                   5117: 
                   5118:   $string =~ s/^__HASH_REF__//;
                   5119: 
                   5120:   while($string !~ /^__END_HASH_REF__/) {
                   5121:       #key
                   5122:       my $key='';
                   5123:       if($string =~ /^__HASH_REF__/) {
                   5124:           ($key, $string)=&str2hashref($string);
                   5125:           if(defined($key->{'error'})) {
                   5126:               $hash{'error'}='Bad data';
                   5127:               return (\%hash, $string);
                   5128:           }
                   5129:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5130:           ($key, $string)=&str2arrayref($string);
                   5131:           if($key->[0] eq 'Array reference error') {
                   5132:               $hash{'error'}='Bad data';
                   5133:               return (\%hash, $string);
                   5134:           }
                   5135:       } else {
                   5136:           $string =~ s/^(.*?)=//;
1.267     albertel 5137: 	  $key=&unescape($1);
1.265     albertel 5138:       }
                   5139:       $string =~ s/^=//;
                   5140: 
                   5141:       #value
                   5142:       my $value='';
                   5143:       if($string =~ /^__HASH_REF__/) {
                   5144:           ($value, $string)=&str2hashref($string);
                   5145:           if(defined($value->{'error'})) {
                   5146:               $hash{'error'}='Bad data';
                   5147:               return (\%hash, $string);
                   5148:           }
                   5149:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5150:           ($value, $string)=&str2arrayref($string);
                   5151:           if($value->[0] eq 'Array reference error') {
                   5152:               $hash{'error'}='Bad data';
                   5153:               return (\%hash, $string);
                   5154:           }
                   5155:       } else {
                   5156: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5157:       }
                   5158:       $string =~ s/^&//;
                   5159: 
                   5160:       $hash{$key}=$value;
1.204     albertel 5161:   }
1.265     albertel 5162: 
                   5163:   $string =~ s/^__END_HASH_REF__//;
                   5164: 
                   5165:   return (\%hash, $string);
1.204     albertel 5166: }
                   5167: 
                   5168: sub str2array {
1.265     albertel 5169:     my ($string)=@_;
                   5170:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5171:     return @$array;
                   5172: }
                   5173: 
                   5174: sub str2arrayref {
1.204     albertel 5175:   my ($string) = @_;
1.265     albertel 5176:   my @array;
                   5177: 
                   5178:   if($string !~ /^__ARRAY_REF__/) {
                   5179:       if (! ($string eq '' || !defined($string))) {
                   5180: 	  $array[0]='Array reference error';
                   5181:       }
                   5182:       return (\@array, $string);
                   5183:   }
                   5184: 
                   5185:   $string =~ s/^__ARRAY_REF__//;
                   5186: 
                   5187:   while($string !~ /^__END_ARRAY_REF__/) {
                   5188:       my $value='';
                   5189:       if($string =~ /^__HASH_REF__/) {
                   5190:           ($value, $string)=&str2hashref($string);
                   5191:           if(defined($value->{'error'})) {
                   5192:               $array[0] ='Array reference error';
                   5193:               return (\@array, $string);
                   5194:           }
                   5195:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5196:           ($value, $string)=&str2arrayref($string);
                   5197:           if($value->[0] eq 'Array reference error') {
                   5198:               $array[0] ='Array reference error';
                   5199:               return (\@array, $string);
                   5200:           }
                   5201:       } else {
                   5202: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5203:       }
                   5204:       $string =~ s/^&//;
                   5205: 
                   5206:       push(@array, $value);
1.191     harris41 5207:   }
1.265     albertel 5208: 
                   5209:   $string =~ s/^__END_ARRAY_REF__//;
                   5210: 
                   5211:   return (\@array, $string);
1.168     albertel 5212: }
                   5213: 
1.167     albertel 5214: # -------------------------------------------------------------------Temp Store
                   5215: 
1.168     albertel 5216: sub tmpreset {
                   5217:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5218:   if (!$symb) {
                   5219:     $symb=&symbread();
1.620     albertel 5220:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5221:   }
                   5222:   $symb=escape($symb);
                   5223: 
1.620     albertel 5224:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5225:   $namespace=~s/\//\_/g;
                   5226:   $namespace=~s/\W//g;
                   5227: 
1.620     albertel 5228:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5229:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5230:   if ($domain eq 'public' && $stuname eq 'public') {
                   5231:       $stuname=$ENV{'REMOTE_ADDR'};
                   5232:   }
1.1117    foxr     5233:   my $path=LONCAPA::tempdir();
1.168     albertel 5234:   my %hash;
                   5235:   if (tie(%hash,'GDBM_File',
                   5236: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5237: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5238:     foreach my $key (keys(%hash)) {
1.180     albertel 5239:       if ($key=~ /:$symb/) {
1.168     albertel 5240: 	delete($hash{$key});
                   5241:       }
                   5242:     }
                   5243:   }
                   5244: }
                   5245: 
1.167     albertel 5246: sub tmpstore {
1.168     albertel 5247:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5248: 
                   5249:   if (!$symb) {
                   5250:     $symb=&symbread();
1.620     albertel 5251:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5252:   }
                   5253:   $symb=escape($symb);
                   5254: 
                   5255:   if (!$namespace) {
                   5256:     # I don't think we would ever want to store this for a course.
                   5257:     # it seems this will only be used if we don't have a course.
1.620     albertel 5258:     #$namespace=$env{'request.course.id'};
1.168     albertel 5259:     #if (!$namespace) {
1.620     albertel 5260:       $namespace=$env{'request.state'};
1.168     albertel 5261:     #}
                   5262:   }
                   5263:   $namespace=~s/\//\_/g;
                   5264:   $namespace=~s/\W//g;
1.620     albertel 5265:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5266:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5267:   if ($domain eq 'public' && $stuname eq 'public') {
                   5268:       $stuname=$ENV{'REMOTE_ADDR'};
                   5269:   }
1.168     albertel 5270:   my $now=time;
                   5271:   my %hash;
1.1117    foxr     5272:   my $path=LONCAPA::tempdir();
1.168     albertel 5273:   if (tie(%hash,'GDBM_File',
                   5274: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5275: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5276:     $hash{"version:$symb"}++;
                   5277:     my $version=$hash{"version:$symb"};
                   5278:     my $allkeys=''; 
                   5279:     foreach my $key (keys(%$storehash)) {
                   5280:       $allkeys.=$key.':';
1.591     albertel 5281:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5282:     }
                   5283:     $hash{"$version:$symb:timestamp"}=$now;
                   5284:     $allkeys.='timestamp';
                   5285:     $hash{"$version:keys:$symb"}=$allkeys;
                   5286:     if (untie(%hash)) {
                   5287:       return 'ok';
                   5288:     } else {
                   5289:       return "error:$!";
                   5290:     }
                   5291:   } else {
                   5292:     return "error:$!";
                   5293:   }
                   5294: }
1.167     albertel 5295: 
1.168     albertel 5296: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5297: 
1.168     albertel 5298: sub tmprestore {
                   5299:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5300: 
1.168     albertel 5301:   if (!$symb) {
                   5302:     $symb=&symbread();
1.620     albertel 5303:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5304:   }
                   5305:   $symb=escape($symb);
                   5306: 
1.620     albertel 5307:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5308: 
1.620     albertel 5309:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5310:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5311:   if ($domain eq 'public' && $stuname eq 'public') {
                   5312:       $stuname=$ENV{'REMOTE_ADDR'};
                   5313:   }
1.168     albertel 5314:   my %returnhash;
                   5315:   $namespace=~s/\//\_/g;
                   5316:   $namespace=~s/\W//g;
                   5317:   my %hash;
1.1117    foxr     5318:   my $path=LONCAPA::tempdir();
1.168     albertel 5319:   if (tie(%hash,'GDBM_File',
                   5320: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5321: 	  &GDBM_READER(),0640)) {
1.168     albertel 5322:     my $version=$hash{"version:$symb"};
                   5323:     $returnhash{'version'}=$version;
                   5324:     my $scope;
                   5325:     for ($scope=1;$scope<=$version;$scope++) {
                   5326:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5327:       my @keys=split(/:/,$vkeys);
                   5328:       my $key;
                   5329:       $returnhash{"$scope:keys"}=$vkeys;
                   5330:       foreach $key (@keys) {
1.591     albertel 5331: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5332: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5333:       }
                   5334:     }
1.168     albertel 5335:     if (!(untie(%hash))) {
                   5336:       return "error:$!";
                   5337:     }
                   5338:   } else {
                   5339:     return "error:$!";
                   5340:   }
                   5341:   return %returnhash;
1.167     albertel 5342: }
                   5343: 
1.9       www      5344: # ----------------------------------------------------------------------- Store
                   5345: 
                   5346: sub store {
1.1172.2.64  raeburn  5347:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5348:     my $home='';
                   5349: 
1.168     albertel 5350:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5351: 
1.213     www      5352:     $symb=&symbclean($symb);
1.122     albertel 5353:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5354: 
1.620     albertel 5355:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5356:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5357: 
                   5358:     &devalidate($symb,$stuname,$domain);
1.109     www      5359: 
                   5360:     $symb=escape($symb);
1.187     www      5361:     if (!$namespace) { 
1.620     albertel 5362:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5363:           return ''; 
                   5364:        } 
                   5365:     }
1.620     albertel 5366:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5367: 
                   5368:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5369:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5370: 
1.12      www      5371:     my $namevalue='';
1.800     albertel 5372:     foreach my $key (keys(%$storehash)) {
                   5373:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5374:     }
1.12      www      5375:     $namevalue=~s/\&$//;
1.187     www      5376:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  5377:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5378: }
                   5379: 
1.47      www      5380: # -------------------------------------------------------------- Critical Store
                   5381: 
                   5382: sub cstore {
1.1172.2.64  raeburn  5383:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5384:     my $home='';
                   5385: 
1.168     albertel 5386:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5387: 
1.213     www      5388:     $symb=&symbclean($symb);
1.122     albertel 5389:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5390: 
1.620     albertel 5391:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5392:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5393: 
                   5394:     &devalidate($symb,$stuname,$domain);
1.109     www      5395: 
                   5396:     $symb=escape($symb);
1.187     www      5397:     if (!$namespace) { 
1.620     albertel 5398:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5399:           return ''; 
                   5400:        } 
                   5401:     }
1.620     albertel 5402:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5403: 
                   5404:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5405:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5406: 
1.47      www      5407:     my $namevalue='';
1.800     albertel 5408:     foreach my $key (keys(%$storehash)) {
                   5409:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5410:     }
1.47      www      5411:     $namevalue=~s/\&$//;
1.187     www      5412:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5413:     return critical
1.1172.2.64  raeburn  5414:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5415: }
                   5416: 
1.9       www      5417: # --------------------------------------------------------------------- Restore
                   5418: 
                   5419: sub restore {
1.124     www      5420:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5421:     my $home='';
                   5422: 
1.168     albertel 5423:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5424: 
1.122     albertel 5425:     if (!$symb) {
1.1172.2.26  raeburn  5426:         return if ($namespace eq 'courserequests');
                   5427:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5428:     } else {
1.1172.2.26  raeburn  5429:         unless ($namespace eq 'courserequests') {
                   5430:             $symb=&escape(&symbclean($symb));
                   5431:         }
1.122     albertel 5432:     }
1.188     www      5433:     if (!$namespace) { 
1.620     albertel 5434:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5435:           return ''; 
                   5436:        } 
                   5437:     }
1.620     albertel 5438:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5439:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5440:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5441:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5442: 
1.12      www      5443:     my %returnhash=();
1.800     albertel 5444:     foreach my $line (split(/\&/,$answer)) {
                   5445: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5446:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5447:     }
1.75      www      5448:     my $version;
                   5449:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5450:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5451:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5452:        }
1.75      www      5453:     }
1.13      www      5454:     return %returnhash;
1.34      www      5455: }
                   5456: 
                   5457: # ---------------------------------------------------------- Course Description
1.1118    foxr     5458: #
                   5459: #  
1.34      www      5460: 
                   5461: sub coursedescription {
1.731     albertel 5462:     my ($courseid,$args)=@_;
1.34      www      5463:     $courseid=~s/^\///;
1.49      www      5464:     $courseid=~s/\_/\//g;
1.34      www      5465:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5466:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5467:     my $normalid=$cdomain.'_'.$cnum;
                   5468:     # need to always cache even if we get errors otherwise we keep 
                   5469:     # trying and trying and trying to get the course description.
                   5470:     my %envhash=();
                   5471:     my %returnhash=();
1.731     albertel 5472:     
                   5473:     my $expiretime=600;
                   5474:     if ($env{'request.course.id'} eq $normalid) {
                   5475: 	$expiretime=120;
                   5476:     }
                   5477: 
                   5478:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5479:     if (!$args->{'freshen_cache'}
                   5480: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5481: 	foreach my $key (keys(%env)) {
                   5482: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5483: 	    my ($setting) = $1;
                   5484: 	    $returnhash{$setting} = $env{$key};
                   5485: 	}
                   5486: 	return %returnhash;
                   5487:     }
                   5488: 
1.1118    foxr     5489:     # get the data again
                   5490: 
1.731     albertel 5491:     if (!$args->{'one_time'}) {
                   5492: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5493:     }
1.811     albertel 5494: 
1.34      www      5495:     if ($chome ne 'no_host') {
1.302     albertel 5496:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5497:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5498: 	   my $username = $env{'user.name'}; # Defult username
                   5499: 	   if(defined $args->{'user'}) {
                   5500: 	       $username = $args->{'user'};
                   5501: 	   }
1.129     albertel 5502:            $returnhash{'home'}= $chome;
                   5503: 	   $returnhash{'domain'} = $cdomain;
                   5504: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5505:            if (!defined($returnhash{'type'})) {
                   5506:                $returnhash{'type'} = 'Course';
                   5507:            }
1.130     albertel 5508:            while (my ($name,$value) = each %returnhash) {
1.53      www      5509:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5510:            }
1.270     www      5511:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5512:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5513: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5514:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5515:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5516:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5517:        }
                   5518:     }
1.731     albertel 5519:     if (!$args->{'one_time'}) {
1.949     raeburn  5520: 	&appenv(\%envhash);
1.731     albertel 5521:     }
1.302     albertel 5522:     return %returnhash;
1.461     www      5523: }
                   5524: 
1.1080    raeburn  5525: sub update_released_required {
                   5526:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5527:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5528:         $cid = $env{'request.course.id'};
                   5529:         $cdom = $env{'course.'.$cid.'.domain'};
                   5530:         $cnum = $env{'course.'.$cid.'.num'};
                   5531:         $chome = $env{'course.'.$cid.'.home'};
                   5532:     }
                   5533:     if ($needsrelease) {
                   5534:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5535:         my $needsupdate;
                   5536:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5537:             $needsupdate = 1;
                   5538:         } else {
                   5539:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5540:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5541:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5542:                 $needsupdate = 1;
                   5543:             }
                   5544:         }
                   5545:         if ($needsupdate) {
                   5546:             my %needshash = (
                   5547:                              'internal.releaserequired' => $needsrelease,
                   5548:                             );
                   5549:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5550:             if ($putresult eq 'ok') {
                   5551:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5552:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5553:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5554:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5555:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5556:                 }
                   5557:             }
                   5558:         }
                   5559:     }
                   5560:     return;
                   5561: }
                   5562: 
1.461     www      5563: # -------------------------------------------------See if a user is privileged
                   5564: 
                   5565: sub privileged {
1.1172.2.23  raeburn  5566:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5567:     my $now = time;
1.1172.2.23  raeburn  5568:     my $roles;
                   5569:     if (ref($possroles) eq 'ARRAY') {
                   5570:         $roles = $possroles;
                   5571:     } else {
                   5572:         $roles = ['dc','su'];
                   5573:     }
                   5574:     if (ref($possdomains) eq 'ARRAY') {
                   5575:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5576:         foreach my $dom (@{$possdomains}) {
                   5577:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5578:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5579:                 foreach my $role (@{$roles}) {
                   5580:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5581:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5582:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5583:                             return 1 unless (($end && $end < $now) ||
                   5584:                                              ($start && $start > $now));
                   5585:                         }
                   5586:                     }
                   5587:                 }
                   5588:             }
                   5589:         }
                   5590:     } else {
                   5591:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5592:         my $now = time;
1.1170    droeschl 5593: 
1.1172.2.58  raeburn  5594:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5595:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  5596:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   5597:                 return 1 unless ($tend && $tend < $now)
                   5598:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5599:             }
1.1172.2.23  raeburn  5600:         }
                   5601:     }
1.461     www      5602:     return 0;
1.9       www      5603: }
1.1       albertel 5604: 
1.1172.2.23  raeburn  5605: sub privileged_by_domain {
                   5606:     my ($domains,$roles) = @_;
                   5607:     my %privileged = ();
                   5608:     my $cachetime = 60*60*24;
                   5609:     my $now = time;
                   5610:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5611:         return %privileged;
                   5612:     }
                   5613:     foreach my $dom (@{$domains}) {
                   5614:         next if (ref($privileged{$dom}) eq 'HASH');
                   5615:         my $needroles;
                   5616:         foreach my $role (@{$roles}) {
                   5617:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5618:             if (defined($cached)) {
                   5619:                 if (ref($result) eq 'HASH') {
                   5620:                     $privileged{$dom}{$role} = $result;
                   5621:                 }
                   5622:             } else {
                   5623:                 $needroles = 1;
                   5624:             }
                   5625:         }
                   5626:         if ($needroles) {
                   5627:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5628:             $privileged{$dom} = {};
                   5629:             foreach my $server (keys(%dompersonnel)) {
                   5630:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5631:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5632:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5633:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5634:                         next if ($end && $end < $now);
                   5635:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   5636:                             $dompersonnel{$server}{$item};
                   5637:                     }
                   5638:                 }
                   5639:             }
                   5640:             if (ref($privileged{$dom}) eq 'HASH') {
                   5641:                 foreach my $role (@{$roles}) {
                   5642:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5643:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5644:                     } else {
                   5645:                         my %hash = ();
                   5646:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5647:                     }
                   5648:                 }
                   5649:             }
                   5650:         }
                   5651:     }
                   5652:     return %privileged;
                   5653: }
                   5654: 
1.103     harris41 5655: # -------------------------------------------------------- Get user privileges
1.11      www      5656: 
                   5657: sub rolesinit {
1.1169    droeschl 5658:     my ($domain, $username) = @_;
                   5659:     my %userroles = ('user.login.time' => time);
                   5660:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5661: 
                   5662:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5663:     # also, blocking can be triggered by an activating timer
                   5664:     # it's saved in the user's %env.
                   5665:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5666:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5667:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5668:         %timerintchk, %timerintenv);
                   5669: 
1.1162    raeburn  5670:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5671:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5672:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5673:     }
1.1169    droeschl 5674: 
1.1162    raeburn  5675:     foreach my $key (keys(%timerinterval)) {
                   5676:         my ($cid,$rest) = split(/\0/,$key);
                   5677:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5678:     }
1.1169    droeschl 5679: 
1.11      www      5680:     my %allroles=();
1.1162    raeburn  5681:     my %allgroups=();
1.11      www      5682: 
1.1172.2.58  raeburn  5683:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5684:         my $role = $rolesdump{$area};
                   5685:         $area =~ s/\_\w\w$//;
                   5686: 
                   5687:         my ($trole, $tend, $tstart, $group_privs);
                   5688: 
                   5689:         if ($role =~ /^cr/) {
                   5690:         # Custom role, defined by a user 
                   5691:         # e.g., user.role.cr/msu/smith/mynewrole
                   5692:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5693:                 $trole = $1;
                   5694:                 ($tend, $tstart) = split('_', $2);
                   5695:             } else {
                   5696:                 $trole = $role;
                   5697:             }
                   5698:         } elsif ($role =~ m|^gr/|) {
                   5699:         # Role of member in a group, defined within a course/community
                   5700:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5701:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5702:             next if $tstart eq '-1';
                   5703:             ($trole, $group_privs) = split(/\//, $trole);
                   5704:             $group_privs = &unescape($group_privs);
                   5705:         } else {
                   5706:         # Just a normal role, defined in roles.tab
                   5707:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5708:         }
                   5709: 
                   5710:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5711:                  $username);
                   5712:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5713: 
                   5714:         # role expired or not available yet?
                   5715:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5716:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5717: 
                   5718:         next if $area eq '' or $trole eq '';
                   5719: 
                   5720:         my $spec = "$trole.$area";
                   5721:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5722: 
                   5723:         if ($trole =~ /^cr\//) {
                   5724:         # Custom role, defined by a user
                   5725:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5726:         } elsif ($trole eq 'gr') {
                   5727:         # Role of a member in a group, defined within a course/community
                   5728:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5729:             next;
                   5730:         } else {
                   5731:         # Normal role, defined in roles.tab
                   5732:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5733:         }
                   5734: 
                   5735:         my $cid = $tdomain.'_'.$trest;
                   5736:         unless ($firstaccchk{$cid}) {
                   5737:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5738:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5739:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5740:                         $coursetimerstarts{$cid}{$item}; 
                   5741:                 }
                   5742:             }
                   5743:             $firstaccchk{$cid} = 1;
                   5744:         }
                   5745:         unless ($timerintchk{$cid}) {
                   5746:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5747:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5748:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5749:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5750:                 }
1.12      www      5751:             }
1.1169    droeschl 5752:             $timerintchk{$cid} = 1;
1.191     harris41 5753:         }
1.11      www      5754:     }
1.1169    droeschl 5755: 
1.1172.2.91  raeburn  5756:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   5757:                                                           \%allroles, \%allgroups);
1.1169    droeschl 5758:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  5759:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 5760: 
1.1162    raeburn  5761:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5762: }
                   5763: 
1.567     raeburn  5764: sub set_arearole {
1.1172.2.19  raeburn  5765:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5766:     unless ($nolog) {
1.567     raeburn  5767: # log the associated role with the area
1.1172.2.19  raeburn  5768:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5769:     }
1.743     albertel 5770:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5771: }
                   5772: 
                   5773: sub custom_roleprivs {
                   5774:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5775:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  5776:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5777:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5778:         my ($rdummy,$roledef)=
                   5779:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5780:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5781:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5782:             if (defined($syspriv)) {
1.1043    raeburn  5783:                 if ($trest =~ /^$match_community$/) {
                   5784:                     $syspriv =~ s/bre\&S//; 
                   5785:                 }
1.567     raeburn  5786:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5787:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5788:             }
                   5789:             if ($tdomain ne '') {
                   5790:                 if (defined($dompriv)) {
                   5791:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5792:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5793:                 }
                   5794:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  5795:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   5796:                         my $rolename = $1;
                   5797:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   5798:                     }
1.567     raeburn  5799:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5800:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5801:                 }
                   5802:             }
                   5803:         }
                   5804:     }
                   5805: }
                   5806: 
1.1172.2.89  raeburn  5807: sub course_adhocrole_privs {
                   5808:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   5809:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   5810:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   5811:         my (%currprivs,%storeprivs);
                   5812:         foreach my $item (split(/:/,$coursepriv)) {
                   5813:             my ($priv,$restrict) = split(/\&/,$item);
                   5814:             $currprivs{$priv} = $restrict;
                   5815:         }
                   5816:         my (%possadd,%possremove,%full);
                   5817:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   5818:             my ($priv,$restrict)=split(/\&/,$item);
                   5819:             $full{$priv} = $restrict;
                   5820:         }
                   5821:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   5822:              next if ($item eq '');
                   5823:              my ($rule,$rest) = split(/=/,$item);
                   5824:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   5825:              foreach my $priv (split(/:/,$rest)) {
                   5826:                  if ($priv ne '') {
                   5827:                      if ($rule eq 'off') {
                   5828:                          $possremove{$priv} = 1;
                   5829:                      } else {
                   5830:                          $possadd{$priv} = 1;
                   5831:                      }
                   5832:                  }
                   5833:              }
                   5834:          }
                   5835:          foreach my $priv (sort(keys(%full))) {
                   5836:              if (exists($currprivs{$priv})) {
                   5837:                  unless (exists($possremove{$priv})) {
                   5838:                      $storeprivs{$priv} = $currprivs{$priv};
                   5839:                  }
                   5840:              } elsif (exists($possadd{$priv})) {
                   5841:                  $storeprivs{$priv} = $full{$priv};
                   5842:              }
                   5843:          }
                   5844:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   5845:      }
                   5846:      return $coursepriv;
                   5847: }
                   5848: 
1.678     raeburn  5849: sub group_roleprivs {
                   5850:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5851:     my $access = 1;
                   5852:     my $now = time;
                   5853:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5854:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5855:     if ($access) {
1.811     albertel 5856:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5857:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5858:     }
                   5859: }
1.567     raeburn  5860: 
                   5861: sub standard_roleprivs {
                   5862:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5863:     if (defined($pr{$trole.':s'})) {
                   5864:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5865:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5866:     }
                   5867:     if ($tdomain ne '') {
                   5868:         if (defined($pr{$trole.':d'})) {
                   5869:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5870:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5871:         }
                   5872:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5873:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5874:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5875:         }
                   5876:     }
                   5877: }
                   5878: 
                   5879: sub set_userprivs {
1.1064    raeburn  5880:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5881:     my $author=0;
                   5882:     my $adv=0;
1.1172.2.91  raeburn  5883:     my $rar=0;
1.678     raeburn  5884:     my %grouproles = ();
                   5885:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5886:         my @groupkeys; 
1.1000    raeburn  5887:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5888:             push(@groupkeys,$role);
                   5889:         }
                   5890:         if (ref($groups_roles) eq 'HASH') {
                   5891:             foreach my $key (keys(%{$groups_roles})) {
                   5892:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5893:                     push(@groupkeys,$key);
                   5894:                 }
                   5895:             }
                   5896:         }
                   5897:         if (@groupkeys > 0) {
                   5898:             foreach my $role (@groupkeys) {
                   5899:                 my ($trole,$area,$sec,$extendedarea);
                   5900:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5901:                     $trole = $1;
                   5902:                     $area = $2;
                   5903:                     $sec = $3;
                   5904:                     $extendedarea = $area.$sec;
                   5905:                     if (exists($$allgroups{$area})) {
                   5906:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5907:                             my $spec = $trole.'.'.$extendedarea;
                   5908:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5909:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5910:                         }
1.678     raeburn  5911:                     }
                   5912:                 }
                   5913:             }
                   5914:         }
                   5915:     }
1.800     albertel 5916:     foreach my $group (keys(%grouproles)) {
                   5917:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5918:     }
1.800     albertel 5919:     foreach my $role (keys(%{$allroles})) {
                   5920:         my %thesepriv;
1.941     raeburn  5921:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5922:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5923:             if ($item ne '') {
                   5924:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5925:                 if ($restrictions eq '') {
                   5926:                     $thesepriv{$privilege}='F';
                   5927:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5928:                     $thesepriv{$privilege}.=$restrictions;
                   5929:                 }
                   5930:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  5931:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  5932:             }
                   5933:         }
                   5934:         my $thesestr='';
1.1104    raeburn  5935:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5936: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5937: 	}
                   5938:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5939:     }
1.1172.2.91  raeburn  5940:     return ($author,$adv,$rar);
1.567     raeburn  5941: }
                   5942: 
1.994     raeburn  5943: sub role_status {
1.1104    raeburn  5944:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5945:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  5946:         my ($one,$two) = split(m{\./},$rolekey,2);
                   5947:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  5948:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  5949:             $$where = '/'.$two;
1.994     raeburn  5950:             $$trolecode=$$role.'.'.$$where;
                   5951:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5952:             $$tstatus='is';
1.1104    raeburn  5953:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5954:                 $$tstatus='future';
1.1034    raeburn  5955:                 if ($$tstart<$now) {
                   5956:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5957:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5958:                             my (%allroles,%allgroups,$group_privs,
                   5959:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5960:                             my %userroles = (
                   5961:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5962:                             );
1.1064    raeburn  5963:                             @rolecodes = ('cm'); 
1.1002    raeburn  5964:                             my $spec=$$role.'.'.$$where;
                   5965:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5966:                             if ($$role =~ /^cr\//) {
                   5967:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5968:                                 push(@rolecodes,'cr');
1.1002    raeburn  5969:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5970:                                 push(@rolecodes,$$role);
1.1002    raeburn  5971:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5972:                                                     $env{'user.name'});
1.1064    raeburn  5973:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5974:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5975:                                 $group_privs = &unescape($group_privs);
                   5976:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5977:                                 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  5978:                                 &get_groups_roles($tdomain,$trest,
                   5979:                                                   \%course_roles,\@rolecodes,
                   5980:                                                   \%groups_roles);
1.1002    raeburn  5981:                             } else {
1.1064    raeburn  5982:                                 push(@rolecodes,$$role);
1.1002    raeburn  5983:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5984:                             }
1.1172.2.91  raeburn  5985:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   5986:                                                                    \%groups_roles);
1.1064    raeburn  5987:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  5988:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  5989:                         }
                   5990:                     }
1.1034    raeburn  5991:                     $$tstatus = 'is';
1.1002    raeburn  5992:                 }
1.994     raeburn  5993:             }
                   5994:             if ($$tend) {
1.1104    raeburn  5995:                 if ($$tend<$update) {
1.994     raeburn  5996:                     $$tstatus='expired';
                   5997:                 } elsif ($$tend<$now) {
                   5998:                     $$tstatus='will_not';
                   5999:                 }
                   6000:             }
                   6001:         }
                   6002:     }
                   6003: }
                   6004: 
1.1104    raeburn  6005: sub get_groups_roles {
                   6006:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6007:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6008:                   (ref($rolecodes) eq 'ARRAY') && 
                   6009:                   (ref($groups_roles) eq 'HASH')); 
                   6010:     if (keys(%{$cdom_courseroles}) > 0) {
                   6011:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6012:         if ($cdom ne '' && $cnum ne '') {
                   6013:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6014:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6015:                     my $crsrole = $1;
                   6016:                     my $crssec = $2;
                   6017:                     if ($crsrole =~ /^cr/) {
                   6018:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6019:                             push(@{$rolecodes},'cr');
                   6020:                         }
                   6021:                     } else {
                   6022:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6023:                             push(@{$rolecodes},$crsrole);
                   6024:                         }
                   6025:                     }
                   6026:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6027:                     if ($crssec ne '') {
                   6028:                         $rolekey .= "/$crssec";
                   6029:                     }
                   6030:                     $rolekey .= './';
                   6031:                     $groups_roles->{$rolekey} = $rolecodes;
                   6032:                 }
                   6033:             }
                   6034:         }
                   6035:     }
                   6036:     return;
                   6037: }
                   6038: 
                   6039: sub delete_env_groupprivs {
                   6040:     my ($where,$courseroles,$possroles) = @_;
                   6041:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6042:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6043:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6044:         %{$courseroles->{$udom}} =
                   6045:             &get_my_roles('','','userroles',['active'],
                   6046:                           $possroles,[$udom],1);
                   6047:     }
                   6048:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6049:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6050:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6051:             my $area = '/'.$cdom.'/'.$cnum;
                   6052:             my $privkey = "user.priv.$crsrole.$area";
                   6053:             if ($crssec ne '') {
                   6054:                 $privkey .= '/'.$crssec;
                   6055:             }
                   6056:             $privkey .= ".$area/$group";
                   6057:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6058:         }
                   6059:     }
                   6060:     return;
                   6061: }
                   6062: 
1.994     raeburn  6063: sub check_adhoc_privs {
1.1172.2.86  raeburn  6064:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6065:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6066:     if ($sec) {
                   6067:         $cckey .= '/'.$sec;
                   6068:     }
1.1172.2.9  raeburn  6069:     my $setprivs;
1.994     raeburn  6070:     if ($env{$cckey}) {
                   6071:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6072:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6073:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6074:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6075:             $setprivs = 1;
1.994     raeburn  6076:         }
                   6077:     } else {
1.1172.2.87  raeburn  6078:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6079:         $setprivs = 1;
1.994     raeburn  6080:     }
1.1172.2.9  raeburn  6081:     return $setprivs;
1.994     raeburn  6082: }
                   6083: 
                   6084: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6085: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6086:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6087:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6088:     if ($sec ne '') {
                   6089:         $area .= '/'.$sec;
                   6090:     }
1.994     raeburn  6091:     my $spec = $role.'.'.$area;
                   6092:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6093:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6094:     my %rolehash = ();
1.1172.2.89  raeburn  6095:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6096:         my $rolename = $1;
1.1172.2.84  raeburn  6097:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6098:         my %domdef = &get_domain_defaults($dcdom);
                   6099:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6100:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6101:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6102:             }
                   6103:         }
1.1172.2.84  raeburn  6104:     } else {
                   6105:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6106:     }
1.1172.2.91  raeburn  6107:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6108:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6109:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6110:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6111:         &appenv( {'request.role'        => $spec,
                   6112:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6113:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6114:                  }
                   6115:                );
                   6116:         my $tadv=0;
                   6117:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6118:         &appenv({'request.role.adv'    => $tadv});
                   6119:     }
1.994     raeburn  6120: }
                   6121: 
1.12      www      6122: # --------------------------------------------------------------- get interface
                   6123: 
                   6124: sub get {
1.131     albertel 6125:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6126:    my $items='';
1.800     albertel 6127:    foreach my $item (@$storearr) {
                   6128:        $items.=&escape($item).'&';
1.191     harris41 6129:    }
1.12      www      6130:    $items=~s/\&$//;
1.620     albertel 6131:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6132:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6133:    my $uhome=&homeserver($uname,$udomain);
                   6134: 
1.133     albertel 6135:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6136:    my @pairs=split(/\&/,$rep);
1.273     albertel 6137:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6138:      return @pairs;
                   6139:    }
1.15      www      6140:    my %returnhash=();
1.42      www      6141:    my $i=0;
1.800     albertel 6142:    foreach my $item (@$storearr) {
                   6143:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6144:       $i++;
1.191     harris41 6145:    }
1.15      www      6146:    return %returnhash;
1.27      www      6147: }
                   6148: 
                   6149: # --------------------------------------------------------------- del interface
                   6150: 
                   6151: sub del {
1.133     albertel 6152:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6153:    my $items='';
1.800     albertel 6154:    foreach my $item (@$storearr) {
                   6155:        $items.=&escape($item).'&';
1.191     harris41 6156:    }
1.984     neumanie 6157: 
1.27      www      6158:    $items=~s/\&$//;
1.620     albertel 6159:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6160:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6161:    my $uhome=&homeserver($uname,$udomain);
                   6162:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6163: }
                   6164: 
                   6165: # -------------------------------------------------------------- dump interface
                   6166: 
1.1172.2.22  raeburn  6167: sub unserialize {
                   6168:     my ($rep, $escapedkeys) = @_;
                   6169: 
                   6170:     return {} if $rep =~ /^error/;
                   6171: 
                   6172:     my %returnhash=();
                   6173:     foreach my $item (split(/\&/,$rep)) {
                   6174:         my ($key, $value) = split(/=/, $item, 2);
                   6175:         $key = unescape($key) unless $escapedkeys;
                   6176:         next if $key =~ /^error: 2 /;
                   6177:         $returnhash{$key} = &thaw_unescape($value);
                   6178:     }
                   6179:     return \%returnhash;
                   6180: }
                   6181: 
                   6182: # see Lond::dump_with_regexp
                   6183: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6184: sub dump {
1.1172.2.22  raeburn  6185:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6186:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6187:     if (!$uname) { $uname=$env{'user.name'}; }
                   6188:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6189: 
1.1172.2.55  raeburn  6190:     if ($regexp) {
                   6191:         $regexp=&escape($regexp);
                   6192:     } else {
                   6193:         $regexp='.';
                   6194:     }
1.1172.2.22  raeburn  6195:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   6196:         # user is hosted on this machine
1.1172.2.55  raeburn  6197:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  6198:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  6199:         return %{&unserialize($reply, $escapedkeys)};
                   6200:     }
1.1166    raeburn  6201:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6202:     my @pairs=split(/\&/,$rep);
                   6203:     my %returnhash=();
1.1098    foxr     6204:     if (!($rep =~ /^error/ )) {
                   6205: 	foreach my $item (@pairs) {
                   6206: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  6207:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     6208: 	    next if ($key =~ /^error: 2 /);
                   6209: 	    $returnhash{$key}=&thaw_unescape($value);
                   6210: 	}
1.755     albertel 6211:     }
                   6212:     return %returnhash;
1.407     www      6213: }
                   6214: 
1.1098    foxr     6215: 
1.717     albertel 6216: # --------------------------------------------------------- dumpstore interface
                   6217: 
                   6218: sub dumpstore {
                   6219:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  6220:    # same as dump but keys must be escaped. They may contain colon separated
                   6221:    # lists of values that may themself contain colons (e.g. symbs).
                   6222:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6223: }
                   6224: 
1.407     www      6225: # -------------------------------------------------------------- keys interface
                   6226: 
                   6227: sub getkeys {
                   6228:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6229:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6230:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6231:    my $uhome=&homeserver($uname,$udomain);
                   6232:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6233:    my @keyarray=();
1.800     albertel 6234:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6235:       next if ($key =~ /^error: 2 /);
1.800     albertel 6236:       push(@keyarray,&unescape($key));
1.407     www      6237:    }
                   6238:    return @keyarray;
1.318     matthew  6239: }
                   6240: 
1.319     matthew  6241: # --------------------------------------------------------------- currentdump
                   6242: sub currentdump {
1.328     matthew  6243:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6244:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6245:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6246:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6247:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  6248:    my $rep;
                   6249: 
                   6250:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6251:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   6252:                    $courseid)));
                   6253:    } else {
                   6254:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6255:    }
                   6256: 
1.318     matthew  6257:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6258:    #
1.318     matthew  6259:    my %returnhash=();
1.319     matthew  6260:    #
1.1172.2.93.4  2(raebur 6261:7):    if ($rep eq 'unknown_cmd') { 
1.319     matthew  6262:        # an old lond will not know currentdump
                   6263:        # Do a dump and make it look like a currentdump
1.822     albertel 6264:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6265:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6266:        my %hash = @tmp;
                   6267:        @tmp=();
1.424     matthew  6268:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6269:    } else {
                   6270:        my @pairs=split(/\&/,$rep);
1.800     albertel 6271:        foreach my $pair (@pairs) {
                   6272:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6273:            my ($symb,$param) = split(/:/,$key);
                   6274:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6275:                                                         &thaw_unescape($value);
1.319     matthew  6276:        }
1.191     harris41 6277:    }
1.12      www      6278:    return %returnhash;
1.424     matthew  6279: }
                   6280: 
                   6281: sub convert_dump_to_currentdump{
                   6282:     my %hash = %{shift()};
                   6283:     my %returnhash;
                   6284:     # Code ripped from lond, essentially.  The only difference
                   6285:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6286:     # we might run in to problems with parameter names =~ /^v\./
                   6287:     while (my ($key,$value) = each(%hash)) {
                   6288:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6289: 	$symb  = &unescape($symb);
                   6290: 	$param = &unescape($param);
1.424     matthew  6291:         next if ($v eq 'version' || $symb eq 'keys');
                   6292:         next if (exists($returnhash{$symb}) &&
                   6293:                  exists($returnhash{$symb}->{$param}) &&
                   6294:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6295:         $returnhash{$symb}->{$param}=$value;
                   6296:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6297:     }
                   6298:     #
                   6299:     # Remove all of the keys in the hashes which keep track of
                   6300:     # the version of the parameter.
                   6301:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6302:         # use a foreach because we are going to delete from the hash.
                   6303:         foreach my $key (keys(%$param_hash)) {
                   6304:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6305:         }
                   6306:     }
                   6307:     return \%returnhash;
1.12      www      6308: }
                   6309: 
1.627     albertel 6310: # ------------------------------------------------------ critical inc interface
                   6311: 
                   6312: sub cinc {
                   6313:     return &inc(@_,'critical');
                   6314: }
                   6315: 
1.449     matthew  6316: # --------------------------------------------------------------- inc interface
                   6317: 
                   6318: sub inc {
1.627     albertel 6319:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6320:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6321:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6322:     my $uhome=&homeserver($uname,$udomain);
                   6323:     my $items='';
                   6324:     if (! ref($store)) {
                   6325:         # got a single value, so use that instead
                   6326:         $items = &escape($store).'=&';
                   6327:     } elsif (ref($store) eq 'SCALAR') {
                   6328:         $items = &escape($$store).'=&';        
                   6329:     } elsif (ref($store) eq 'ARRAY') {
                   6330:         $items = join('=&',map {&escape($_);} @{$store});
                   6331:     } elsif (ref($store) eq 'HASH') {
                   6332:         while (my($key,$value) = each(%{$store})) {
                   6333:             $items.= &escape($key).'='.&escape($value).'&';
                   6334:         }
                   6335:     }
                   6336:     $items=~s/\&$//;
1.627     albertel 6337:     if ($critical) {
                   6338: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6339:     } else {
                   6340: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6341:     }
1.449     matthew  6342: }
                   6343: 
1.12      www      6344: # --------------------------------------------------------------- put interface
                   6345: 
                   6346: sub put {
1.134     albertel 6347:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6348:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6349:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6350:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6351:    my $items='';
1.800     albertel 6352:    foreach my $item (keys(%$storehash)) {
                   6353:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6354:    }
1.12      www      6355:    $items=~s/\&$//;
1.134     albertel 6356:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6357: }
                   6358: 
1.631     albertel 6359: # ------------------------------------------------------------ newput interface
                   6360: 
                   6361: sub newput {
                   6362:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6363:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6364:    if (!$uname) { $uname=$env{'user.name'}; }
                   6365:    my $uhome=&homeserver($uname,$udomain);
                   6366:    my $items='';
                   6367:    foreach my $key (keys(%$storehash)) {
                   6368:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6369:    }
                   6370:    $items=~s/\&$//;
                   6371:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6372: }
                   6373: 
                   6374: # ---------------------------------------------------------  putstore interface
                   6375: 
1.524     raeburn  6376: sub putstore {
1.1172.2.59  raeburn  6377:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6378:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6379:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6380:    my $uhome=&homeserver($uname,$udomain);
                   6381:    my $items='';
1.715     albertel 6382:    foreach my $key (keys(%$storehash)) {
                   6383:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6384:    }
1.715     albertel 6385:    $items=~s/\&$//;
1.716     albertel 6386:    my $esc_symb=&escape($symb);
                   6387:    my $esc_v=&escape($version);
1.715     albertel 6388:    my $reply =
1.716     albertel 6389:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6390: 	      $uhome);
1.1172.2.59  raeburn  6391:    if (($tolog) && ($reply eq 'ok')) {
                   6392:        my $namevalue='';
                   6393:        foreach my $key (keys(%{$storehash})) {
                   6394:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6395:        }
                   6396:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6397:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6398:                      '&version='.$esc_v.
                   6399:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6400:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6401:    }
1.715     albertel 6402:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6403:        # gfall back to way things use to be done
1.715     albertel 6404:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6405: 			    $uname);
1.524     raeburn  6406:    }
1.715     albertel 6407:    return $reply;
                   6408: }
                   6409: 
                   6410: sub old_putstore {
1.716     albertel 6411:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6412:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6413:     if (!$uname) { $uname=$env{'user.name'}; }
                   6414:     my $uhome=&homeserver($uname,$udomain);
                   6415:     my %newstorehash;
1.800     albertel 6416:     foreach my $item (keys(%$storehash)) {
                   6417: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6418: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6419:     }
                   6420:     my $items='';
                   6421:     my %allitems = ();
1.800     albertel 6422:     foreach my $item (keys(%newstorehash)) {
                   6423: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6424: 	    my $key = $1.':keys:'.$2;
                   6425: 	    $allitems{$key} .= $3.':';
                   6426: 	}
1.800     albertel 6427: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6428:     }
1.800     albertel 6429:     foreach my $item (keys(%allitems)) {
                   6430: 	$allitems{$item} =~ s/\:$//;
                   6431: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6432:     }
                   6433:     $items=~s/\&$//;
                   6434:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6435: }
                   6436: 
1.47      www      6437: # ------------------------------------------------------ critical put interface
                   6438: 
                   6439: sub cput {
1.134     albertel 6440:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6441:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6442:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6443:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6444:    my $items='';
1.800     albertel 6445:    foreach my $item (keys(%$storehash)) {
                   6446:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6447:    }
1.47      www      6448:    $items=~s/\&$//;
1.134     albertel 6449:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6450: }
                   6451: 
                   6452: # -------------------------------------------------------------- eget interface
                   6453: 
                   6454: sub eget {
1.133     albertel 6455:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6456:    my $items='';
1.800     albertel 6457:    foreach my $item (@$storearr) {
                   6458:        $items.=&escape($item).'&';
1.191     harris41 6459:    }
1.12      www      6460:    $items=~s/\&$//;
1.620     albertel 6461:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6462:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6463:    my $uhome=&homeserver($uname,$udomain);
                   6464:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6465:    my @pairs=split(/\&/,$rep);
                   6466:    my %returnhash=();
1.42      www      6467:    my $i=0;
1.800     albertel 6468:    foreach my $item (@$storearr) {
                   6469:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6470:       $i++;
1.191     harris41 6471:    }
1.12      www      6472:    return %returnhash;
                   6473: }
                   6474: 
1.667     albertel 6475: # ------------------------------------------------------------ tmpput interface
                   6476: sub tmpput {
1.802     raeburn  6477:     my ($storehash,$server,$context)=@_;
1.667     albertel 6478:     my $items='';
1.800     albertel 6479:     foreach my $item (keys(%$storehash)) {
                   6480: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6481:     }
                   6482:     $items=~s/\&$//;
1.802     raeburn  6483:     if (defined($context)) {
                   6484:         $items .= ':'.&escape($context);
                   6485:     }
1.667     albertel 6486:     return &reply("tmpput:$items",$server);
                   6487: }
                   6488: 
                   6489: # ------------------------------------------------------------ tmpget interface
                   6490: sub tmpget {
1.688     albertel 6491:     my ($token,$server)=@_;
                   6492:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6493:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6494:     my %returnhash;
1.1172.2.85  raeburn  6495:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   6496:         return %returnhash;
                   6497:     }
1.667     albertel 6498:     foreach my $item (split(/\&/,$rep)) {
                   6499: 	my ($key,$value)=split(/=/,$item);
                   6500: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6501:     }
                   6502:     return %returnhash;
                   6503: }
                   6504: 
1.1113    raeburn  6505: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6506: sub tmpdel {
                   6507:     my ($token,$server)=@_;
                   6508:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6509:     return &reply("tmpdel:$token",$server);
                   6510: }
                   6511: 
1.1172.2.13  raeburn  6512: # ------------------------------------------------------------ get_timebased_id
                   6513: 
                   6514: sub get_timebased_id {
                   6515:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6516:         $maxtries) = @_;
                   6517:     my ($newid,$error,$dellock);
                   6518:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   6519:         return ('','ok','invalid call to get suffix');
                   6520:     }
                   6521: 
                   6522: # set defaults for any optional args for which values were not supplied
                   6523:     if ($who eq '') {
                   6524:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6525:     }
                   6526:     if (!$locktries) {
                   6527:         $locktries = 3;
                   6528:     }
                   6529:     if (!$maxtries) {
                   6530:         $maxtries = 10;
                   6531:     }
                   6532: 
                   6533:     if (($cdom eq '') || ($cnum eq '')) {
                   6534:         if ($env{'request.course.id'}) {
                   6535:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6536:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6537:         }
                   6538:         if (($cdom eq '') || ($cnum eq '')) {
                   6539:             return ('','ok','call to get suffix not in course context');
                   6540:         }
                   6541:     }
                   6542: 
                   6543: # construct locking item
                   6544:     my $lockhash = {
                   6545:                       $prefix."\0".'locked_'.$keyid => $who,
                   6546:                    };
                   6547:     my $tries = 0;
                   6548: 
                   6549: # attempt to get lock on nohist_$namespace file
                   6550:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6551:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6552:         $tries ++;
                   6553:         sleep 1;
                   6554:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6555:     }
                   6556: 
                   6557: # attempt to get unique identifier, based on current timestamp
                   6558:     if ($gotlock eq 'ok') {
                   6559:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6560:         my $id = time;
                   6561:         $newid = $id;
1.1172.2.56  raeburn  6562:         if ($idtype eq 'addcode') {
                   6563:             $newid .= &sixnum_code();
                   6564:         }
1.1172.2.13  raeburn  6565:         my $idtries = 0;
                   6566:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6567:             if ($idtype eq 'concat') {
                   6568:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  6569:             } elsif ($idtype eq 'addcode') {
                   6570:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  6571:             } else {
                   6572:                 $newid ++;
                   6573:             }
                   6574:             $idtries ++;
                   6575:         }
                   6576:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6577:             my %new_item =  (
                   6578:                               $prefix."\0".$newid => $who,
                   6579:                             );
                   6580:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6581:                                                  $cdom,$cnum);
                   6582:             if ($putresult ne 'ok') {
                   6583:                 undef($newid);
                   6584:                 $error = 'error saving new item: '.$putresult;
                   6585:             }
                   6586:         } else {
1.1172.2.56  raeburn  6587:              undef($newid);
1.1172.2.13  raeburn  6588:              $error = ('error: no unique suffix available for the new item ');
                   6589:         }
                   6590: #  remove lock
                   6591:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6592:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6593:     } else {
                   6594:         $error = "error: could not obtain lockfile\n";
                   6595:         $dellock = 'ok';
1.1172.2.58  raeburn  6596:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6597:             $dellock = 'nolock';
                   6598:         }
1.1172.2.13  raeburn  6599:     }
                   6600:     return ($newid,$dellock,$error);
                   6601: }
                   6602: 
1.1172.2.56  raeburn  6603: sub sixnum_code {
                   6604:     my $code;
                   6605:     for (0..6) {
                   6606:         $code .= int( rand(9) );
                   6607:     }
                   6608:     return $code;
                   6609: }
                   6610: 
1.765     albertel 6611: # -------------------------------------------------- portfolio access checking
                   6612: 
                   6613: sub portfolio_access {
1.1172.2.77  raeburn  6614:     my ($requrl,$clientip) = @_;
1.765     albertel 6615:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  6616:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6617:     if ($result) {
                   6618:         my %setters;
                   6619:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6620:             my ($startblock,$endblock) =
                   6621:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6622:             if ($startblock && $endblock) {
                   6623:                 return 'B';
                   6624:             }
                   6625:         } else {
                   6626:             my ($startblock,$endblock) =
                   6627:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6628:             if ($startblock && $endblock) {
                   6629:                 return 'B';
                   6630:             }
                   6631:         }
                   6632:     }
1.765     albertel 6633:     if ($result eq 'ok') {
1.766     albertel 6634:        return 'F';
1.765     albertel 6635:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6636:        return 'A';
1.765     albertel 6637:     }
1.766     albertel 6638:     return '';
1.765     albertel 6639: }
                   6640: 
                   6641: sub get_portfolio_access {
1.1172.2.77  raeburn  6642:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 6643: 
                   6644:     if (!ref($access_hash)) {
                   6645: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6646: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6647: 						   $file_name);
                   6648: 	$access_hash = $access_controls{$file_name};
                   6649:     }
                   6650: 
1.1172.2.77  raeburn  6651:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 6652:     my $now = time;
                   6653:     if (ref($access_hash) eq 'HASH') {
                   6654:         foreach my $key (keys(%{$access_hash})) {
                   6655:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6656:             if ($start > $now) {
                   6657:                 next;
                   6658:             }
                   6659:             if ($end && $end<$now) {
                   6660:                 next;
                   6661:             }
                   6662:             if ($scope eq 'public') {
                   6663:                 $public = $key;
                   6664:                 last;
                   6665:             } elsif ($scope eq 'guest') {
                   6666:                 $guest = $key;
                   6667:             } elsif ($scope eq 'domains') {
                   6668:                 push(@domains,$key);
                   6669:             } elsif ($scope eq 'users') {
                   6670:                 push(@users,$key);
                   6671:             } elsif ($scope eq 'course') {
                   6672:                 push(@courses,$key);
                   6673:             } elsif ($scope eq 'group') {
                   6674:                 push(@groups,$key);
1.1172.2.77  raeburn  6675:             } elsif ($scope eq 'ip') {
                   6676:                 push(@ips,$key);
1.765     albertel 6677:             }
                   6678:         }
                   6679:         if ($public) {
                   6680:             return 'ok';
1.1172.2.77  raeburn  6681:         } elsif (@ips > 0) {
                   6682:             my $allowed;
                   6683:             foreach my $ipkey (@ips) {
                   6684:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   6685:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   6686:                         $allowed = 1;
                   6687:                         last;
                   6688:                     }
                   6689:                 }
                   6690:             }
                   6691:             if ($allowed) {
                   6692:                 return 'ok';
                   6693:             }
1.765     albertel 6694:         }
                   6695:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6696:             if ($guest) {
                   6697:                 return $guest;
                   6698:             }
                   6699:         } else {
                   6700:             if (@domains > 0) {
                   6701:                 foreach my $domkey (@domains) {
                   6702:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6703:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6704:                             return 'ok';
                   6705:                         }
                   6706:                     }
                   6707:                 }
                   6708:             }
                   6709:             if (@users > 0) {
                   6710:                 foreach my $userkey (@users) {
1.865     raeburn  6711:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6712:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6713:                             if (ref($item) eq 'HASH') {
                   6714:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6715:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6716:                                     return 'ok';
                   6717:                                 }
                   6718:                             }
                   6719:                         }
                   6720:                     } 
1.765     albertel 6721:                 }
                   6722:             }
                   6723:             my %roleshash;
                   6724:             my @courses_and_groups = @courses;
                   6725:             push(@courses_and_groups,@groups); 
                   6726:             if (@courses_and_groups > 0) {
                   6727:                 my (%allgroups,%allroles); 
                   6728:                 my ($start,$end,$role,$sec,$group);
                   6729:                 foreach my $envkey (%env) {
1.1060    raeburn  6730:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6731:                         my $cid = $2.'_'.$3; 
                   6732:                         if ($1 eq 'gr') {
                   6733:                             $group = $4;
                   6734:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6735:                         } else {
                   6736:                             if ($4 eq '') {
                   6737:                                 $sec = 'none';
                   6738:                             } else {
                   6739:                                 $sec = $4;
                   6740:                             }
                   6741:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6742:                         }
1.811     albertel 6743:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6744:                         my $cid = $2.'_'.$3;
                   6745:                         if ($4 eq '') {
                   6746:                             $sec = 'none';
                   6747:                         } else {
                   6748:                             $sec = $4;
                   6749:                         }
                   6750:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6751:                     }
                   6752:                 }
                   6753:                 if (keys(%allroles) == 0) {
                   6754:                     return;
                   6755:                 }
                   6756:                 foreach my $key (@courses_and_groups) {
                   6757:                     my %content = %{$$access_hash{$key}};
                   6758:                     my $cnum = $content{'number'};
                   6759:                     my $cdom = $content{'domain'};
                   6760:                     my $cid = $cdom.'_'.$cnum;
                   6761:                     if (!exists($allroles{$cid})) {
                   6762:                         next;
                   6763:                     }    
                   6764:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6765:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6766:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6767:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6768:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6769:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6770:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6771:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6772:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6773:                                         if (grep/^all$/,@sections) {
                   6774:                                             return 'ok';
                   6775:                                         } else {
                   6776:                                             if (grep/^$sec$/,@sections) {
                   6777:                                                 return 'ok';
                   6778:                                             }
                   6779:                                         }
                   6780:                                     }
                   6781:                                 }
                   6782:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6783:                                     if (grep/^none$/,@groups) {
                   6784:                                         return 'ok';
                   6785:                                     }
                   6786:                                 } else {
                   6787:                                     if (grep/^all$/,@groups) {
                   6788:                                         return 'ok';
                   6789:                                     } 
                   6790:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6791:                                         if (grep/^$group$/,@groups) {
                   6792:                                             return 'ok';
                   6793:                                         }
                   6794:                                     }
                   6795:                                 } 
                   6796:                             }
                   6797:                         }
                   6798:                     }
                   6799:                 }
                   6800:             }
                   6801:             if ($guest) {
                   6802:                 return $guest;
                   6803:             }
                   6804:         }
                   6805:     }
                   6806:     return;
                   6807: }
                   6808: 
                   6809: sub course_group_datechecker {
                   6810:     my ($dates,$now,$status) = @_;
                   6811:     my ($start,$end) = split(/\./,$dates);
                   6812:     if (!$start && !$end) {
                   6813:         return 'ok';
                   6814:     }
                   6815:     if (grep/^active$/,@{$status}) {
                   6816:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6817:             return 'ok';
                   6818:         }
                   6819:     }
                   6820:     if (grep/^previous$/,@{$status}) {
                   6821:         if ($end > $now ) {
                   6822:             return 'ok';
                   6823:         }
                   6824:     }
                   6825:     if (grep/^future$/,@{$status}) {
                   6826:         if ($start > $now) {
                   6827:             return 'ok';
                   6828:         }
                   6829:     }
                   6830:     return; 
                   6831: }
                   6832: 
                   6833: sub parse_portfolio_url {
                   6834:     my ($url) = @_;
                   6835: 
                   6836:     my ($type,$udom,$unum,$group,$file_name);
                   6837:     
1.823     albertel 6838:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6839: 	$type = 1;
                   6840:         $udom = $1;
                   6841:         $unum = $2;
                   6842:         $file_name = $3;
1.823     albertel 6843:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6844: 	$type = 2;
                   6845:         $udom = $1;
                   6846:         $unum = $2;
                   6847:         $group = $3;
                   6848:         $file_name = $3.'/'.$4;
                   6849:     }
                   6850:     if (wantarray) {
                   6851: 	return ($type,$udom,$unum,$file_name,$group);
                   6852:     }
                   6853:     return $type;
                   6854: }
                   6855: 
                   6856: sub is_portfolio_url {
                   6857:     my ($url) = @_;
                   6858:     return scalar(&parse_portfolio_url($url));
                   6859: }
                   6860: 
1.798     raeburn  6861: sub is_portfolio_file {
                   6862:     my ($file) = @_;
1.820     raeburn  6863:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6864:         return 1;
                   6865:     }
                   6866:     return;
                   6867: }
                   6868: 
1.976     raeburn  6869: sub usertools_access {
1.1084    raeburn  6870:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6871:     my ($access,%tools);
                   6872:     if ($context eq '') {
                   6873:         $context = 'tools';
                   6874:     }
                   6875:     if ($context eq 'requestcourses') {
                   6876:         %tools = (
                   6877:                       official   => 1,
                   6878:                       unofficial => 1,
1.1006    raeburn  6879:                       community  => 1,
1.1172.2.37  raeburn  6880:                       textbook   => 1,
1.985     raeburn  6881:                  );
1.1172.2.9  raeburn  6882:     } elsif ($context eq 'requestauthor') {
                   6883:         %tools = (
                   6884:                       requestauthor => 1,
                   6885:                  );
1.985     raeburn  6886:     } else {
                   6887:         %tools = (
                   6888:                       aboutme   => 1,
                   6889:                       blog      => 1,
1.1172.2.6  raeburn  6890:                       webdav    => 1,
1.985     raeburn  6891:                       portfolio => 1,
                   6892:                  );
                   6893:     }
1.976     raeburn  6894:     return if (!defined($tools{$tool}));
                   6895: 
1.1172.2.35  raeburn  6896:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6897:         $udom = $env{'user.domain'};
                   6898:         $uname = $env{'user.name'};
                   6899:     }
                   6900: 
1.978     raeburn  6901:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6902:         if ($action ne 'reload') {
1.985     raeburn  6903:             if ($context eq 'requestcourses') {
                   6904:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  6905:             } elsif ($context eq 'requestauthor') {
                   6906:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6907:             } else {
                   6908:                 return $env{'environment.availabletools.'.$tool};
                   6909:             }
                   6910:         }
1.976     raeburn  6911:     }
                   6912: 
1.1172.2.9  raeburn  6913:     my ($toolstatus,$inststatus,$envkey);
                   6914:     if ($context eq 'requestauthor') {
                   6915:         $envkey = $context;
                   6916:     } else {
                   6917:         $envkey = $context.'.'.$tool;
                   6918:     }
1.976     raeburn  6919: 
1.985     raeburn  6920:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6921:          ($action ne 'reload')) {
1.1172.2.9  raeburn  6922:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6923:         $inststatus = $env{'environment.inststatus'};
                   6924:     } else {
1.1084    raeburn  6925:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  6926:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6927:             $inststatus = $userenvref->{'inststatus'};
                   6928:         } else {
1.1172.2.9  raeburn  6929:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6930:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6931:             $inststatus = $userenv{'inststatus'};
                   6932:         }
1.976     raeburn  6933:     }
                   6934: 
                   6935:     if ($toolstatus ne '') {
                   6936:         if ($toolstatus) {
                   6937:             $access = 1;
                   6938:         } else {
                   6939:             $access = 0;
                   6940:         }
                   6941:         return $access;
                   6942:     }
                   6943: 
1.1084    raeburn  6944:     my ($is_adv,%domdef);
                   6945:     if (ref($is_advref) eq 'HASH') {
                   6946:         $is_adv = $is_advref->{'is_adv'};
                   6947:     } else {
                   6948:         $is_adv = &is_advanced_user($udom,$uname);
                   6949:     }
                   6950:     if (ref($domdefref) eq 'HASH') {
                   6951:         %domdef = %{$domdefref};
                   6952:     } else {
                   6953:         %domdef = &get_domain_defaults($udom);
                   6954:     }
1.976     raeburn  6955:     if (ref($domdef{$tool}) eq 'HASH') {
                   6956:         if ($is_adv) {
                   6957:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6958:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6959:                     $access = 1;
                   6960:                 } else {
                   6961:                     $access = 0;
                   6962:                 }
                   6963:                 return $access;
                   6964:             }
                   6965:         }
                   6966:         if ($inststatus ne '') {
                   6967:             my ($hasaccess,$hasnoaccess);
                   6968:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6969:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6970:                     if ($domdef{$tool}{$affiliation}) {
                   6971:                         $hasaccess = 1;
                   6972:                     } else {
                   6973:                         $hasnoaccess = 1;
                   6974:                     }
                   6975:                 }
                   6976:             }
                   6977:             if ($hasaccess || $hasnoaccess) {
                   6978:                 if ($hasaccess) {
                   6979:                     $access = 1;
                   6980:                 } elsif ($hasnoaccess) {
                   6981:                     $access = 0; 
                   6982:                 }
                   6983:                 return $access;
                   6984:             }
                   6985:         } else {
                   6986:             if ($domdef{$tool}{'default'} ne '') {
                   6987:                 if ($domdef{$tool}{'default'}) {
                   6988:                     $access = 1;
                   6989:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6990:                     $access = 0;
                   6991:                 }
                   6992:                 return $access;
                   6993:             }
                   6994:         }
                   6995:     } else {
1.1172.2.6  raeburn  6996:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6997:             $access = 1;
                   6998:         } else {
                   6999:             $access = 0;
                   7000:         }
1.976     raeburn  7001:         return $access;
                   7002:     }
                   7003: }
                   7004: 
1.1050    raeburn  7005: sub is_course_owner {
                   7006:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7007:     if (($udom eq '') || ($uname eq '')) {
                   7008:         $udom = $env{'user.domain'};
                   7009:         $uname = $env{'user.name'};
                   7010:     }
                   7011:     unless (($udom eq '') || ($uname eq '')) {
                   7012:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7013:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7014:                 return 1;
                   7015:             } else {
                   7016:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7017:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7018:                     return 1;
                   7019:                 }
                   7020:             }
                   7021:         }
                   7022:     }
                   7023:     return;
                   7024: }
                   7025: 
1.976     raeburn  7026: sub is_advanced_user {
                   7027:     my ($udom,$uname) = @_;
1.1085    raeburn  7028:     if ($udom ne '' && $uname ne '') {
                   7029:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7030:             if (wantarray) {
                   7031:                 return ($env{'user.adv'},$env{'user.author'});
                   7032:             } else {
                   7033:                 return $env{'user.adv'};
                   7034:             }
1.1085    raeburn  7035:         }
                   7036:     }
1.976     raeburn  7037:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7038:     my %allroles;
1.1128    raeburn  7039:     my ($is_adv,$is_author);
1.976     raeburn  7040:     foreach my $role (keys(%roleshash)) {
                   7041:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7042:         my $area = '/'.$tdomain.'/'.$trest;
                   7043:         if ($sec ne '') {
                   7044:             $area .= '/'.$sec;
                   7045:         }
                   7046:         if (($area ne '') && ($trole ne '')) {
                   7047:             my $spec=$trole.'.'.$area;
                   7048:             if ($trole =~ /^cr\//) {
                   7049:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7050:             } elsif ($trole ne 'gr') {
                   7051:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7052:             }
1.1128    raeburn  7053:             if ($trole eq 'au') {
                   7054:                 $is_author = 1;
                   7055:             }
1.976     raeburn  7056:         }
                   7057:     }
                   7058:     foreach my $role (keys(%allroles)) {
                   7059:         last if ($is_adv);
                   7060:         foreach my $item (split(/:/,$allroles{$role})) {
                   7061:             if ($item ne '') {
                   7062:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7063:                 if ($privilege eq 'adv') {
                   7064:                     $is_adv = 1;
                   7065:                     last;
                   7066:                 }
                   7067:             }
                   7068:         }
                   7069:     }
1.1128    raeburn  7070:     if (wantarray) {
                   7071:         return ($is_adv,$is_author);
                   7072:     }
1.976     raeburn  7073:     return $is_adv;
                   7074: }
1.798     raeburn  7075: 
1.1035    raeburn  7076: sub check_can_request {
1.1036    raeburn  7077:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7078:     my $canreq = 0;
                   7079:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7080:     my @options = ('approval','validate','autolimit');
                   7081:     my $optregex = join('|',@options);
                   7082:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7083:         foreach my $type (@{$types}) {
                   7084:             if (&usertools_access($env{'user.name'},
                   7085:                                   $env{'user.domain'},
                   7086:                                   $type,undef,'requestcourses')) {
                   7087:                 $canreq ++;
1.1036    raeburn  7088:                 if (ref($request_domains) eq 'HASH') {
                   7089:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7090:                 }
1.1035    raeburn  7091:                 if ($dom eq $env{'user.domain'}) {
                   7092:                     $can_request->{$type} = 1;
                   7093:                 }
                   7094:             }
                   7095:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7096:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7097:                 if (@curr > 0) {
1.1036    raeburn  7098:                     foreach my $item (@curr) {
                   7099:                         if (ref($request_domains) eq 'HASH') {
                   7100:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7101:                             if ($otherdom ne '') {
                   7102:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7103:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7104:                                         push(@{$request_domains->{$type}},$otherdom);
                   7105:                                     }
                   7106:                                 } else {
                   7107:                                     push(@{$request_domains->{$type}},$otherdom);
                   7108:                                 }
                   7109:                             }
                   7110:                         }
                   7111:                     }
                   7112:                     unless($dom eq $env{'user.domain'}) {
                   7113:                         $canreq ++;
1.1035    raeburn  7114:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7115:                             $can_request->{$type} = 1;
                   7116:                         }
                   7117:                     }
                   7118:                 }
                   7119:             }
                   7120:         }
                   7121:     }
                   7122:     return $canreq;
                   7123: }
                   7124: 
1.341     www      7125: # ---------------------------------------------- Custom access rule evaluation
                   7126: 
                   7127: sub customaccess {
                   7128:     my ($priv,$uri)=@_;
1.807     albertel 7129:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7130:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7131:     $udom = &LONCAPA::clean_domain($udom);
                   7132:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7133:     my $access=0;
1.800     albertel 7134:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7135: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7136: 	if ($type eq 'user') {
                   7137: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7138: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7139: 		if ($tdom) {
                   7140: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7141: 		}
1.896     albertel 7142: 		if ($tuname) {
                   7143: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7144: 		}
                   7145: 		$access=($effect eq 'allow');
                   7146: 		last;
                   7147: 	    }
                   7148: 	} else {
                   7149: 	    if ($role) {
                   7150: 		if ($role ne $urole) { next; }
                   7151: 	    }
                   7152: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7153: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7154: 		if ($tdom) {
                   7155: 		    if ($tdom ne $udom) { next; }
                   7156: 		}
                   7157: 		if ($tcrs) {
                   7158: 		    if ($tcrs ne $ucrs) { next; }
                   7159: 		}
                   7160: 		if ($tsec) {
                   7161: 		    if ($tsec ne $usec) { next; }
                   7162: 		}
                   7163: 		$access=($effect eq 'allow');
                   7164: 		last;
                   7165: 	    }
                   7166: 	    if ($realm eq '' && $role eq '') {
                   7167: 		$access=($effect eq 'allow');
                   7168: 	    }
1.402     bowersj2 7169: 	}
1.341     www      7170:     }
                   7171:     return $access;
                   7172: }
                   7173: 
1.103     harris41 7174: # ------------------------------------------------- Check for a user privilege
1.12      www      7175: 
                   7176: sub allowed {
1.1172.2.65  raeburn  7177:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7178:     my $ver_orguri=$uri;
1.439     www      7179:     $uri=&deversion($uri);
1.152     www      7180:     my $orguri=$uri;
1.52      www      7181:     $uri=&declutter($uri);
1.809     raeburn  7182: 
1.810     raeburn  7183:     if ($priv eq 'evb') {
                   7184: # Evade communication block restrictions for specified role in a course
                   7185:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7186:             return $1;
                   7187:         } else {
                   7188:             return;
                   7189:         }
                   7190:     }
                   7191: 
1.620     albertel 7192:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7193: # Free bre access to adm and meta resources
1.1172.2.93.4  2(raebur 7194:7):     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
1.769     albertel 7195: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7196: 	&& ($priv eq 'bre')) {
1.14      www      7197: 	return 'F';
1.159     www      7198:     }
                   7199: 
1.545     banghart 7200: # Free bre access to user's own portfolio contents
1.714     raeburn  7201:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7202:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7203: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7204:         my %setters;
                   7205:         my ($startblock,$endblock) = 
                   7206:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7207:         if ($startblock && $endblock) {
                   7208:             return 'B';
                   7209:         } else {
                   7210:             return 'F';
                   7211:         }
1.545     banghart 7212:     }
                   7213: 
1.762     raeburn  7214: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7215:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7216:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7217:         if (exists($env{'request.course.id'})) {
                   7218:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7219:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7220:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7221:                 my $courseprivid=$env{'request.course.id'};
                   7222:                 $courseprivid=~s/\_/\//;
                   7223:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7224:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7225:                     return $1; 
1.762     raeburn  7226:                 } else {
                   7227:                     if ($env{'request.course.sec'}) {
                   7228:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7229:                     }
                   7230:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7231:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7232:                         return $2;
                   7233:                     }
1.714     raeburn  7234:                 }
                   7235:             }
                   7236:         }
                   7237:     }
                   7238: 
1.159     www      7239: # Free bre to public access
                   7240: 
                   7241:     if ($priv eq 'bre') {
1.238     www      7242:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7243: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7244:            return 'F'; 
                   7245:         }
1.238     www      7246:         if ($copyright eq 'priv') {
                   7247:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7248: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7249: 		return '';
                   7250:             }
                   7251:         }
                   7252:         if ($copyright eq 'domain') {
                   7253:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7254: 	    unless (($env{'user.domain'} eq $1) ||
                   7255:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7256: 		return '';
                   7257:             }
1.262     matthew  7258:         }
1.620     albertel 7259:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7260:             # Library role, so allow browsing of resources in this domain.
                   7261:             return 'F';
1.238     www      7262:         }
1.341     www      7263:         if ($copyright eq 'custom') {
                   7264: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7265:         }
1.14      www      7266:     }
1.264     matthew  7267:     # Domain coordinator is trying to create a course
1.620     albertel 7268:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7269:         # uri is the requested domain in this case.
                   7270:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7271:         # a role of dc for the domain in question.
1.620     albertel 7272:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7273:     }
1.29      www      7274: 
1.52      www      7275:     my $thisallowed='';
                   7276:     my $statecond=0;
                   7277:     my $courseprivid='';
                   7278: 
1.1039    raeburn  7279:     my $ownaccess;
1.1043    raeburn  7280:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7281:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7282:         if ($uri eq '') {
                   7283:             $ownaccess = 1;
                   7284:         } else {
                   7285:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7286:                 my $udom = $env{'user.domain'};
                   7287:                 my $uname = $env{'user.name'};
                   7288:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7289:                     $ownaccess = 1;
1.1040    raeburn  7290:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7291:                     unless ($uri =~ m{\.\./}) {
                   7292:                         $ownaccess = 1;
                   7293:                     }
                   7294:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7295:                     my $now = time;
                   7296:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7297:                         my $adom = $1;
                   7298:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7299:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7300:                                 my ($start,$end) = split('.',$env{$key});
                   7301:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7302:                                     $ownaccess = 1;
                   7303:                                     last;
                   7304:                                 }
                   7305:                             }
                   7306:                         }
                   7307:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7308:                         my $adom = $1;
                   7309:                         my $aname = $2;
1.1042    raeburn  7310:                         foreach my $role ('ca','aa') { 
                   7311:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7312:                                 my ($start,$end) =
                   7313:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7314:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7315:                                     $ownaccess = 1;
                   7316:                                     last;
                   7317:                                 }
1.1039    raeburn  7318:                             }
                   7319:                         }
                   7320:                     }
                   7321:                 }
                   7322:             }
                   7323:         }
                   7324:     }
                   7325: 
1.52      www      7326: # Course
                   7327: 
1.620     albertel 7328:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7329:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7330:             $thisallowed.=$1;
                   7331:         }
1.52      www      7332:     }
1.29      www      7333: 
1.52      www      7334: # Domain
                   7335: 
1.620     albertel 7336:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7337:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7338:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7339:             $thisallowed.=$1;
                   7340:         }
1.12      www      7341:     }
1.52      www      7342: 
1.1141    raeburn  7343: # User who is not author or co-author might still be able to edit
                   7344: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7345:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7346:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7347:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7348:             $thisallowed.=$1;
                   7349:         }
                   7350:     }
                   7351: 
1.52      www      7352: # Course: uri itself is a course
1.66      www      7353:     my $courseuri=$uri;
                   7354:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7355:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7356: 
1.620     albertel 7357:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7358:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7359:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7360:             $thisallowed.=$1;
                   7361:         }
1.12      www      7362:     }
1.29      www      7363: 
1.665     albertel 7364: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7365: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7366:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7367: 	$thisallowed='';
1.671     raeburn  7368:         my ($match)=&is_on_map($uri);
                   7369:         if ($match) {
                   7370:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7371:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  7372:                 my $value = $1;
                   7373:                 if ($noblockcheck) {
                   7374:                     $thisallowed.=$value;
1.1162    raeburn  7375:                 } else {
1.1172.2.65  raeburn  7376:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7377:                     if (@blockers > 0) {
                   7378:                         $thisallowed = 'B';
                   7379:                     } else {
                   7380:                         $thisallowed.=$value;
                   7381:                     }
1.1162    raeburn  7382:                 }
1.671     raeburn  7383:             }
                   7384:         } else {
1.705     albertel 7385:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7386:             if ($refuri) {
                   7387:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7388:                     $thisallowed='F';
1.671     raeburn  7389:                 } else {
                   7390:                     $refuri=&declutter($refuri);
                   7391:                     my ($match) = &is_on_map($refuri);
                   7392:                     if ($match) {
1.1172.2.65  raeburn  7393:                         if ($noblockcheck) {
1.1162    raeburn  7394:                             $thisallowed='F';
1.1172.2.65  raeburn  7395:                         } else {
                   7396:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7397:                             if (@blockers > 0) {
                   7398:                                 $thisallowed = 'B';
                   7399:                             } else {
                   7400:                                 $thisallowed='F';
                   7401:                             }
1.1162    raeburn  7402:                         }
1.671     raeburn  7403:                     }
1.669     raeburn  7404:                 }
1.671     raeburn  7405:             }
                   7406:         }
1.314     www      7407:     }
1.492     albertel 7408: 
1.766     albertel 7409:     if ($priv eq 'bre'
                   7410: 	&& $thisallowed ne 'F' 
                   7411: 	&& $thisallowed ne '2'
                   7412: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  7413: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7414:     }
                   7415:     
1.52      www      7416: # Full access at system, domain or course-wide level? Exit.
1.29      www      7417:     if ($thisallowed=~/F/) {
                   7418: 	return 'F';
                   7419:     }
                   7420: 
1.52      www      7421: # If this is generating or modifying users, exit with special codes
1.29      www      7422: 
1.643     www      7423:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7424: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7425: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7426: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7427: 	    unless ($auname) { return $thisallowed; }
                   7428: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7429: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7430: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7431: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7432: 	}
1.52      www      7433: 	return $thisallowed;
                   7434:     }
                   7435: #
1.103     harris41 7436: # Gathered so far: system, domain and course wide privileges
1.52      www      7437: #
                   7438: # Course: See if uri or referer is an individual resource that is part of 
                   7439: # the course
                   7440: 
1.620     albertel 7441:     if ($env{'request.course.id'}) {
1.232     www      7442: 
1.620     albertel 7443:        $courseprivid=$env{'request.course.id'};
                   7444:        if ($env{'request.course.sec'}) {
                   7445:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7446:        }
                   7447:        $courseprivid=~s/\_/\//;
                   7448:        my $checkreferer=1;
1.232     www      7449:        my ($match,$cond)=&is_on_map($uri);
                   7450:        if ($match) {
                   7451:            $statecond=$cond;
1.620     albertel 7452:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7453:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7454:                my $value = $1;
                   7455:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  7456:                    if ($noblockcheck) {
1.1162    raeburn  7457:                        $thisallowed.=$value;
1.1172.2.65  raeburn  7458:                    } else {
                   7459:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7460:                        if (@blockers > 0) {
                   7461:                            $thisallowed = 'B';
                   7462:                        } else {
                   7463:                            $thisallowed.=$value;
                   7464:                        }
1.1162    raeburn  7465:                    }
                   7466:                } else {
                   7467:                    $thisallowed.=$value;
                   7468:                }
1.52      www      7469:                $checkreferer=0;
                   7470:            }
1.29      www      7471:        }
1.83      www      7472:        
1.148     www      7473:        if ($checkreferer) {
1.620     albertel 7474: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7475:             unless ($refuri) {
1.800     albertel 7476:                 foreach my $key (keys(%env)) {
                   7477: 		    if ($key=~/^httpref\..*\*/) {
                   7478: 			my $pattern=$key;
1.156     www      7479:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7480:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7481:                         $pattern=~s/\//\\\//g;
1.152     www      7482:                         if ($orguri=~/$pattern/) {
1.800     albertel 7483: 			    $refuri=$env{$key};
1.148     www      7484:                         }
                   7485:                     }
1.191     harris41 7486:                 }
1.148     www      7487:             }
1.232     www      7488: 
1.148     www      7489:          if ($refuri) { 
1.152     www      7490: 	  $refuri=&declutter($refuri);
1.232     www      7491:           my ($match,$cond)=&is_on_map($refuri);
                   7492:             if ($match) {
                   7493:               my $refstatecond=$cond;
1.620     albertel 7494:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7495:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7496:                   my $value = $1;
                   7497:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  7498:                       if ($noblockcheck) {
1.1162    raeburn  7499:                           $thisallowed.=$value;
1.1172.2.65  raeburn  7500:                       } else {
                   7501:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7502:                           if (@blockers > 0) {
                   7503:                               $thisallowed = 'B';
                   7504:                           } else {
                   7505:                               $thisallowed.=$value;
                   7506:                           }
1.1162    raeburn  7507:                       }
                   7508:                   } else {
                   7509:                       $thisallowed.=$value;
                   7510:                   }
1.53      www      7511:                   $uri=$refuri;
                   7512:                   $statecond=$refstatecond;
1.52      www      7513:               }
                   7514:           }
1.148     www      7515:         }
1.29      www      7516:        }
1.52      www      7517:    }
1.29      www      7518: 
1.52      www      7519: #
1.103     harris41 7520: # Gathered now: all privileges that could apply, and condition number
1.52      www      7521: # 
                   7522: #
                   7523: # Full or no access?
                   7524: #
1.29      www      7525: 
1.52      www      7526:     if ($thisallowed=~/F/) {
                   7527: 	return 'F';
                   7528:     }
1.29      www      7529: 
1.52      www      7530:     unless ($thisallowed) {
                   7531:         return '';
                   7532:     }
1.29      www      7533: 
1.52      www      7534: # Restrictions exist, deal with them
                   7535: #
                   7536: #   C:according to course preferences
                   7537: #   R:according to resource settings
                   7538: #   L:unless locked
                   7539: #   X:according to user session state
                   7540: #
                   7541: 
                   7542: # Possibly locked functionality, check all courses
1.54      www      7543: # Locks might take effect only after 10 minutes cache expiration for other
                   7544: # courses, and 2 minutes for current course
1.52      www      7545: 
                   7546:     my $envkey;
                   7547:     if ($thisallowed=~/L/) {
1.1000    raeburn  7548:         foreach $envkey (keys(%env)) {
1.54      www      7549:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7550:                my $courseid=$2;
                   7551:                my $roleid=$1.'.'.$2;
1.92      www      7552:                $courseid=~s/^\///;
1.54      www      7553:                my $expiretime=600;
1.620     albertel 7554:                if ($env{'request.role'} eq $roleid) {
1.54      www      7555: 		  $expiretime=120;
                   7556:                }
                   7557: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7558:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7559:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7560: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7561:                }
1.620     albertel 7562:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7563:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7564: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7565:                        &log($env{'user.domain'},$env{'user.name'},
                   7566:                             $env{'user.home'},
1.57      www      7567:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7568:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7569:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7570: 		       return '';
                   7571:                    }
                   7572:                }
1.620     albertel 7573:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7574:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7575: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7576:                        &log($env{'user.domain'},$env{'user.name'},
                   7577:                             $env{'user.home'},
1.57      www      7578:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7579:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7580:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7581: 		       return '';
                   7582:                    }
                   7583:                }
                   7584: 	   }
1.29      www      7585:        }
1.52      www      7586:     }
                   7587:    
                   7588: #
                   7589: # Rest of the restrictions depend on selected course
                   7590: #
                   7591: 
1.620     albertel 7592:     unless ($env{'request.course.id'}) {
1.766     albertel 7593: 	if ($thisallowed eq 'A') {
                   7594: 	    return 'A';
1.814     raeburn  7595:         } elsif ($thisallowed eq 'B') {
                   7596:             return 'B';
1.766     albertel 7597: 	} else {
                   7598: 	    return '1';
                   7599: 	}
1.52      www      7600:     }
1.29      www      7601: 
1.52      www      7602: #
                   7603: # Now user is definitely in a course
                   7604: #
1.53      www      7605: 
                   7606: 
                   7607: # Course preferences
                   7608: 
                   7609:    if ($thisallowed=~/C/) {
1.620     albertel 7610:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7611:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7612:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7613: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  7614: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7615: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7616: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7617: 			$env{'request.course.id'});
                   7618: 	   }
1.237     www      7619:            return '';
                   7620:        }
                   7621: 
1.620     albertel 7622:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7623: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  7624: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7625: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7626: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7627: 			$env{'request.course.id'});
                   7628: 	   }
1.54      www      7629:            return '';
                   7630:        }
1.53      www      7631:    }
                   7632: 
                   7633: # Resource preferences
                   7634: 
                   7635:    if ($thisallowed=~/R/) {
1.620     albertel 7636:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7637:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7638: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7639: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7640: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7641: 	   }
                   7642: 	   return '';
1.54      www      7643:        }
1.53      www      7644:    }
1.30      www      7645: 
1.246     www      7646: # Restricted by state or randomout?
1.30      www      7647: 
1.52      www      7648:    if ($thisallowed=~/X/) {
1.620     albertel 7649:       if ($env{'acc.randomout'}) {
1.579     albertel 7650: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7651:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7652:             return ''; 
                   7653:          }
1.247     www      7654:       }
                   7655:       if (&condval($statecond)) {
1.52      www      7656: 	 return '2';
                   7657:       } else {
                   7658:          return '';
                   7659:       }
                   7660:    }
1.30      www      7661: 
1.766     albertel 7662:     if ($thisallowed eq 'A') {
                   7663: 	return 'A';
1.814     raeburn  7664:     } elsif ($thisallowed eq 'B') {
                   7665:         return 'B';
1.766     albertel 7666:     }
1.52      www      7667:    return 'F';
1.232     www      7668: }
1.1162    raeburn  7669: 
1.1172.2.13  raeburn  7670: # ------------------------------------------- Check construction space access
                   7671: 
                   7672: sub constructaccess {
                   7673:     my ($url,$setpriv)=@_;
                   7674: 
                   7675: # We do not allow editing of previous versions of files
                   7676:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7677: 
                   7678: # Get username and domain from URL
                   7679:     my ($ownername,$ownerdomain,$ownerhome);
                   7680: 
                   7681:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  7682:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  7683: 
                   7684: # The URL does not really point to any authorspace, forget it
                   7685:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7686: 
                   7687: # Now we need to see if the user has access to the authorspace of
                   7688: # $ownername at $ownerdomain
                   7689: 
                   7690:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7691: # Real author for this?
                   7692:        $ownerhome = $env{'user.home'};
                   7693:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7694:           return ($ownername,$ownerdomain,$ownerhome);
                   7695:        }
                   7696:     } else {
                   7697: # Co-author for this?
                   7698:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7699:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7700:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7701:             return ($ownername,$ownerdomain,$ownerhome);
                   7702:         }
                   7703:     }
                   7704: 
                   7705: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7706: # we might as well leave
                   7707:    unless ($setpriv) { return ''; }
                   7708: 
                   7709: # Backdoor access?
                   7710:     my $allowed=&allowed('eco',$ownerdomain);
                   7711: # Nope
                   7712:     unless ($allowed) { return ''; }
                   7713: # Looks like we may have access, but could be locked by the owner of the construction space
                   7714:     if ($allowed eq 'U') {
                   7715:         my %blocked=&get('environment',['domcoord.author'],
                   7716:                          $ownerdomain,$ownername);
                   7717: # Is blocked by owner
                   7718:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7719:     }
                   7720:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7721: # Grant temporary access
                   7722:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  7723:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  7724:         if (!$update) { $update = $then; }
                   7725:         my $refresh=$env{'user.refresh.time'};
                   7726:         if (!$refresh) { $refresh = $update; }
                   7727:         my $now = time;
                   7728:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7729:                            $now,'ca','constructaccess');
                   7730:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7731:         return($ownername,$ownerdomain,$ownerhome);
                   7732:     }
                   7733: # No business here
                   7734:     return '';
                   7735: }
                   7736: 
1.1172.2.66  raeburn  7737: # ----------------------------------------------------------- Content Blocking
                   7738: 
                   7739: {
                   7740: # Caches for faster Course Contents display where content blocking
                   7741: # is in operation (i.e., interval param set) for timed quiz.
                   7742: #
                   7743: # User for whom data are being temporarily cached.
                   7744: my $cacheduser='';
                   7745: # Cached blockers for this user (a hash of blocking items).
                   7746: my %cachedblockers=();
                   7747: # When the data were last cached.
                   7748: my $cachedlast='';
                   7749: 
                   7750: sub load_all_blockers {
                   7751:     my ($uname,$udom,$blocks)=@_;
                   7752:     if (($uname ne '') && ($udom ne '')) {
                   7753:         if (($cacheduser eq $uname.':'.$udom) &&
                   7754:             (abs($cachedlast-time)<5)) {
                   7755:             return;
                   7756:         }
                   7757:     }
                   7758:     $cachedlast=time;
                   7759:     $cacheduser=$uname.':'.$udom;
                   7760:     %cachedblockers = &get_commblock_resources($blocks);
                   7761: }
                   7762: 
1.1162    raeburn  7763: sub get_comm_blocks {
                   7764:     my ($cdom,$cnum) = @_;
                   7765:     if ($cdom eq '' || $cnum eq '') {
                   7766:         return unless ($env{'request.course.id'});
                   7767:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7768:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7769:     }
                   7770:     my %commblocks;
                   7771:     my $hashid=$cdom.'_'.$cnum;
                   7772:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7773:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7774:         %commblocks = %{$blocksref};
                   7775:     } else {
                   7776:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7777:         my $cachetime = 600;
                   7778:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7779:     }
                   7780:     return %commblocks;
                   7781: }
                   7782: 
1.1172.2.66  raeburn  7783: sub get_commblock_resources {
                   7784:     my ($blocks) = @_;
                   7785:     my %blockers = ();
                   7786:     return %blockers unless ($env{'request.course.id'});
                   7787:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  7788:     my %commblocks;
                   7789:     if (ref($blocks) eq 'HASH') {
                   7790:         %commblocks = %{$blocks};
                   7791:     } else {
                   7792:         %commblocks = &get_comm_blocks();
                   7793:     }
1.1172.2.66  raeburn  7794:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  7795:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  7796:     return %blockers unless (ref($navmap));
                   7797:     my $now = time;
1.1162    raeburn  7798:     foreach my $block (keys(%commblocks)) {
                   7799:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7800:             my ($start,$end) = ($1,$2);
                   7801:             if ($start <= $now && $end >= $now) {
                   7802:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7803:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7804:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  7805:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7806:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  7807:                             }
                   7808:                         }
                   7809:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  7810:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7811:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  7812:                             }
                   7813:                         }
                   7814:                     }
                   7815:                 }
                   7816:             }
                   7817:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7818:             my $item = $1;
1.1163    raeburn  7819:             my @to_test;
1.1162    raeburn  7820:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7821:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66  raeburn  7822:                     my @interval;
                   7823:                     my $type = 'map';
                   7824:                     if ($item eq 'course') {
                   7825:                         $type = 'course';
                   7826:                         @interval=&EXT("resource.0.interval");
                   7827:                     } else {
                   7828:                         if ($item =~ /___\d+___/) {
                   7829:                             $type = 'resource';
                   7830:                             @interval=&EXT("resource.0.interval",$item);
                   7831:                             if (ref($navmap)) {
                   7832:                                 my $res = $navmap->getBySymb($item);
                   7833:                                 push(@to_test,$res);
                   7834:                             }
1.1162    raeburn  7835:                         } else {
1.1172.2.66  raeburn  7836:                             my $mapsymb = &symbread($item,1);
                   7837:                             if ($mapsymb) {
                   7838:                                 if (ref($navmap)) {
                   7839:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   7840:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   7841:                                     foreach my $res (@to_test) {
                   7842:                                         my $symb = $res->symb();
                   7843:                                         next if ($symb eq $mapsymb);
                   7844:                                         if ($symb ne '') {
                   7845:                                             @interval=&EXT("resource.0.interval",$symb);
                   7846:                                             if ($interval[1] eq 'map') {
                   7847:                                                 last;
1.1162    raeburn  7848:                                             }
                   7849:                                         }
                   7850:                                     }
                   7851:                                 }
                   7852:                             }
                   7853:                         }
1.1172.2.66  raeburn  7854:                     }
1.1172.2.93.4  1(raebur 7855:7):                     if ($interval[0] =~ /^(\d+)/) {
                   7856:7):                         my $timelimit = $1;
1.1172.2.66  raeburn  7857:                         my $first_access;
                   7858:                         if ($type eq 'resource') {
                   7859:                             $first_access=&get_first_access($interval[1],$item);
                   7860:                         } elsif ($type eq 'map') {
                   7861:                             $first_access=&get_first_access($interval[1],undef,$item);
                   7862:                         } else {
                   7863:                             $first_access=&get_first_access($interval[1]);
                   7864:                         }
                   7865:                         if ($first_access) {
1.1172.2.93.4  1(raebur 7866:7):                             my $timesup = $first_access+$timelimit;
1.1172.2.66  raeburn  7867:                             if ($timesup > $now) {
                   7868:                                 my $activeblock;
                   7869:                                 foreach my $res (@to_test) {
                   7870:                                     if ($res->answerable()) {
                   7871:                                         $activeblock = 1;
                   7872:                                         last;
                   7873:                                     }
                   7874:                                 }
                   7875:                                 if ($activeblock) {
                   7876:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7877:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7878:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   7879:                                          }
                   7880:                                     }
                   7881:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7882:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7883:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  7884:                                         }
1.1162    raeburn  7885:                                     }
                   7886:                                 }
                   7887:                             }
                   7888:                         }
                   7889:                     }
                   7890:                 }
                   7891:             }
                   7892:         }
                   7893:     }
1.1172.2.66  raeburn  7894:     return %blockers;
1.1162    raeburn  7895: }
                   7896: 
1.1172.2.66  raeburn  7897: sub has_comm_blocking {
                   7898:     my ($priv,$symb,$uri,$blocks) = @_;
                   7899:     my @blockers;
                   7900:     return unless ($env{'request.course.id'});
                   7901:     return unless ($priv eq 'bre');
                   7902:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7903:     return if ($env{'request.state'} eq 'construct');
                   7904:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   7905:     return unless (keys(%cachedblockers) > 0);
                   7906:     my (%possibles,@symbs);
                   7907:     if (!$symb) {
                   7908:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  7909:     }
1.1172.2.66  raeburn  7910:     if ($symb) {
                   7911:         @symbs = ($symb);
                   7912:     } elsif (keys(%possibles)) {
                   7913:         @symbs = keys(%possibles);
                   7914:     }
                   7915:     my $noblock;
                   7916:     foreach my $symb (@symbs) {
                   7917:         last if ($noblock);
                   7918:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   7919:         foreach my $block (keys(%cachedblockers)) {
                   7920:             if ($block =~ /^firstaccess____(.+)$/) {
                   7921:                 my $item = $1;
                   7922:                 if (($item eq $map) || ($item eq $symb)) {
                   7923:                     $noblock = 1;
                   7924:                     last;
                   7925:                 }
1.1162    raeburn  7926:             }
1.1172.2.66  raeburn  7927:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   7928:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   7929:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   7930:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   7931:                             push(@blockers,$block);
                   7932:                         }
                   7933:                     }
                   7934:                 }
                   7935:             }
                   7936:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   7937:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   7938:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   7939:                         push(@blockers,$block);
                   7940:                     }
                   7941:                 }
1.1162    raeburn  7942:             }
                   7943:         }
                   7944:     }
1.1172.2.66  raeburn  7945:     return if ($noblock);
                   7946:     return @blockers;
                   7947: }
1.1162    raeburn  7948: }
                   7949: 
1.1172.2.66  raeburn  7950: # -------------------------------- Deversion and split uri into path an filename
                   7951: 
1.1133    foxr     7952: #
1.1172.2.66  raeburn  7953: #   Removes the version from a URI and
1.1133    foxr     7954: #   splits it in to its filename and path to the filename.
                   7955: #   Seems like File::Basename could have done this more clearly.
                   7956: #   Parameters:
                   7957: #      $uri   - input URI
                   7958: #   Returns:
                   7959: #     Two element list consisting of 
                   7960: #     $pathname  - the URI up to and excluding the trailing /
                   7961: #     $filename  - The part of the URI following the last /
                   7962: #  NOTE:
                   7963: #    Another realization of this is simply:
                   7964: #    use File::Basename;
                   7965: #    ...
                   7966: #    $uri = shift;
                   7967: #    $filename = basename($uri);
                   7968: #    $path     = dirname($uri);
                   7969: #    return ($filename, $path);
                   7970: #
                   7971: #     The implementation below is probably faster however.
                   7972: #
1.710     albertel 7973: sub split_uri_for_cond {
                   7974:     my $uri=&deversion(&declutter(shift));
                   7975:     my @uriparts=split(/\//,$uri);
                   7976:     my $filename=pop(@uriparts);
                   7977:     my $pathname=join('/',@uriparts);
                   7978:     return ($pathname,$filename);
                   7979: }
1.232     www      7980: # --------------------------------------------------- Is a resource on the map?
                   7981: 
                   7982: sub is_on_map {
1.710     albertel 7983:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7984:     #Trying to find the conditional for the file
1.620     albertel 7985:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7986: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7987:     if ($match) {
1.289     bowersj2 7988: 	return (1,$1);
                   7989:     } else {
1.434     www      7990: 	return (0,0);
1.289     bowersj2 7991:     }
1.12      www      7992: }
                   7993: 
1.427     www      7994: # --------------------------------------------------------- Get symb from alias
                   7995: 
                   7996: sub get_symb_from_alias {
                   7997:     my $symb=shift;
                   7998:     my ($map,$resid,$url)=&decode_symb($symb);
                   7999: # Already is a symb
                   8000:     if ($url) { return $symb; }
                   8001: # Must be an alias
                   8002:     my $aliassymb='';
                   8003:     my %bighash;
1.620     albertel 8004:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8005:                             &GDBM_READER(),0640)) {
                   8006:         my $rid=$bighash{'mapalias_'.$symb};
                   8007: 	if ($rid) {
                   8008: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8009: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8010: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8011: 	}
                   8012:         untie %bighash;
                   8013:     }
                   8014:     return $aliassymb;
                   8015: }
                   8016: 
1.12      www      8017: # ----------------------------------------------------------------- Define Role
                   8018: 
                   8019: sub definerole {
                   8020:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  8021:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8022:     foreach my $role (split(':',$sysrole)) {
                   8023: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8024:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8025:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8026: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8027:                return "refused:s:$crole&$cqual"; 
                   8028:             }
                   8029:         }
1.191     harris41 8030:     }
1.800     albertel 8031:     foreach my $role (split(':',$domrole)) {
                   8032: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8033:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8034:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8035: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8036:                return "refused:d:$crole&$cqual"; 
                   8037:             }
                   8038:         }
1.191     harris41 8039:     }
1.800     albertel 8040:     foreach my $role (split(':',$courole)) {
                   8041: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8042:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8043:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8044: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8045:                return "refused:c:$crole&$cqual"; 
                   8046:             }
                   8047:         }
1.191     harris41 8048:     }
1.1172.2.84  raeburn  8049:     my $uhome;
                   8050:     if (($uname ne '') && ($udom ne '')) {
                   8051:         $uhome = &homeserver($uname,$udom);
                   8052:         return $uhome if ($uhome eq 'no_host');
                   8053:     } else {
                   8054:         $uname = $env{'user.name'};
                   8055:         $udom = $env{'user.domain'};
                   8056:         $uhome = $env{'user.home'};
                   8057:     }
1.620     albertel 8058:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  8059:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8060:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  8061:     return reply($command,$uhome);
1.12      www      8062:   } else {
                   8063:     return 'refused';
                   8064:   }
1.105     harris41 8065: }
                   8066: 
                   8067: # ---------------- Make a metadata query against the network of library servers
                   8068: 
                   8069: sub metadata_query {
1.1172.2.33  raeburn  8070:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8071:     my %rhash;
1.845     albertel 8072:     my %libserv = &all_library();
1.244     matthew  8073:     my @server_list = (defined($server_array) ? @$server_array
                   8074:                                               : keys(%libserv) );
                   8075:     for my $server (@server_list) {
1.1172.2.33  raeburn  8076:         my $domains = '';
                   8077:         if (ref($domains_hash) eq 'HASH') {
                   8078:             $domains = $domains_hash->{$server};    
                   8079:         }
1.118     harris41 8080: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  8081: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8082: 	    $rhash{$server}=$reply;
                   8083: 	}
                   8084: 	else {
                   8085: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  8086: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8087: 			     $server);
                   8088: 	    $rhash{$server}=$reply;
                   8089: 	}
1.112     harris41 8090:     }
1.118     harris41 8091:     return \%rhash;
1.240     www      8092: }
                   8093: 
                   8094: # ----------------------------------------- Send log queries and wait for reply
                   8095: 
                   8096: sub log_query {
                   8097:     my ($uname,$udom,$query,%filters)=@_;
                   8098:     my $uhome=&homeserver($uname,$udom);
                   8099:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8100:     my $uhost=&hostname($uhome);
1.800     albertel 8101:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8102:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8103:                        $uhome);
1.479     albertel 8104:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8105:     return get_query_reply($queryid);
                   8106: }
                   8107: 
1.818     raeburn  8108: # -------------------------- Update MySQL table for portfolio file
                   8109: 
                   8110: sub update_portfolio_table {
1.821     raeburn  8111:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8112:     if ($group ne '') {
                   8113:         $file_name =~s /^\Q$group\E//;
                   8114:     }
1.818     raeburn  8115:     my $homeserver = &homeserver($uname,$udom);
                   8116:     my $queryid=
1.821     raeburn  8117:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8118:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8119:     my $reply = &get_query_reply($queryid);
                   8120:     return $reply;
                   8121: }
                   8122: 
1.899     raeburn  8123: # -------------------------- Update MySQL allusers table
                   8124: 
                   8125: sub update_allusers_table {
                   8126:     my ($uname,$udom,$names) = @_;
                   8127:     my $homeserver = &homeserver($uname,$udom);
                   8128:     my $queryid=
                   8129:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8130:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8131:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8132:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8133:                'generation='.&escape($names->{'generation'}).'%%'.
                   8134:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8135:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8136:     return;
1.899     raeburn  8137: }
                   8138: 
1.508     raeburn  8139: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8140: 
                   8141: sub fetch_enrollment_query {
1.511     raeburn  8142:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  8143:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8144:     my $maxtries = 1;
1.508     raeburn  8145:     if ($context eq 'automated') {
                   8146:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  8147:         $sleep = 2;
                   8148:         $loopmax = 100;
1.547     raeburn  8149:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8150:     } else {
                   8151:         $homeserver = &homeserver($cnum,$dom);
                   8152:     }
1.838     albertel 8153:     my $host=&hostname($homeserver);
1.506     raeburn  8154:     my $cmd = '';
1.1000    raeburn  8155:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8156:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8157:     }
                   8158:     $cmd =~ s/%%$//;
                   8159:     $cmd = &escape($cmd);
                   8160:     my $query = 'fetchenrollment';
1.620     albertel 8161:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8162:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8163:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8164:         return 'error: '.$queryid;
                   8165:     }
1.1172.2.93  raeburn  8166:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8167:     my $tries = 1;
                   8168:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  8169:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8170:         $tries ++;
                   8171:     }
1.526     raeburn  8172:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8173:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8174:     } else {
1.901     albertel 8175:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  8176:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8177:             foreach my $line (@responses) {
                   8178:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8179:                 $$replyref{$key} = $value;
                   8180:             }
                   8181:         } else {
1.1117    foxr     8182:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8183:             foreach my $line (@responses) {
                   8184:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8185:                 $$replyref{$key} = $value;
                   8186:                 if ($value > 0) {
1.800     albertel 8187:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8188:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8189:                         my $destname = $pathname.'/'.$filename;
                   8190:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8191:                         if ($xml_classlist =~ /^error/) {
                   8192:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8193:                         } else {
1.1172.2.93.4  7(raebur 8194:7):                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8195:                                 print FILE &unescape($xml_classlist);
                   8196:                                 close(FILE);
1.526     raeburn  8197:                             } else {
                   8198:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8199:                             }
                   8200:                         }
                   8201:                     }
                   8202:                 }
                   8203:             }
                   8204:         }
                   8205:         return 'ok';
                   8206:     }
                   8207:     return 'error';
                   8208: }
                   8209: 
1.242     www      8210: sub get_query_reply {
1.1172.2.79  raeburn  8211:     my ($queryid,$sleep,$loopmax) = @_;
                   8212:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8213:         $sleep = 0.2;
                   8214:     }
                   8215:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8216:         $loopmax = 100;
                   8217:     }
1.1117    foxr     8218:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8219:     my $reply='';
1.1172.2.79  raeburn  8220:     for (1..$loopmax) {
                   8221: 	sleep($sleep);
1.240     www      8222:         if (-e $replyfile.'.end') {
1.1172.2.93.4  7(raebur 8223:7): 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8224: 		$reply = join('',<$fh>);
                   8225: 		close($fh);
1.240     www      8226: 	   } else { return 'error: reply_file_error'; }
1.242     www      8227:            return &unescape($reply);
                   8228: 	}
1.240     www      8229:     }
1.242     www      8230:     return 'timeout:'.$queryid;
1.240     www      8231: }
                   8232: 
                   8233: sub courselog_query {
1.241     www      8234: #
                   8235: # possible filters:
                   8236: # url: url or symb
                   8237: # username
                   8238: # domain
                   8239: # action: view, submit, grade
                   8240: # start: timestamp
                   8241: # end: timestamp
                   8242: #
1.240     www      8243:     my (%filters)=@_;
1.620     albertel 8244:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8245:     if ($filters{'url'}) {
                   8246: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8247:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8248:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8249:     }
1.620     albertel 8250:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8251:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8252:     return &log_query($cname,$cdom,'courselog',%filters);
                   8253: }
                   8254: 
                   8255: sub userlog_query {
1.858     raeburn  8256: #
                   8257: # possible filters:
                   8258: # action: log check role
                   8259: # start: timestamp
                   8260: # end: timestamp
                   8261: #
1.240     www      8262:     my ($uname,$udom,%filters)=@_;
                   8263:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8264: }
                   8265: 
1.506     raeburn  8266: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8267: 
                   8268: sub auto_run {
1.508     raeburn  8269:     my ($cnum,$cdom) = @_;
1.876     raeburn  8270:     my $response = 0;
                   8271:     my $settings;
                   8272:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8273:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8274:         $settings = $domconfig{'autoenroll'};
                   8275:         if ($settings->{'run'} eq '1') {
                   8276:             $response = 1;
                   8277:         }
                   8278:     } else {
1.934     raeburn  8279:         my $homeserver;
                   8280:         if (&is_course($cdom,$cnum)) {
                   8281:             $homeserver = &homeserver($cnum,$cdom);
                   8282:         } else {
                   8283:             $homeserver = &domain($cdom,'primary');
                   8284:         }
                   8285:         if ($homeserver ne 'no_host') {
                   8286:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8287:         }
1.876     raeburn  8288:     }
1.506     raeburn  8289:     return $response;
                   8290: }
1.776     albertel 8291: 
1.506     raeburn  8292: sub auto_get_sections {
1.508     raeburn  8293:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8294:     my $homeserver;
                   8295:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8296:         $homeserver = &homeserver($cnum,$cdom);
                   8297:     }
                   8298:     if (!defined($homeserver)) { 
                   8299:         if ($cdom =~ /^$match_domain$/) {
                   8300:             $homeserver = &domain($cdom,'primary');
                   8301:         }
                   8302:     }
                   8303:     my @secs;
                   8304:     if (defined($homeserver)) {
                   8305:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8306:         unless ($response eq 'refused') {
                   8307:             @secs = split(/:/,$response);
                   8308:         }
1.506     raeburn  8309:     }
                   8310:     return @secs;
                   8311: }
1.776     albertel 8312: 
1.506     raeburn  8313: sub auto_new_course {
1.1099    raeburn  8314:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8315:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8316:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8317:     return $response;
                   8318: }
1.776     albertel 8319: 
1.506     raeburn  8320: sub auto_validate_courseID {
1.508     raeburn  8321:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8322:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8323:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8324:     return $response;
                   8325: }
1.776     albertel 8326: 
1.1007    raeburn  8327: sub auto_validate_instcode {
1.1020    raeburn  8328:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8329:     my ($homeserver,$response);
                   8330:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8331:         $homeserver = &homeserver($cnum,$cdom);
                   8332:     }
                   8333:     if (!defined($homeserver)) {
                   8334:         if ($cdom =~ /^$match_domain$/) {
                   8335:             $homeserver = &domain($cdom,'primary');
                   8336:         }
                   8337:     }
1.1065    raeburn  8338:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8339:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  8340:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8341:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8342: }
                   8343: 
1.506     raeburn  8344: sub auto_create_password {
1.873     raeburn  8345:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8346:     my ($homeserver,$response);
1.506     raeburn  8347:     my $create_passwd = 0;
                   8348:     my $authchk = '';
1.873     raeburn  8349:     if ($udom =~ /^$match_domain$/) {
                   8350:         $homeserver = &domain($udom,'primary');
                   8351:     }
                   8352:     if ($homeserver eq '') {
                   8353:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8354:             $homeserver = &homeserver($cnum,$cdom);
                   8355:         }
                   8356:     }
                   8357:     if ($homeserver eq '') {
                   8358:         $authchk = 'nodomain';
1.506     raeburn  8359:     } else {
1.873     raeburn  8360:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8361:         if ($response eq 'refused') {
                   8362:             $authchk = 'refused';
                   8363:         } else {
1.901     albertel 8364:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8365:         }
1.506     raeburn  8366:     }
                   8367:     return ($authparam,$create_passwd,$authchk);
                   8368: }
                   8369: 
1.706     raeburn  8370: sub auto_photo_permission {
                   8371:     my ($cnum,$cdom,$students) = @_;
                   8372:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8373:     my ($outcome,$perm_reqd,$conditions) = 
                   8374: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8375:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8376: 	return (undef,undef);
                   8377:     }
1.706     raeburn  8378:     return ($outcome,$perm_reqd,$conditions);
                   8379: }
                   8380: 
                   8381: sub auto_checkphotos {
                   8382:     my ($uname,$udom,$pid) = @_;
                   8383:     my $homeserver = &homeserver($uname,$udom);
                   8384:     my ($result,$resulttype);
                   8385:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8386: 				   &escape($uname).':'.&escape($pid),
                   8387: 				   $homeserver));
1.709     albertel 8388:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8389: 	return (undef,undef);
                   8390:     }
1.706     raeburn  8391:     if ($outcome) {
                   8392:         ($result,$resulttype) = split(/:/,$outcome);
                   8393:     } 
                   8394:     return ($result,$resulttype);
                   8395: }
                   8396: 
                   8397: sub auto_photochoice {
                   8398:     my ($cnum,$cdom) = @_;
                   8399:     my $homeserver = &homeserver($cnum,$cdom);
                   8400:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8401: 						       &escape($cdom),
                   8402: 						       $homeserver)));
1.709     albertel 8403:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8404: 	return (undef,undef);
                   8405:     }
1.706     raeburn  8406:     return ($update,$comment);
                   8407: }
                   8408: 
                   8409: sub auto_photoupdate {
                   8410:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8411:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8412:     my $host=&hostname($homeserver);
1.706     raeburn  8413:     my $cmd = '';
                   8414:     my $maxtries = 1;
1.800     albertel 8415:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8416:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8417:     }
                   8418:     $cmd =~ s/%%$//;
                   8419:     $cmd = &escape($cmd);
                   8420:     my $query = 'institutionalphotos';
                   8421:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8422:     unless ($queryid=~/^\Q$host\E\_/) {
                   8423:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8424:         return 'error: '.$queryid;
                   8425:     }
                   8426:     my $reply = &get_query_reply($queryid);
                   8427:     my $tries = 1;
                   8428:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8429:         $reply = &get_query_reply($queryid);
                   8430:         $tries ++;
                   8431:     }
                   8432:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8433:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8434:     } else {
                   8435:         my @responses = split(/:/,$reply);
                   8436:         my $outcome = shift(@responses); 
                   8437:         foreach my $item (@responses) {
                   8438:             my ($key,$value) = split(/=/,$item);
                   8439:             $$photo{$key} = $value;
                   8440:         }
                   8441:         return $outcome;
                   8442:     }
                   8443:     return 'error';
                   8444: }
                   8445: 
1.521     raeburn  8446: sub auto_instcode_format {
1.793     albertel 8447:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8448: 	$cat_order) = @_;
1.521     raeburn  8449:     my $courses = '';
1.772     raeburn  8450:     my @homeservers;
1.521     raeburn  8451:     if ($caller eq 'global') {
1.841     albertel 8452: 	my %servers = &get_servers($codedom,'library');
                   8453: 	foreach my $tryserver (keys(%servers)) {
                   8454: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8455: 		push(@homeservers,$tryserver);
                   8456: 	    }
1.584     raeburn  8457:         }
1.1022    raeburn  8458:     } elsif ($caller eq 'requests') {
                   8459:         if ($codedom =~ /^$match_domain$/) {
                   8460:             my $chome = &domain($codedom,'primary');
                   8461:             unless ($chome eq 'no_host') {
                   8462:                 push(@homeservers,$chome);
                   8463:             }
                   8464:         }
1.521     raeburn  8465:     } else {
1.772     raeburn  8466:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8467:     }
1.793     albertel 8468:     foreach my $code (keys(%{$instcodes})) {
                   8469:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8470:     }
                   8471:     chop($courses);
1.772     raeburn  8472:     my $ok_response = 0;
                   8473:     my $response;
                   8474:     while (@homeservers > 0 && $ok_response == 0) {
                   8475:         my $server = shift(@homeservers); 
                   8476:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8477:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8478:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8479: 		split(/:/,$response);
1.772     raeburn  8480:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8481:             push(@{$codetitles},&str2array($codetitles_str));
                   8482:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8483:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8484:             $ok_response = 1;
                   8485:         }
                   8486:     }
                   8487:     if ($ok_response) {
1.521     raeburn  8488:         return 'ok';
1.772     raeburn  8489:     } else {
                   8490:         return $response;
1.521     raeburn  8491:     }
                   8492: }
                   8493: 
1.792     raeburn  8494: sub auto_instcode_defaults {
                   8495:     my ($domain,$returnhash,$code_order) = @_;
                   8496:     my @homeservers;
1.841     albertel 8497: 
                   8498:     my %servers = &get_servers($domain,'library');
                   8499:     foreach my $tryserver (keys(%servers)) {
                   8500: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8501: 	    push(@homeservers,$tryserver);
                   8502: 	}
1.792     raeburn  8503:     }
1.841     albertel 8504: 
1.792     raeburn  8505:     my $response;
1.841     albertel 8506:     foreach my $server (@homeservers) {
1.792     raeburn  8507:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8508:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8509: 	
                   8510: 	foreach my $pair (split(/\&/,$response)) {
                   8511: 	    my ($name,$value)=split(/\=/,$pair);
                   8512: 	    if ($name eq 'code_order') {
                   8513: 		@{$code_order} = split(/\&/,&unescape($value));
                   8514: 	    } else {
                   8515: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8516: 	    }
                   8517: 	}
                   8518: 	return 'ok';
1.792     raeburn  8519:     }
1.841     albertel 8520: 
                   8521:     return $response;
1.1003    raeburn  8522: }
                   8523: 
                   8524: sub auto_possible_instcodes {
1.1007    raeburn  8525:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8526:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8527:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8528:         return;
                   8529:     }
1.1003    raeburn  8530:     my (@homeservers,$uhome);
                   8531:     if (defined(&domain($domain,'primary'))) {
                   8532:         $uhome=&domain($domain,'primary');
                   8533:         push(@homeservers,&domain($domain,'primary'));
                   8534:     } else {
                   8535:         my %servers = &get_servers($domain,'library');
                   8536:         foreach my $tryserver (keys(%servers)) {
                   8537:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8538:                 push(@homeservers,$tryserver);
                   8539:             }
                   8540:         }
                   8541:     }
                   8542:     my $response;
                   8543:     foreach my $server (@homeservers) {
                   8544:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8545:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8546:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8547:             split(':',$response);
                   8548:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8549:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8550:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8551:             my ($name,$value)=split('=',$item);
                   8552:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8553:         }
                   8554:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8555:             my ($name,$value)=split('=',$item);
                   8556:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8557:         }
                   8558:         return 'ok';
                   8559:     }
                   8560:     return $response;
                   8561: }
1.792     raeburn  8562: 
1.1010    raeburn  8563: sub auto_courserequest_checks {
                   8564:     my ($dom) = @_;
1.1020    raeburn  8565:     my ($homeserver,%validations);
                   8566:     if ($dom =~ /^$match_domain$/) {
                   8567:         $homeserver = &domain($dom,'primary');
                   8568:     }
                   8569:     unless ($homeserver eq 'no_host') {
                   8570:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8571:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8572:             my @items = split(/&/,$response);
                   8573:             foreach my $item (@items) {
                   8574:                 my ($key,$value) = split('=',$item);
                   8575:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8576:             }
                   8577:         }
                   8578:     }
1.1010    raeburn  8579:     return %validations; 
                   8580: }
                   8581: 
1.1020    raeburn  8582: sub auto_courserequest_validation {
1.1172.2.43  raeburn  8583:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8584:     my ($homeserver,$response);
                   8585:     if ($dom =~ /^$match_domain$/) {
                   8586:         $homeserver = &domain($dom,'primary');
                   8587:     }
1.1172.2.43  raeburn  8588:     unless ($homeserver eq 'no_host') {
                   8589:         my $customdata;
                   8590:         if (ref($custominfo) eq 'HASH') {
                   8591:             $customdata = &freeze_escape($custominfo);
                   8592:         }
1.1020    raeburn  8593:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8594:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  8595:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8596:                                     $customdata,$homeserver));
1.1020    raeburn  8597:     }
                   8598:     return $response;
                   8599: }
                   8600: 
1.777     albertel 8601: sub auto_validate_class_sec {
1.918     raeburn  8602:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8603:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8604:     my $ownerlist;
                   8605:     if (ref($owners) eq 'ARRAY') {
                   8606:         $ownerlist = join(',',@{$owners});
                   8607:     } else {
                   8608:         $ownerlist = $owners;
                   8609:     }
1.773     raeburn  8610:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8611:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8612:     return $response;
                   8613: }
                   8614: 
1.1172.2.93.4  10(raebu 8615:18): sub auto_validate_instclasses {
                   8616:18):     my ($cdom,$cnum,$owners,$classesref) = @_;
                   8617:18):     my ($homeserver,%validations);
                   8618:18):     $homeserver = &homeserver($cnum,$cdom);
                   8619:18):     unless ($homeserver eq 'no_host') {
                   8620:18):         my $ownerlist;
                   8621:18):         if (ref($owners) eq 'ARRAY') {
                   8622:18):             $ownerlist = join(',',@{$owners});
                   8623:18):         } else {
                   8624:18):             $ownerlist = $owners;
                   8625:18):         }
                   8626:18):         if (ref($classesref) eq 'HASH') {
                   8627:18):             my $classes = &freeze_escape($classesref);
                   8628:18):             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   8629:18):                                 ':'.$cdom.':'.$classes,$homeserver);
                   8630:18):             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8631:18):                 my @items = split(/&/,$response);
                   8632:18):                 foreach my $item (@items) {
                   8633:18):                     my ($key,$value) = split('=',$item);
                   8634:18):                     $validations{&unescape($key)} = &thaw_unescape($value);
                   8635:18):                 }
                   8636:18):             }
                   8637:18):         }
                   8638:18):     }
                   8639:18):     return %validations;
                   8640:18): }
                   8641:18): 
1.1172.2.38  raeburn  8642: sub auto_crsreq_update {
                   8643:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  8644:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  8645:     my ($homeserver,%crsreqresponse);
                   8646:     if ($cdom =~ /^$match_domain$/) {
                   8647:         $homeserver = &domain($cdom,'primary');
                   8648:     }
                   8649:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8650:         my $info;
                   8651:         if (ref($inbound) eq 'HASH') {
                   8652:             $info = &freeze_escape($inbound);
                   8653:         }
                   8654:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8655:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8656:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  8657:                             &escape($title).':'.&escape($code).':'.
                   8658:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  8659:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8660:             my @items = split(/&/,$response);
                   8661:             foreach my $item (@items) {
                   8662:                 my ($key,$value) = split('=',$item);
                   8663:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8664:             }
                   8665:         }
                   8666:     }
                   8667:     return \%crsreqresponse;
                   8668: }
                   8669: 
1.1172.2.78  raeburn  8670: sub auto_export_grades {
                   8671:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   8672:     my ($homeserver,%exportresponse);
                   8673:     if ($cdom =~ /^$match_domain$/) {
                   8674:         $homeserver = &domain($cdom,'primary');
                   8675:     }
                   8676:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8677:         my $info;
                   8678:         if (ref($inforef) eq 'HASH') {
                   8679:             $info = &freeze_escape($inforef);
                   8680:         }
                   8681:         if (ref($gradesref) eq 'HASH') {
                   8682:             my $grades = &freeze_escape($gradesref);
                   8683:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   8684:                                 $info.':'.$grades,$homeserver);
                   8685:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   8686:                 my @items = split(/&/,$response);
                   8687:                 foreach my $item (@items) {
                   8688:                     my ($key,$value) = split('=',$item);
                   8689:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   8690:                 }
                   8691:             }
                   8692:         }
                   8693:     }
                   8694:     return \%exportresponse;
                   8695: }
                   8696: 
1.1172.2.68  raeburn  8697: sub check_instcode_cloning {
                   8698:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   8699:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8700:         return;
                   8701:     }
                   8702:     my $canclone;
                   8703:     if (@{$code_order} > 0) {
                   8704:         my $instcoderegexp ='^';
                   8705:         my @clonecodes = split(/\&/,$cloner);
                   8706:         foreach my $item (@{$code_order}) {
                   8707:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   8708:                 foreach my $pair (@clonecodes) {
                   8709:                     my ($key,$val) = split(/\=/,$pair,2);
                   8710:                     $val = &unescape($val);
                   8711:                     if ($key eq $item) {
                   8712:                         $instcoderegexp .= '('.$val.')';
                   8713:                         last;
                   8714:                     }
                   8715:                 }
                   8716:             } else {
                   8717:                 $instcoderegexp .= $codedefaults->{$item};
                   8718:             }
                   8719:         }
                   8720:         $instcoderegexp .= '$';
                   8721:         my (@from,@to);
                   8722:         eval {
                   8723:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8724:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8725:         };
                   8726:         if ((@from > 0) && (@to > 0)) {
                   8727:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8728:             if (!@diffs) {
                   8729:                 $canclone = 1;
                   8730:             }
                   8731:         }
                   8732:     }
                   8733:     return $canclone;
                   8734: }
                   8735: 
                   8736: sub default_instcode_cloning {
                   8737:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   8738:     my (%codedefaults,@code_order,$canclone);
                   8739:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   8740:         %codedefaults = %{$codedefaultsref};
                   8741:         @code_order = @{$codeorderref};
                   8742:     } elsif ($clonedom) {
                   8743:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   8744:     }
                   8745:     if (($domdefclone) && (@code_order)) {
                   8746:         my @clonecodes = split(/\+/,$domdefclone);
                   8747:         my $instcoderegexp ='^';
                   8748:         foreach my $item (@code_order) {
                   8749:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   8750:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   8751:             } else {
                   8752:                 $instcoderegexp .= $codedefaults{$item};
                   8753:             }
                   8754:         }
                   8755:         $instcoderegexp .= '$';
                   8756:         my (@from,@to);
                   8757:         eval {
                   8758:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8759:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8760:         };
                   8761:         if ((@from > 0) && (@to > 0)) {
                   8762:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8763:             if (!@diffs) {
                   8764:                 $canclone = 1;
                   8765:             }
                   8766:         }
                   8767:     }
                   8768:     return $canclone;
                   8769: }
                   8770: 
1.679     raeburn  8771: # ------------------------------------------------------- Course Group routines
                   8772: 
                   8773: sub get_coursegroups {
1.809     raeburn  8774:     my ($cdom,$cnum,$group,$namespace) = @_;
                   8775:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  8776: }
                   8777: 
1.679     raeburn  8778: sub modify_coursegroup {
                   8779:     my ($cdom,$cnum,$groupsettings) = @_;
                   8780:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   8781: }
                   8782: 
1.809     raeburn  8783: sub toggle_coursegroup_status {
                   8784:     my ($cdom,$cnum,$group,$action) = @_;
                   8785:     my ($from_namespace,$to_namespace);
                   8786:     if ($action eq 'delete') {
                   8787:         $from_namespace = 'coursegroups';
                   8788:         $to_namespace = 'deleted_groups';
                   8789:     } else {
                   8790:         $from_namespace = 'deleted_groups';
                   8791:         $to_namespace = 'coursegroups';
                   8792:     }
                   8793:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  8794:     if (my $tmp = &error(%curr_group)) {
                   8795:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   8796:         return ('read error',$tmp);
                   8797:     } else {
                   8798:         my %savedsettings = %curr_group; 
1.809     raeburn  8799:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  8800:         my $deloutcome;
                   8801:         if ($result eq 'ok') {
1.809     raeburn  8802:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  8803:         } else {
                   8804:             return ('write error',$result);
                   8805:         }
                   8806:         if ($deloutcome eq 'ok') {
                   8807:             return 'ok';
                   8808:         } else {
                   8809:             return ('delete error',$deloutcome);
                   8810:         }
                   8811:     }
                   8812: }
                   8813: 
1.679     raeburn  8814: sub modify_group_roles {
1.957     raeburn  8815:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  8816:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   8817:     my $role = 'gr/'.&escape($userprivs);
                   8818:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  8819:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  8820:     if ($result eq 'ok') {
                   8821:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   8822:     }
1.679     raeburn  8823:     return $result;
                   8824: }
                   8825: 
                   8826: sub modify_coursegroup_membership {
                   8827:     my ($cdom,$cnum,$membership) = @_;
                   8828:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   8829:     return $result;
                   8830: }
                   8831: 
1.682     raeburn  8832: sub get_active_groups {
                   8833:     my ($udom,$uname,$cdom,$cnum) = @_;
                   8834:     my $now = time;
                   8835:     my %groups = ();
                   8836:     foreach my $key (keys(%env)) {
1.811     albertel 8837:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  8838:             my ($start,$end) = split(/\./,$env{$key});
                   8839:             if (($end!=0) && ($end<$now)) { next; }
                   8840:             if (($start!=0) && ($start>$now)) { next; }
                   8841:             if ($1 eq $cdom && $2 eq $cnum) {
                   8842:                 $groups{$3} = $env{$key} ;
                   8843:             }
                   8844:         }
                   8845:     }
                   8846:     return %groups;
                   8847: }
                   8848: 
1.683     raeburn  8849: sub get_group_membership {
                   8850:     my ($cdom,$cnum,$group) = @_;
                   8851:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   8852: }
                   8853: 
                   8854: sub get_users_groups {
                   8855:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  8856:     my @usersgroups;
1.683     raeburn  8857:     my $cachetime=1800;
                   8858: 
                   8859:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  8860:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   8861:     if (defined($cached)) {
1.734     albertel 8862:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  8863:     } else {  
                   8864:         $grouplist = '';
1.816     raeburn  8865:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  8866:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  8867:         my $access_end = $env{'course.'.$courseid.
                   8868:                               '.default_enrollment_end_date'};
                   8869:         my $now = time;
                   8870:         foreach my $key (keys(%roleshash)) {
                   8871:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   8872:                 my $group = $1;
                   8873:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   8874:                     my $start = $2;
                   8875:                     my $end = $1;
                   8876:                     if ($start == -1) { next; } # deleted from group
                   8877:                     if (($start!=0) && ($start>$now)) { next; }
                   8878:                     if (($end!=0) && ($end<$now)) {
                   8879:                         if ($access_end && $access_end < $now) {
                   8880:                             if ($access_end - $end < 86400) {
                   8881:                                 push(@usersgroups,$group);
1.733     raeburn  8882:                             }
                   8883:                         }
1.817     raeburn  8884:                         next;
1.733     raeburn  8885:                     }
1.817     raeburn  8886:                     push(@usersgroups,$group);
1.683     raeburn  8887:                 }
                   8888:             }
                   8889:         }
1.817     raeburn  8890:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8891:         $grouplist = join(':',@usersgroups);
                   8892:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8893:     }
1.733     raeburn  8894:     return @usersgroups;
1.683     raeburn  8895: }
                   8896: 
                   8897: sub devalidate_getgroups_cache {
                   8898:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8899:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8900: 
1.683     raeburn  8901:     my $hashid="$udom:$uname:$courseid";
                   8902:     &devalidate_cache_new('getgroups',$hashid);
                   8903: }
                   8904: 
1.12      www      8905: # ------------------------------------------------------------------ Plain Text
                   8906: 
                   8907: sub plaintext {
1.988     raeburn  8908:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8909:     if ($short =~ m{^cr/}) {
1.758     albertel 8910: 	return (split('/',$short))[-1];
                   8911:     }
1.742     raeburn  8912:     if (!defined($cid)) {
                   8913:         $cid = $env{'request.course.id'};
                   8914:     }
                   8915:     my %rolenames = (
1.1008    raeburn  8916:                       Course    => 'std',
                   8917:                       Community => 'alt1',
1.742     raeburn  8918:                     );
1.1037    raeburn  8919:     if ($cid ne '') {
                   8920:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8921:             unless ($forcedefault) {
                   8922:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8923:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8924:                 return &Apache::lonlocal::mt($roletext);
                   8925:             }
                   8926:         }
                   8927:     }
                   8928:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8929:         (defined($rolenames{$type})) && 
                   8930:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8931:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8932:     } elsif ($cid ne '') {
                   8933:         my $crstype = $env{'course.'.$cid.'.type'};
                   8934:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8935:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8936:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8937:         }
1.742     raeburn  8938:     }
1.1037    raeburn  8939:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8940: }
                   8941: 
                   8942: # ----------------------------------------------------------------- Assign Role
                   8943: 
                   8944: sub assignrole {
1.957     raeburn  8945:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8946:         $context)=@_;
1.21      www      8947:     my $mrole;
                   8948:     if ($role =~ /^cr\//) {
1.393     www      8949:         my $cwosec=$url;
1.811     albertel 8950:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8951: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8952:            my $refused = 1;
                   8953:            if ($context eq 'requestcourses') {
                   8954:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8955:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8956:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8957:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8958:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8959:                            if ($crsenv{'internal.courseowner'} eq
                   8960:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8961:                                $refused = '';
                   8962:                            }
                   8963:                        }
                   8964:                    }
                   8965:                }
                   8966:            }
                   8967:            if ($refused) {
                   8968:                &logthis('Refused custom assignrole: '.
                   8969:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8970:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8971:                return 'refused';
                   8972:            }
1.104     www      8973:         }
1.21      www      8974:         $mrole='cr';
1.678     raeburn  8975:     } elsif ($role =~ /^gr\//) {
                   8976:         my $cwogrp=$url;
1.811     albertel 8977:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8978:         unless (&allowed('mdg',$cwogrp)) {
                   8979:             &logthis('Refused group assignrole: '.
                   8980:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   8981:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   8982:             return 'refused';
                   8983:         }
                   8984:         $mrole='gr';
1.21      www      8985:     } else {
1.82      www      8986:         my $cwosec=$url;
1.811     albertel 8987:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  8988:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   8989:             my $refused;
                   8990:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   8991:                 if (!(&allowed('c'.$role,$url))) {
                   8992:                     $refused = 1;
                   8993:                 }
                   8994:             } else {
                   8995:                 $refused = 1;
                   8996:             }
1.947     raeburn  8997:             if ($refused) {
1.1045    raeburn  8998:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8999:                 if (!$selfenroll && $context eq 'course') {
                   9000:                     my %crsenv;
                   9001:                     if ($role eq 'cc' || $role eq 'co') {
                   9002:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9003:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9004:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9005:                                 if ($crsenv{'internal.courseowner'} eq 
                   9006:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9007:                                     $refused = '';
                   9008:                                 }
                   9009:                             }
                   9010:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9011:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9012:                                 if ($crsenv{'internal.courseowner'} eq 
                   9013:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9014:                                     $refused = '';
                   9015:                                 }
                   9016:                             }
                   9017:                         }
                   9018:                     }
                   9019:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  9020:                     $refused = '';
1.1017    raeburn  9021:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9022:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9023:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9024:                         my $wrongcc;
                   9025:                         if ($cnum =~ /^$match_community$/) {
                   9026:                             $wrongcc = 1 if ($role eq 'cc');
                   9027:                         } else {
                   9028:                             $wrongcc = 1 if ($role eq 'co');
                   9029:                         }
                   9030:                         unless ($wrongcc) {
                   9031:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9032:                             if ($crsenv{'internal.courseowner'} eq 
                   9033:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9034:                                 $refused = '';
                   9035:                             }
1.1017    raeburn  9036:                         }
                   9037:                     }
1.1172.2.9  raeburn  9038:                 } elsif ($context eq 'requestauthor') {
                   9039:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   9040:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9041:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9042:                             $refused = '';
                   9043:                         } else {
                   9044:                             my %domdefaults = &get_domain_defaults($udom);
                   9045:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9046:                                 my $checkbystatus;
                   9047:                                 if ($env{'user.adv'}) {
                   9048:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9049:                                     if ($disposition eq 'automatic') {
                   9050:                                         $refused = '';
                   9051:                                     } elsif ($disposition eq '') {
                   9052:                                         $checkbystatus = 1;
                   9053:                                     }
                   9054:                                 } else {
                   9055:                                     $checkbystatus = 1;
                   9056:                                 }
                   9057:                                 if ($checkbystatus) {
                   9058:                                     if ($env{'environment.inststatus'}) {
                   9059:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9060:                                         foreach my $type (@inststatuses) {
                   9061:                                             if (($type ne '') &&
                   9062:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9063:                                                 $refused = '';
                   9064:                                             }
                   9065:                                         }
                   9066:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9067:                                         $refused = '';
                   9068:                                     }
                   9069:                                 }
                   9070:                             }
                   9071:                         }
                   9072:                     }
1.1017    raeburn  9073:                 }
                   9074:                 if ($refused) {
1.947     raeburn  9075:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9076:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9077: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9078:                     return 'refused';
                   9079:                 }
1.932     raeburn  9080:             }
1.1131    raeburn  9081:         } elsif ($role eq 'au') {
                   9082:             if ($url ne '/'.$udom.'/') {
                   9083:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9084:                          ' to assign author role for '.$uname.':'.$udom.
                   9085:                          ' in domain: '.$url.' refused (wrong domain).');
                   9086:                 return 'refused';
                   9087:             }
1.104     www      9088:         }
1.21      www      9089:         $mrole=$role;
                   9090:     }
1.620     albertel 9091:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9092:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9093:     if ($end) { $command.='_'.$end; }
1.21      www      9094:     if ($start) {
                   9095: 	if ($end) { 
1.81      www      9096:            $command.='_'.$start; 
1.21      www      9097:         } else {
1.81      www      9098:            $command.='_0_'.$start;
1.21      www      9099:         }
                   9100:     }
1.739     raeburn  9101:     my $origstart = $start;
                   9102:     my $origend = $end;
1.957     raeburn  9103:     my $delflag;
1.357     www      9104: # actually delete
                   9105:     if ($deleteflag) {
1.373     www      9106: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9107: # modify command to delete the role
1.620     albertel 9108:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9109:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9110: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9111: # set start and finish to negative values for userrolelog
                   9112:            $start=-1;
                   9113:            $end=-1;
1.957     raeburn  9114:            $delflag = 1;
1.357     www      9115:         }
                   9116:     }
                   9117: # send command
1.349     www      9118:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9119: # log new user role if status is ok
1.349     www      9120:     if ($answer eq 'ok') {
1.663     raeburn  9121: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  9122:         if (($role eq 'cc') || ($role eq 'in') ||
                   9123:             ($role eq 'ep') || ($role eq 'ad') ||
                   9124:             ($role eq 'ta') || ($role eq 'st') ||
                   9125:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9126:             ($role eq 'co')) {
1.1172.2.13  raeburn  9127: # for course roles, perform group memberships changes triggered by role change.
                   9128:             unless ($role =~ /^gr/) {
                   9129:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9130:                                                  $origstart,$selfenroll,$context);
                   9131:             }
1.1172.2.9  raeburn  9132:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9133:                            $selfenroll,$context);
                   9134:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  9135:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9136:                  ($role eq 'da')) {
1.1172.2.9  raeburn  9137:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9138:                            $context);
                   9139:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9140:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9141:                              $context);
                   9142:         }
1.1053    raeburn  9143:         if ($role eq 'cc') {
                   9144:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9145:         }
1.349     www      9146:     }
                   9147:     return $answer;
1.169     harris41 9148: }
                   9149: 
1.1053    raeburn  9150: sub autoupdate_coowners {
                   9151:     my ($url,$end,$start,$uname,$udom) = @_;
                   9152:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9153:     if (($cdom ne '') && ($cnum ne '')) {
                   9154:         my $now = time;
                   9155:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9156:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9157:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9158:             my $instcode = $coursehash{'internal.coursecode'};
                   9159:             if ($instcode ne '') {
1.1056    raeburn  9160:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9161:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9162:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9163:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9164:                         if ($result eq 'valid') {
                   9165:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9166:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9167:                                     push(@newcoowners,$coowner);
                   9168:                                 }
                   9169:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9170:                                     push(@newcoowners,$uname.':'.$udom);
                   9171:                                 }
                   9172:                                 @newcoowners = sort(@newcoowners);
                   9173:                             } else {
                   9174:                                 push(@newcoowners,$uname.':'.$udom);
                   9175:                             }
                   9176:                         } else {
                   9177:                             if ($coursehash{'internal.co-owners'}) {
                   9178:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9179:                                     unless ($coowner eq $uname.':'.$udom) {
                   9180:                                         push(@newcoowners,$coowner);
                   9181:                                     }
                   9182:                                 }
                   9183:                                 unless (@newcoowners > 0) {
                   9184:                                     $delcoowners = 1;
                   9185:                                     $coowners = '';
                   9186:                                 }
                   9187:                             }
                   9188:                         }
                   9189:                         if (@newcoowners || $delcoowners) {
                   9190:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9191:                                             $delcoowners,@newcoowners);
                   9192:                         }
                   9193:                     }
                   9194:                 }
                   9195:             }
                   9196:         }
                   9197:     }
                   9198: }
                   9199: 
                   9200: sub store_coowners {
                   9201:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9202:     my $cid = $cdom.'_'.$cnum;
                   9203:     my ($coowners,$delresult,$putresult);
                   9204:     if (@newcoowners) {
                   9205:         $coowners = join(',',@newcoowners);
                   9206:         my %coownershash = (
                   9207:                             'internal.co-owners' => $coowners,
                   9208:                            );
                   9209:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9210:         if ($putresult eq 'ok') {
                   9211:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9212:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9213:             }
                   9214:         }
                   9215:     }
                   9216:     if ($delcoowners) {
                   9217:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9218:         if ($delresult eq 'ok') {
                   9219:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9220:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9221:             }
                   9222:         }
                   9223:     }
                   9224:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9225:         my %crsinfo =
                   9226:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9227:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9228:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9229:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9230:         }
                   9231:     }
                   9232: }
                   9233: 
1.169     harris41 9234: # -------------------------------------------------- Modify user authentication
1.197     www      9235: # Overrides without validation
                   9236: 
1.169     harris41 9237: sub modifyuserauth {
                   9238:     my ($udom,$uname,$umode,$upass)=@_;
                   9239:     my $uhome=&homeserver($uname,$udom);
1.197     www      9240:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   9241:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9242:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9243:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9244:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9245: 		     &escape($upass),$uhome);
1.620     albertel 9246:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9247:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9248:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9249:     &log($udom,,$uname,$uhome,
1.620     albertel 9250:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9251:                                      $env{'user.name'}.', '.$umode.
1.197     www      9252:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9253:     unless ($reply eq 'ok') {
1.197     www      9254:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9255: 	return 'error: '.$reply;
                   9256:     }   
1.170     harris41 9257:     return 'ok';
1.80      www      9258: }
                   9259: 
1.81      www      9260: # --------------------------------------------------------------- Modify a user
1.80      www      9261: 
1.81      www      9262: sub modifyuser {
1.206     matthew  9263:     my ($udom,    $uname, $uid,
                   9264:         $umode,   $upass, $first,
                   9265:         $middle,  $last,  $gene,
1.1058    raeburn  9266:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9267:     $udom= &LONCAPA::clean_domain($udom);
                   9268:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9269:     my $showcandelete = 'none';
                   9270:     if (ref($candelete) eq 'ARRAY') {
                   9271:         if (@{$candelete} > 0) {
                   9272:             $showcandelete = join(', ',@{$candelete});
                   9273:         }
                   9274:     }
1.81      www      9275:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9276:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9277: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9278:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9279:                                      ' desiredhome not specified'). 
1.620     albertel 9280:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9281:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9282:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9283:     my $newuser;
                   9284:     if ($uhome eq 'no_host') {
                   9285:         $newuser = 1;
                   9286:     }
1.80      www      9287: # ----------------------------------------------------------------- Create User
1.406     albertel 9288:     if (($uhome eq 'no_host') && 
                   9289: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      9290:         my $unhome='';
1.844     albertel 9291:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9292:             $unhome = $desiredhome;
1.620     albertel 9293: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9294: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9295:         } else { # load balancing routine for determining $unhome
1.81      www      9296:             my $loadm=10000000;
1.841     albertel 9297: 	    my %servers = &get_servers($udom,'library');
                   9298: 	    foreach my $tryserver (keys(%servers)) {
                   9299: 		my $answer=reply('load',$tryserver);
                   9300: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9301: 		    $loadm=$answer;
                   9302: 		    $unhome=$tryserver;
                   9303: 		}
1.80      www      9304: 	    }
                   9305:         }
                   9306:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9307: 	    return 'error: unable to find a home server for '.$uname.
                   9308:                    ' in domain '.$udom;
1.80      www      9309:         }
                   9310:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9311:                          &escape($upass),$unhome);
                   9312: 	unless ($reply eq 'ok') {
                   9313:             return 'error: '.$reply;
                   9314:         }   
1.230     stredwic 9315:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9316:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9317: 	    return 'error: unable verify users home machine.';
1.80      www      9318:         }
1.209     matthew  9319:     }   # End of creation of new user
1.80      www      9320: # ---------------------------------------------------------------------- Add ID
                   9321:     if ($uid) {
                   9322:        $uid=~tr/A-Z/a-z/;
                   9323:        my %uidhash=&idrget($udom,$uname);
1.196     www      9324:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9325:          && (!$forceid)) {
1.80      www      9326: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9327: 	      return 'error: user id "'.$uid.'" does not match '.
                   9328:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9329:           }
                   9330:        } else {
                   9331: 	  &idput($udom,($uname => $uid));
                   9332:        }
                   9333:     }
                   9334: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9335:     my @tmp=&get('environment',
1.899     raeburn  9336: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9337:                     'permanentemail','inststatus'],
1.134     albertel 9338: 		   $udom,$uname);
1.1075    raeburn  9339:     my (%names,%oldnames);
1.313     matthew  9340:     if ($tmp[0] =~ m/^error:.*/) { 
                   9341:         %names=(); 
                   9342:     } else {
                   9343:         %names = @tmp;
1.1075    raeburn  9344:         %oldnames = %names;
1.313     matthew  9345:     }
1.388     www      9346: #
1.1058    raeburn  9347: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9348: # of users did not contain them), do not overwrite existing values
                   9349: # unless field is in $candelete array ref.  
                   9350: #
                   9351: 
                   9352:     my @fields = ('firstname','middlename','lastname','generation',
                   9353:                   'permanentemail','id');
                   9354:     my %newvalues;
                   9355:     if (ref($candelete) eq 'ARRAY') {
                   9356:         foreach my $field (@fields) {
                   9357:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9358:                 if ($field eq 'firstname') {
                   9359:                     $names{$field} = $first;
                   9360:                 } elsif ($field eq 'middlename') {
                   9361:                     $names{$field} = $middle;
                   9362:                 } elsif ($field eq 'lastname') {
                   9363:                     $names{$field} = $last;
                   9364:                 } elsif ($field eq 'generation') { 
                   9365:                     $names{$field} = $gene;
                   9366:                 } elsif ($field eq 'permanentemail') {
                   9367:                     $names{$field} = $email;
                   9368:                 } elsif ($field eq 'id') {
                   9369:                     $names{$field}  = $uid;
                   9370:                 }
                   9371:             }
                   9372:         }
                   9373:     }
1.388     www      9374:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9375:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9376:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9377:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9378:     if ($email) {
                   9379:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9380:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9381:     }
1.899     raeburn  9382:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9383:     if (defined($inststatus)) {
                   9384:         $names{'inststatus'} = '';
                   9385:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9386:         if (ref($usertypes) eq 'HASH') {
                   9387:             my @okstatuses; 
                   9388:             foreach my $item (split(/:/,$inststatus)) {
                   9389:                 if (defined($usertypes->{$item})) {
                   9390:                     push(@okstatuses,$item);  
                   9391:                 }
                   9392:             }
                   9393:             if (@okstatuses) {
                   9394:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9395:             }
                   9396:         }
                   9397:     }
1.1075    raeburn  9398:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9399:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9400:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9401:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9402:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9403:     } else {
                   9404:         $logmsg .= ' during self creation';
                   9405:     }
1.1075    raeburn  9406:     my $changed;
                   9407:     if ($newuser) {
                   9408:         $changed = 1;
                   9409:     } else {
                   9410:         foreach my $field (@fields) {
                   9411:             if ($names{$field} ne $oldnames{$field}) {
                   9412:                 $changed = 1;
                   9413:                 last;
                   9414:             }
                   9415:         }
                   9416:     }
                   9417:     unless ($changed) {
                   9418:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9419:         &logthis($logmsg);
                   9420:         return 'ok';
                   9421:     }
                   9422:     my $reply = &put('environment', \%names, $udom,$uname);
                   9423:     if ($reply ne 'ok') { 
                   9424:         return 'error: '.$reply;
                   9425:     }
1.1087    raeburn  9426:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9427:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9428:     }
1.1075    raeburn  9429:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9430:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9431:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9432:     &logthis($logmsg);
1.134     albertel 9433:     return 'ok';
1.80      www      9434: }
                   9435: 
1.81      www      9436: # -------------------------------------------------------------- Modify student
1.80      www      9437: 
1.81      www      9438: sub modifystudent {
                   9439:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9440:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  9441:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9442:     if (!$cid) {
1.620     albertel 9443: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9444: 	    return 'not_in_class';
                   9445: 	}
1.80      www      9446:     }
                   9447: # --------------------------------------------------------------- Make the user
1.81      www      9448:     my $reply=&modifyuser
1.209     matthew  9449: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9450:          $desiredhome,$email,$inststatus);
1.80      www      9451:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9452:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  9453:     # student's environment
1.297     matthew  9454:     $uid = undef if (!$forceid);
1.455     albertel 9455:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  9456: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  9457:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9458:     return $reply;
                   9459: }
                   9460: 
                   9461: sub modify_student_enrollment {
1.1172.2.23  raeburn  9462:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  9463:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9464:     my ($cdom,$cnum,$chome);
                   9465:     if (!$cid) {
1.620     albertel 9466: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9467: 	    return 'not_in_class';
                   9468: 	}
1.620     albertel 9469: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9470: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9471:     } else {
                   9472: 	($cdom,$cnum)=split(/_/,$cid);
                   9473:     }
1.620     albertel 9474:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9475:     if (!$chome) {
1.457     raeburn  9476: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9477:     }
1.455     albertel 9478:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9479:     # Make sure the user exists
1.81      www      9480:     my $uhome=&homeserver($uname,$udom);
                   9481:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9482: 	return 'error: no such user';
                   9483:     }
1.297     matthew  9484:     # Get student data if we were not given enough information
                   9485:     if (!defined($first)  || $first  eq '' || 
                   9486:         !defined($last)   || $last   eq '' || 
                   9487:         !defined($uid)    || $uid    eq '' || 
                   9488:         !defined($middle) || $middle eq '' || 
                   9489:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9490:         # They did not supply us with enough data to enroll the student, so
                   9491:         # we need to pick up more information.
1.297     matthew  9492:         my %tmp = &get('environment',
1.294     matthew  9493:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9494:                        ,$udom,$uname);
                   9495: 
1.800     albertel 9496:         #foreach my $key (keys(%tmp)) {
                   9497:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9498:         #}
1.294     matthew  9499:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9500:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9501:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9502:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9503:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9504:     }
1.556     albertel 9505:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9506:     my $user = "$uname:$udom";
                   9507:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9508:     my $reply=cput('classlist',
1.1148    raeburn  9509: 		   {$user => 
1.1172.2.76  raeburn  9510: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 9511: 		   $cdom,$cnum);
1.1148    raeburn  9512:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9513:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9514:     } else { 
1.81      www      9515: 	return 'error: '.$reply;
                   9516:     }
1.297     matthew  9517:     # Add student role to user
1.83      www      9518:     my $uurl='/'.$cid;
1.81      www      9519:     $uurl=~s/\_/\//g;
                   9520:     if ($usec) {
                   9521: 	$uurl.='/'.$usec;
                   9522:     }
1.1148    raeburn  9523:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9524:                              $selfenroll,$context);
                   9525:     if ($result ne 'ok') {
                   9526:         if ($old_entry{$user} ne '') {
                   9527:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9528:         } else {
                   9529:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9530:         }
                   9531:     }
                   9532:     return $result; 
1.21      www      9533: }
                   9534: 
1.556     albertel 9535: sub format_name {
                   9536:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9537:     my $name;
                   9538:     if ($first ne 'lastname') {
                   9539: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9540:     } else {
                   9541: 	if ($lastname=~/\S/) {
                   9542: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9543: 	    $name=~s/\s+,/,/;
                   9544: 	} else {
                   9545: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9546: 	}
                   9547:     }
                   9548:     $name=~s/^\s+//;
                   9549:     $name=~s/\s+$//;
                   9550:     $name=~s/\s+/ /g;
                   9551:     return $name;
                   9552: }
                   9553: 
1.84      www      9554: # ------------------------------------------------- Write to course preferences
                   9555: 
                   9556: sub writecoursepref {
                   9557:     my ($courseid,%prefs)=@_;
                   9558:     $courseid=~s/^\///;
                   9559:     $courseid=~s/\_/\//g;
                   9560:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9561:     my $chome=homeserver($cnum,$cdomain);
                   9562:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9563: 	return 'error: no such course';
                   9564:     }
                   9565:     my $cstring='';
1.800     albertel 9566:     foreach my $pref (keys(%prefs)) {
                   9567: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9568:     }
1.84      www      9569:     $cstring=~s/\&$//;
                   9570:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9571: }
                   9572: 
                   9573: # ---------------------------------------------------------- Make/modify course
                   9574: 
                   9575: sub createcourse {
1.741     raeburn  9576:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  9577:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      9578:     $url=&declutter($url);
                   9579:     my $cid='';
1.1028    raeburn  9580:     if ($context eq 'requestcourses') {
                   9581:         my $can_create = 0;
                   9582:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9583:         if ($udom eq $ownerdom) {
                   9584:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   9585:                                   $context)) {
                   9586:                 $can_create = 1;
                   9587:             }
                   9588:         } else {
                   9589:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9590:                                            $category);
                   9591:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   9592:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   9593:                 if (@curr > 0) {
                   9594:                     my @options = qw(approval validate autolimit);
                   9595:                     my $optregex = join('|',@options);
                   9596:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   9597:                         $can_create = 1;
                   9598:                     }
                   9599:                 }
                   9600:             }
                   9601:         }
                   9602:         if ($can_create) {
                   9603:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   9604:                 unless (&allowed('ccc',$udom)) {
                   9605:                     return 'refused'; 
                   9606:                 }
1.1017    raeburn  9607:             }
                   9608:         } else {
                   9609:             return 'refused';
                   9610:         }
1.1028    raeburn  9611:     } elsif (!&allowed('ccc',$udom)) {
                   9612:         return 'refused';
1.84      www      9613:     }
1.1011    raeburn  9614: # --------------------------------------------------------------- Get Unique ID
                   9615:     my $uname;
                   9616:     if ($cnum =~ /^$match_courseid$/) {
                   9617:         my $chome=&homeserver($cnum,$udom,'true');
                   9618:         if (($chome eq '') || ($chome eq 'no_host')) {
                   9619:             $uname = $cnum;
                   9620:         } else {
1.1038    raeburn  9621:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9622:         }
                   9623:     } else {
1.1038    raeburn  9624:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9625:     }
                   9626:     return $uname if ($uname =~ /^error/);
                   9627: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  9628:     if (!defined($course_server)) {
                   9629:         if (defined(&domain($udom,'primary'))) {
                   9630:             $course_server = &domain($udom,'primary');
                   9631:         } else {
                   9632:             $course_server = $env{'user.home'}; 
                   9633:         }
                   9634:     }
                   9635:     my %host_servers =
                   9636:         &Apache::lonnet::get_servers($udom,'library');
                   9637:     unless ($host_servers{$course_server}) {
                   9638:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  9639:     }
1.84      www      9640: # ------------------------------------------------------------- Make the course
                   9641:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  9642:                       $course_server);
1.84      www      9643:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  9644:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      9645:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9646: 	return 'error: no such course';
                   9647:     }
1.271     www      9648: # ----------------------------------------------------------------- Course made
1.516     raeburn  9649: # log existence
1.1029    raeburn  9650:     my $now = time;
1.918     raeburn  9651:     my $newcourse = {
                   9652:                     $udom.'_'.$uname => {
1.921     raeburn  9653:                                      description => $description,
                   9654:                                      inst_code   => $inst_code,
                   9655:                                      owner       => $course_owner,
                   9656:                                      type        => $crstype,
1.1029    raeburn  9657:                                      creator     => $env{'user.name'}.':'.
                   9658:                                                     $env{'user.domain'},
                   9659:                                      created     => $now,
                   9660:                                      context     => $context,
1.918     raeburn  9661:                                                 },
                   9662:                     };
1.921     raeburn  9663:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      9664: # set toplevel url
1.271     www      9665:     my $topurl=$url;
                   9666:     unless ($nonstandard) {
                   9667: # ------------------------------------------ For standard courses, make top url
                   9668:         my $mapurl=&clutter($url);
1.278     www      9669:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 9670:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      9671: <map>
                   9672: <resource id="1" type="start"></resource>
                   9673: <resource id="2" src="$mapurl"></resource>
                   9674: <resource id="3" type="finish"></resource>
                   9675: <link index="1" from="1" to="2"></link>
                   9676: <link index="2" from="2" to="3"></link>
                   9677: </map>
                   9678: ENDINITMAP
                   9679:         $topurl=&declutter(
1.638     albertel 9680:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      9681:                           );
                   9682:     }
                   9683: # ----------------------------------------------------------- Write preferences
1.84      www      9684:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  9685:                      ('description'              => $description,
                   9686:                       'url'                      => $topurl,
                   9687:                       'internal.creator'         => $env{'user.name'}.':'.
                   9688:                                                     $env{'user.domain'},
                   9689:                       'internal.created'         => $now,
                   9690:                       'internal.creationcontext' => $context)
                   9691:                     );
1.84      www      9692:     return '/'.$udom.'/'.$uname;
                   9693: }
                   9694: 
1.1011    raeburn  9695: # ------------------------------------------------------------------- Create ID
                   9696: sub generate_coursenum {
1.1038    raeburn  9697:     my ($udom,$crstype) = @_;
1.1011    raeburn  9698:     my $domdesc = &domain($udom);
                   9699:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  9700:     my $first;
                   9701:     if ($crstype eq 'Community') {
                   9702:         $first = '0';
                   9703:     } else {
                   9704:         $first = int(1+rand(9)); 
                   9705:     } 
                   9706:     my $uname=$first.
1.1011    raeburn  9707:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9708:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9709:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9710: # ----------------------------------------------- Make sure that does not exist
                   9711:     my $uhome=&homeserver($uname,$udom,'true');
                   9712:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  9713:         if ($crstype eq 'Community') {
                   9714:             $first = '0';
                   9715:         } else {
                   9716:             $first = int(1+rand(9));
                   9717:         }
                   9718:         $uname=$first.
1.1011    raeburn  9719:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9720:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9721:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9722:         $uhome=&homeserver($uname,$udom,'true');
                   9723:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   9724:             return 'error: unable to generate unique course-ID';
                   9725:         }
                   9726:     }
                   9727:     return $uname;
                   9728: }
                   9729: 
1.813     albertel 9730: sub is_course {
1.1167    droeschl 9731:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   9732:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   9733: 
                   9734:     return unless $cdom and $cnum;
                   9735: 
                   9736:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   9737:         '.');
                   9738: 
1.1172.2.23  raeburn  9739:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 9740:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 9741: }
                   9742: 
1.1015    raeburn  9743: sub store_userdata {
                   9744:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  9745:     my $result;
1.1016    raeburn  9746:     if ($datakey ne '') {
1.1013    raeburn  9747:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  9748:             if ($udom eq '' || $uname eq '') {
                   9749:                 $udom = $env{'user.domain'};
                   9750:                 $uname = $env{'user.name'};
                   9751:             }
                   9752:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  9753:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   9754:                 $result = 'error: no_host';
                   9755:             } else {
                   9756:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   9757:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   9758: 
                   9759:                 my $namevalue='';
                   9760:                 foreach my $key (keys(%{$storehash})) {
                   9761:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   9762:                 }
                   9763:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  9764:                 unless ($namespace eq 'courserequests') {
                   9765:                     $datakey = &escape($datakey);
                   9766:                 }
1.1105    raeburn  9767:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   9768:                                   $namevalue,$uhome);
1.1013    raeburn  9769:             }
                   9770:         } else {
                   9771:             $result = 'error: data to store was not a hash reference'; 
                   9772:         }
                   9773:     } else {
                   9774:         $result= 'error: invalid requestkey'; 
                   9775:     }
                   9776:     return $result;
                   9777: }
                   9778: 
1.21      www      9779: # ---------------------------------------------------------- Assign Custom Role
                   9780: 
                   9781: sub assigncustomrole {
1.957     raeburn  9782:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9783:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  9784:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      9785: }
                   9786: 
                   9787: # ----------------------------------------------------------------- Revoke Role
                   9788: 
                   9789: sub revokerole {
1.957     raeburn  9790:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9791:     my $now=time;
1.965     raeburn  9792:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      9793: }
                   9794: 
                   9795: # ---------------------------------------------------------- Revoke Custom Role
                   9796: 
                   9797: sub revokecustomrole {
1.957     raeburn  9798:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9799:     my $now=time;
1.357     www      9800:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  9801:            $deleteflag,$selfenroll,$context);
1.17      www      9802: }
                   9803: 
1.533     banghart 9804: # ------------------------------------------------------------ Disk usage
1.535     albertel 9805: sub diskusage {
1.955     raeburn  9806:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   9807:     $directorypath =~ s/\/$//;
                   9808:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   9809:                        .&escape($getpropath).':'.&escape($uname).':'
                   9810:                        .&escape($udom),homeserver($uname,$udom));
                   9811:     if ($listing eq 'unknown_cmd') {
                   9812:         if ($getpropath) {
                   9813:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   9814:         }
                   9815:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   9816:     }
1.514     albertel 9817:     return $listing;
1.512     banghart 9818: }
                   9819: 
1.566     banghart 9820: sub is_locked {
1.1096    raeburn  9821:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 9822:     my @check;
                   9823:     my $is_locked;
1.1093    raeburn  9824:     push (@check,$file_name);
1.613     albertel 9825:     my %locked = &get('file_permissions',\@check,
1.620     albertel 9826: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 9827:     my ($tmp)=keys(%locked);
                   9828:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  9829:     
1.566     banghart 9830:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  9831:         $is_locked = 'false';
                   9832:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  9833:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  9834:                $is_locked = 'true';
1.1096    raeburn  9835:                if (ref($which) eq 'ARRAY') {
                   9836:                    push(@{$which},$entry);
                   9837:                } else {
                   9838:                    last;
                   9839:                }
1.745     raeburn  9840:            }
                   9841:        }
1.566     banghart 9842:     } else {
                   9843:         $is_locked = 'false';
                   9844:     }
1.1093    raeburn  9845:     return $is_locked;
1.566     banghart 9846: }
                   9847: 
1.759     albertel 9848: sub declutter_portfile {
                   9849:     my ($file) = @_;
1.833     albertel 9850:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 9851:     return $file;
                   9852: }
                   9853: 
1.559     banghart 9854: # ------------------------------------------------------------- Mark as Read Only
                   9855: 
                   9856: sub mark_as_readonly {
                   9857:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 9858:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9859:     my ($tmp)=keys(%current_permissions);
                   9860:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 9861:     foreach my $file (@{$files}) {
1.759     albertel 9862: 	$file = &declutter_portfile($file);
1.561     banghart 9863:         push(@{$current_permissions{$file}},$what);
1.559     banghart 9864:     }
1.613     albertel 9865:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9866:     return;
                   9867: }
                   9868: 
1.572     banghart 9869: # ------------------------------------------------------------Save Selected Files
                   9870: 
                   9871: sub save_selected_files {
                   9872:     my ($user, $path, @files) = @_;
                   9873:     my $filename = $user."savedfiles";
1.573     banghart 9874:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.93.4  7(raebur 9875:7):     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 9876:     foreach my $file (@files) {
1.620     albertel 9877:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 9878:     }
                   9879:     foreach my $file (@other_files) {
1.574     banghart 9880:         print (OUT $file."\n");
1.572     banghart 9881:     }
1.574     banghart 9882:     close (OUT);
1.572     banghart 9883:     return 'ok';
                   9884: }
                   9885: 
1.574     banghart 9886: sub clear_selected_files {
                   9887:     my ($user) = @_;
                   9888:     my $filename = $user."savedfiles";
1.1172.2.93.4  7(raebur 9889:7):     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 9890:     print (OUT undef);
                   9891:     close (OUT);
                   9892:     return ("ok");    
                   9893: }
                   9894: 
1.572     banghart 9895: sub files_in_path {
                   9896:     my ($user, $path) = @_;
                   9897:     my $filename = $user."savedfiles";
                   9898:     my %return_files;
1.1172.2.93.4  7(raebur 9899:7):     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 9900:     while (my $line_in = <IN>) {
1.574     banghart 9901:         chomp ($line_in);
                   9902:         my @paths_and_file = split (m!/!, $line_in);
                   9903:         my $file_part = pop (@paths_and_file);
                   9904:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9905:         $path_part.='/';
                   9906:         my $path_and_file = $path_part.$file_part;
                   9907:         if ($path_part eq $path) {
                   9908:             $return_files{$file_part}= 'selected';
                   9909:         }
                   9910:     }
1.574     banghart 9911:     close (IN);
                   9912:     return (\%return_files);
1.572     banghart 9913: }
                   9914: 
                   9915: # called in portfolio select mode, to show files selected NOT in current directory
                   9916: sub files_not_in_path {
                   9917:     my ($user, $path) = @_;
                   9918:     my $filename = $user."savedfiles";
                   9919:     my @return_files;
                   9920:     my $path_part;
1.1172.2.93.4  7(raebur 9921:7):     open(IN,'<',LONCAPA::tempdir().$filename);
1.800     albertel 9922:     while (my $line = <IN>) {
1.572     banghart 9923:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9924:         my @paths_and_file = split(m|/|, $line);
                   9925:         my $file_part = pop(@paths_and_file);
                   9926:         chomp($file_part);
                   9927:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9928:         $path_part .= '/';
                   9929:         my $path_and_file = $path_part.$file_part;
                   9930:         if ($path_part ne $path) {
1.800     albertel 9931:             push(@return_files, ($path_and_file));
1.572     banghart 9932:         }
                   9933:     }
1.800     albertel 9934:     close(OUT);
1.574     banghart 9935:     return (@return_files);
1.572     banghart 9936: }
                   9937: 
1.745     raeburn  9938: #----------------------------------------------Get portfolio file permissions
1.629     banghart 9939: 
1.745     raeburn  9940: sub get_portfile_permissions {
                   9941:     my ($domain,$user) = @_;
1.613     albertel 9942:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9943:     my ($tmp)=keys(%current_permissions);
                   9944:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9945:     return \%current_permissions;
                   9946: }
                   9947: 
                   9948: #---------------------------------------------Get portfolio file access controls
                   9949: 
1.749     raeburn  9950: sub get_access_controls {
1.745     raeburn  9951:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 9952:     my %access;
                   9953:     my $real_file = $file;
                   9954:     $file =~ s/\.meta$//;
1.745     raeburn  9955:     if (defined($file)) {
1.749     raeburn  9956:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   9957:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 9958:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  9959:             }
                   9960:         }
1.745     raeburn  9961:     } else {
1.749     raeburn  9962:         foreach my $key (keys(%{$current_permissions})) {
                   9963:             if ($key =~ /\0accesscontrol$/) {
                   9964:                 if (defined($group)) {
                   9965:                     if ($key !~ m-^\Q$group\E/-) {
                   9966:                         next;
                   9967:                     }
                   9968:                 }
                   9969:                 my ($fullpath) = split(/\0/,$key);
                   9970:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   9971:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   9972:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   9973:                     }
                   9974:                 }
                   9975:             }
                   9976:         }
                   9977:     }
                   9978:     return %access;
                   9979: }
                   9980: 
                   9981: sub modify_access_controls {
                   9982:     my ($file_name,$changes,$domain,$user)=@_;
                   9983:     my ($outcome,$deloutcome);
                   9984:     my %store_permissions;
                   9985:     my %new_values;
                   9986:     my %new_control;
                   9987:     my %translation;
                   9988:     my @deletions = ();
                   9989:     my $now = time;
                   9990:     if (exists($$changes{'activate'})) {
                   9991:         if (ref($$changes{'activate'}) eq 'HASH') {
                   9992:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   9993:             my $numnew = scalar(@newitems);
                   9994:             for (my $i=0; $i<$numnew; $i++) {
                   9995:                 my $newkey = $newitems[$i];
                   9996:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  9997:                 if ($newkey =~ /^\d+:/) { 
                   9998:                     $newkey =~ s/^(\d+)/$newid/;
                   9999:                     $translation{$1} = $newid;
                   10000:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10001:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10002:                     $translation{$1} = $newid;
                   10003:                 }
1.749     raeburn  10004:                 $new_values{$file_name."\0".$newkey} = 
                   10005:                                           $$changes{'activate'}{$newitems[$i]};
                   10006:                 $new_control{$newkey} = $now;
                   10007:             }
                   10008:         }
                   10009:     }
                   10010:     my %todelete;
                   10011:     my %changed_items;
                   10012:     foreach my $action ('delete','update') {
                   10013:         if (exists($$changes{$action})) {
                   10014:             if (ref($$changes{$action}) eq 'HASH') {
                   10015:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10016:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10017:                     if ($action eq 'delete') { 
                   10018:                         $todelete{$itemnum} = 1;
                   10019:                     } else {
                   10020:                         $changed_items{$itemnum} = $key;
                   10021:                     }
                   10022:                 }
1.745     raeburn  10023:             }
                   10024:         }
1.749     raeburn  10025:     }
                   10026:     # get lock on access controls for file.
                   10027:     my $lockhash = {
                   10028:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10029:                                                        ':'.$env{'user.domain'},
                   10030:                    }; 
                   10031:     my $tries = 0;
                   10032:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10033:    
1.1172.2.79  raeburn  10034:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10035:         $tries ++;
1.1172.2.79  raeburn  10036:         sleep(0.1);
1.749     raeburn  10037:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10038:     }
                   10039:     if ($gotlock eq 'ok') {
                   10040:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10041:         my ($tmp)=keys(%curr_permissions);
                   10042:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10043:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10044:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10045:             if (ref($curr_controls) eq 'HASH') {
                   10046:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10047:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10048:                     if (defined($todelete{$itemnum})) {
                   10049:                         push(@deletions,$file_name."\0".$control_item);
                   10050:                     } else {
                   10051:                         if (defined($changed_items{$itemnum})) {
                   10052:                             $new_control{$changed_items{$itemnum}} = $now;
                   10053:                             push(@deletions,$file_name."\0".$control_item);
                   10054:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10055:                         } else {
                   10056:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10057:                         }
                   10058:                     }
1.745     raeburn  10059:                 }
                   10060:             }
                   10061:         }
1.970     raeburn  10062:         my ($group);
                   10063:         if (&is_course($domain,$user)) {
                   10064:             ($group,my $file) = split(/\//,$file_name,2);
                   10065:         }
1.749     raeburn  10066:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10067:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10068:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10069:         #  remove lock
                   10070:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10071:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10072:         my $sqlresult =
1.970     raeburn  10073:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10074:                                     $group);
1.749     raeburn  10075:     } else {
                   10076:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10077:     }
1.749     raeburn  10078:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10079: }
                   10080: 
1.827     raeburn  10081: sub make_public_indefinitely {
                   10082:     my ($requrl) = @_;
                   10083:     my $now = time;
                   10084:     my $action = 'activate';
                   10085:     my $aclnum = 0;
                   10086:     if (&is_portfolio_url($requrl)) {
                   10087:         my (undef,$udom,$unum,$file_name,$group) =
                   10088:             &parse_portfolio_url($requrl);
                   10089:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   10090:         my %access_controls = &get_access_controls($current_perms,
                   10091:                                                    $group,$file_name);
                   10092:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10093:             my ($num,$scope,$end,$start) = 
                   10094:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   10095:             if ($scope eq 'public') {
                   10096:                 if ($start <= $now && $end == 0) {
                   10097:                     $action = 'none';
                   10098:                 } else {
                   10099:                     $action = 'update';
                   10100:                     $aclnum = $num;
                   10101:                 }
                   10102:                 last;
                   10103:             }
                   10104:         }
                   10105:         if ($action eq 'none') {
                   10106:              return 'ok';
                   10107:         } else {
                   10108:             my %changes;
                   10109:             my $newend = 0;
                   10110:             my $newstart = $now;
                   10111:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   10112:             $changes{$action}{$newkey} = {
                   10113:                 type => 'public',
                   10114:                 time => {
                   10115:                     start => $newstart,
                   10116:                     end   => $newend,
                   10117:                 },
                   10118:             };
                   10119:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10120:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   10121:             return $outcome;
                   10122:         }
                   10123:     } else {
                   10124:         return 'invalid';
                   10125:     }
                   10126: }
                   10127: 
1.745     raeburn  10128: #------------------------------------------------------Get Marked as Read Only
                   10129: 
                   10130: sub get_marked_as_readonly {
                   10131:     my ($domain,$user,$what,$group) = @_;
                   10132:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10133:     my @readonly_files;
1.629     banghart 10134:     my $cmp1=$what;
                   10135:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10136:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10137:         if (defined($group)) {
                   10138:             if ($file_name !~ m-^\Q$group\E/-) {
                   10139:                 next;
                   10140:             }
                   10141:         }
1.561     banghart 10142:         if (ref($value) eq "ARRAY"){
                   10143:             foreach my $stored_what (@{$value}) {
1.629     banghart 10144:                 my $cmp2=$stored_what;
1.759     albertel 10145:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10146:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10147:                 }
1.629     banghart 10148:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10149:                     push(@readonly_files, $file_name);
1.745     raeburn  10150:                     last;
1.563     banghart 10151:                 } elsif (!defined($what)) {
                   10152:                     push(@readonly_files, $file_name);
1.745     raeburn  10153:                     last;
1.561     banghart 10154:                 }
                   10155:             }
1.745     raeburn  10156:         }
1.561     banghart 10157:     }
                   10158:     return @readonly_files;
                   10159: }
1.577     banghart 10160: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10161: 
1.577     banghart 10162: sub get_marked_as_readonly_hash {
1.745     raeburn  10163:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10164:     my %readonly_files;
1.745     raeburn  10165:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10166:         if (defined($group)) {
                   10167:             if ($file_name !~ m-^\Q$group\E/-) {
                   10168:                 next;
                   10169:             }
                   10170:         }
1.577     banghart 10171:         if (ref($value) eq "ARRAY"){
                   10172:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10173:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10174:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10175:                         if ($lock_descriptor eq 'graded') {
                   10176:                             $readonly_files{$file_name} = 'graded';
                   10177:                         } elsif ($lock_descriptor eq 'handback') {
                   10178:                             $readonly_files{$file_name} = 'handback';
                   10179:                         } else {
                   10180:                             if (!exists($readonly_files{$file_name})) {
                   10181:                                 $readonly_files{$file_name} = 'locked';
                   10182:                             }
                   10183:                         }
1.745     raeburn  10184:                     }
1.750     banghart 10185:                 } 
1.577     banghart 10186:             }
                   10187:         } 
                   10188:     }
                   10189:     return %readonly_files;
                   10190: }
1.559     banghart 10191: # ------------------------------------------------------------ Unmark as Read Only
                   10192: 
                   10193: sub unmark_as_readonly {
1.629     banghart 10194:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10195:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10196:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10197:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10198:     my $symb_crs = $what;
                   10199:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10200:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10201:     my ($tmp)=keys(%current_permissions);
                   10202:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10203:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10204:     foreach my $file (@readonly_files) {
1.759     albertel 10205: 	my $clean_file = &declutter_portfile($file);
                   10206: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10207: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10208:         my @new_locks;
                   10209:         my @del_keys;
                   10210:         if (ref($current_locks) eq "ARRAY"){
                   10211:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10212:                 my $compare=$locker;
1.749     raeburn  10213:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10214:                     $compare=join('',@{$locker});
1.746     raeburn  10215:                     if ($compare ne $symb_crs) {
                   10216:                         push(@new_locks, $locker);
                   10217:                     }
1.563     banghart 10218:                 }
                   10219:             }
1.650     albertel 10220:             if (scalar(@new_locks) > 0) {
1.563     banghart 10221:                 $current_permissions{$file} = \@new_locks;
                   10222:             } else {
                   10223:                 push(@del_keys, $file);
1.613     albertel 10224:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10225:                 delete($current_permissions{$file});
1.563     banghart 10226:             }
                   10227:         }
1.561     banghart 10228:     }
1.613     albertel 10229:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10230:     return;
                   10231: }
1.512     banghart 10232: 
1.17      www      10233: # ------------------------------------------------------------ Directory lister
                   10234: 
                   10235: sub dirlist {
1.955     raeburn  10236:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10237:     $uri=~s/^\///;
                   10238:     $uri=~s/\/$//;
1.253     stredwic 10239:     my ($udom, $uname);
1.955     raeburn  10240:     if ($getuserdir) {
1.253     stredwic 10241:         $udom = $userdomain;
                   10242:         $uname = $username;
1.955     raeburn  10243:     } else {
                   10244:         (undef,$udom,$uname)=split(/\//,$uri);
                   10245:         if(defined($userdomain)) {
                   10246:             $udom = $userdomain;
                   10247:         }
                   10248:         if(defined($username)) {
                   10249:             $uname = $username;
                   10250:         }
1.253     stredwic 10251:     }
1.955     raeburn  10252:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10253: 
1.955     raeburn  10254:     $dirRoot = $perlvar{'lonDocRoot'};
                   10255:     if (defined($getpropath)) {
                   10256:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10257:         $dirRoot =~ s/\/$//;
1.955     raeburn  10258:     } elsif (defined($getuserdir)) {
                   10259:         my $subdir=$uname.'__';
                   10260:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10261:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10262:                    ."/$udom/$subdir/$uname";
                   10263:     } elsif (defined($alternateRoot)) {
                   10264:         $dirRoot = $alternateRoot;
1.751     banghart 10265:     }
1.253     stredwic 10266: 
                   10267:     if($udom) {
                   10268:         if($uname) {
1.1135    raeburn  10269:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10270:             if ($uhome eq 'no_host') {
                   10271:                 return ([],'no_host');
                   10272:             }
1.955     raeburn  10273:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10274:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10275:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10276:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10277:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10278:             } else {
                   10279:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10280:             }
1.605     matthew  10281:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10282:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10283:                 @listing_results = split(/:/,$listing);
                   10284:             } else {
                   10285:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10286:             }
1.1135    raeburn  10287:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10288:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10289:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10290:                 return ([],$listing);
                   10291:             } else {
                   10292:                 return (\@listing_results);
1.1135    raeburn  10293:             }
1.955     raeburn  10294:         } elsif(!$alternateRoot) {
1.1136    raeburn  10295:             my (%allusers,%listerror);
1.841     albertel 10296: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10297:  	    foreach my $tryserver (keys(%servers)) {
                   10298:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10299:                                   &escape($udom),$tryserver);
                   10300:                 if ($listing eq 'unknown_cmd') {
                   10301: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10302: 				      $udom, $tryserver);
                   10303:                 } else {
                   10304:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10305:                 }
1.841     albertel 10306: 		if ($listing eq 'unknown_cmd') {
                   10307: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10308: 				      $udom, $tryserver);
                   10309: 		    @listing_results = split(/:/,$listing);
                   10310: 		} else {
                   10311: 		    @listing_results =
                   10312: 			map { &unescape($_); } split(/:/,$listing);
                   10313: 		}
1.1136    raeburn  10314:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10315:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10316:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10317:                     $listerror{$tryserver} = $listing;
                   10318:                 } else {
1.841     albertel 10319: 		    foreach my $line (@listing_results) {
                   10320: 			my ($entry) = split(/&/,$line,2);
                   10321: 			$allusers{$entry} = 1;
                   10322: 		    }
                   10323: 		}
1.253     stredwic 10324:             }
1.1136    raeburn  10325:             my @alluserslist=();
1.800     albertel 10326:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10327:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10328:             }
1.1172.2.80  raeburn  10329:             if (!%listerror) {
                   10330:                 # no errors
                   10331:                 return (\@alluserslist);
                   10332:             } elsif (scalar(keys(%servers)) == 1) {
                   10333:                 # one library server, one error
                   10334:                 my ($key) = keys(%listerror);
                   10335:                 return (\@alluserslist, $listerror{$key});
                   10336:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10337:                 # con_lost indicates that we might miss data from at least one
                   10338:                 # library server
                   10339:                 return (\@alluserslist, 'con_lost');
                   10340:             } else {
                   10341:                 # multiple library servers and no con_lost -> data should be
                   10342:                 # complete.
                   10343:                 return (\@alluserslist);
                   10344:             }
                   10345: 
1.253     stredwic 10346:         } else {
1.1136    raeburn  10347:             return ([],'missing username');
1.253     stredwic 10348:         }
1.955     raeburn  10349:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10350:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10351:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10352:         return (\@all_domains);
1.955     raeburn  10353:     } else {
1.1136    raeburn  10354:         return ([],'missing domain');
1.275     stredwic 10355:     }
                   10356: }
                   10357: 
                   10358: # --------------------------------------------- GetFileTimestamp
                   10359: # This function utilizes dirlist and returns the date stamp for
                   10360: # when it was last modified.  It will also return an error of -1
                   10361: # if an error occurs
                   10362: 
                   10363: sub GetFileTimestamp {
1.955     raeburn  10364:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10365:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10366:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10367:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10368:                                     undef,$getuserdir);
                   10369:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10370:         return -1;
                   10371:     }
                   10372:     if (ref($fileref) eq 'ARRAY') {
                   10373:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10374:         # @stats contains first the filename, then the stat output
                   10375:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10376:     } else {
                   10377:         return -1;
1.253     stredwic 10378:     }
1.26      www      10379: }
                   10380: 
1.712     albertel 10381: sub stat_file {
                   10382:     my ($uri) = @_;
1.787     albertel 10383:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10384: 
1.955     raeburn  10385:     my ($udom,$uname,$file);
1.712     albertel 10386:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10387: 	($udom,$uname,$file) =
1.811     albertel 10388: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10389: 	$file = 'userfiles/'.$file;
                   10390:     }
                   10391:     if ($uri =~ m-^/res/-) {
                   10392: 	($udom,$uname) = 
1.807     albertel 10393: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10394: 	$file = $uri;
                   10395:     }
                   10396: 
                   10397:     if (!$udom || !$uname || !$file) {
                   10398: 	# unable to handle the uri
                   10399: 	return ();
                   10400:     }
1.956     raeburn  10401:     my $getpropath;
                   10402:     if ($file =~ /^userfiles\//) {
                   10403:         $getpropath = 1;
                   10404:     }
1.1136    raeburn  10405:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10406:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10407:         return ();
                   10408:     } else {
                   10409:         if (ref($listref) eq 'ARRAY') {
                   10410:             my @stats = split('&',$listref->[0]);
                   10411: 	    shift(@stats); #filename is first
                   10412: 	    return @stats;
                   10413:         }
1.712     albertel 10414:     }
                   10415:     return ();
                   10416: }
                   10417: 
1.26      www      10418: # -------------------------------------------------------- Value of a Condition
                   10419: 
1.713     albertel 10420: # gets the value of a specific preevaluated condition
                   10421: #    stored in the string  $env{user.state.<cid>}
                   10422: # or looks up a condition reference in the bighash and if if hasn't
                   10423: # already been evaluated recurses into docondval to get the value of
                   10424: # the condition, then memoizing it to 
                   10425: #   $env{user.state.<cid>.<condition>}
1.40      www      10426: sub directcondval {
                   10427:     my $number=shift;
1.620     albertel 10428:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 10429: 	&Apache::lonuserstate::evalstate();
                   10430:     }
1.713     albertel 10431:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   10432: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   10433:     } elsif ($number =~ /^_/) {
                   10434: 	my $sub_condition;
                   10435: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10436: 		&GDBM_READER(),0640)) {
                   10437: 	    $sub_condition=$bighash{'conditions'.$number};
                   10438: 	    untie(%bighash);
                   10439: 	}
                   10440: 	my $value = &docondval($sub_condition);
1.949     raeburn  10441: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 10442: 	return $value;
                   10443:     }
1.620     albertel 10444:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   10445:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      10446:     } else {
                   10447:        return 2;
                   10448:     }
                   10449: }
                   10450: 
1.713     albertel 10451: # get the collection of conditions for this resource
1.26      www      10452: sub condval {
                   10453:     my $condidx=shift;
1.54      www      10454:     my $allpathcond='';
1.713     albertel 10455:     foreach my $cond (split(/\|/,$condidx)) {
                   10456: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   10457: 	    $allpathcond.=
                   10458: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   10459: 	}
1.191     harris41 10460:     }
1.54      www      10461:     $allpathcond=~s/\|$//;
1.713     albertel 10462:     return &docondval($allpathcond);
                   10463: }
                   10464: 
                   10465: #evaluates an expression of conditions
                   10466: sub docondval {
                   10467:     my ($allpathcond) = @_;
                   10468:     my $result=0;
                   10469:     if ($env{'request.course.id'}
                   10470: 	&& defined($allpathcond)) {
                   10471: 	my $operand='|';
                   10472: 	my @stack;
                   10473: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   10474: 	    if ($chunk eq '(') {
                   10475: 		push @stack,($operand,$result);
                   10476: 	    } elsif ($chunk eq ')') {
                   10477: 		my $before=pop @stack;
                   10478: 		if (pop @stack eq '&') {
                   10479: 		    $result=$result>$before?$before:$result;
                   10480: 		} else {
                   10481: 		    $result=$result>$before?$result:$before;
                   10482: 		}
                   10483: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   10484: 		$operand=$chunk;
                   10485: 	    } else {
                   10486: 		my $new=directcondval($chunk);
                   10487: 		if ($operand eq '&') {
                   10488: 		    $result=$result>$new?$new:$result;
                   10489: 		} else {
                   10490: 		    $result=$result>$new?$result:$new;
                   10491: 		}
                   10492: 	    }
                   10493: 	}
1.26      www      10494:     }
                   10495:     return $result;
1.421     albertel 10496: }
                   10497: 
                   10498: # ---------------------------------------------------- Devalidate courseresdata
                   10499: 
                   10500: sub devalidatecourseresdata {
                   10501:     my ($coursenum,$coursedomain)=@_;
                   10502:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10503:     &devalidate_cache_new('courseres',$hashid);
1.28      www      10504: }
                   10505: 
1.763     www      10506: 
1.200     www      10507: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     10508: #
                   10509: #  Parameters:
                   10510: #      $coursenum    - Number of the course.
                   10511: #      $coursedomain - Domain at which the course was created.
                   10512: #  Returns:
                   10513: #     A hash of the course parameters along (I think) with timestamps
                   10514: #     and version info.
1.877     foxr     10515: 
1.624     albertel 10516: sub get_courseresdata {
                   10517:     my ($coursenum,$coursedomain)=@_;
1.200     www      10518:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   10519:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10520:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 10521:     my %dumpreply;
1.417     albertel 10522:     unless (defined($cached)) {
1.624     albertel 10523: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 10524: 	$result=\%dumpreply;
1.251     albertel 10525: 	my ($tmp) = keys(%dumpreply);
                   10526: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 10527: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 10528: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   10529: 	    return $tmp;
1.416     albertel 10530: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 10531: 	    $result=undef;
1.599     albertel 10532: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 10533: 	}
                   10534:     }
1.624     albertel 10535:     return $result;
                   10536: }
                   10537: 
1.633     albertel 10538: sub devalidateuserresdata {
                   10539:     my ($uname,$udom)=@_;
                   10540:     my $hashid="$udom:$uname";
                   10541:     &devalidate_cache_new('userres',$hashid);
                   10542: }
                   10543: 
1.624     albertel 10544: sub get_userresdata {
                   10545:     my ($uname,$udom)=@_;
                   10546:     #most student don\'t have any data set, check if there is some data
                   10547:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   10548: 
                   10549:     my $hashid="$udom:$uname";
                   10550:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   10551:     if (!defined($cached)) {
                   10552: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   10553: 	$result=\%resourcedata;
                   10554: 	&do_cache_new('userres',$hashid,$result,600);
                   10555:     }
                   10556:     my ($tmp)=keys(%$result);
                   10557:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   10558: 	return $result;
                   10559:     }
                   10560:     #error 2 occurs when the .db doesn't exist
                   10561:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  10562:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   10563: 	    &logthis("<font color=\"blue\">WARNING:".
                   10564: 		     " Trying to get resource data for ".
                   10565: 		     $uname." at ".$udom.": ".
                   10566: 		     $tmp."</font>");
                   10567:         }
1.624     albertel 10568:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 10569: 	#&EXT_cache_set($udom,$uname);
                   10570: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 10571: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 10572:     }
                   10573:     return $tmp;
                   10574: }
1.879     foxr     10575: #----------------------------------------------- resdata - return resource data
                   10576: #  Purpose:
                   10577: #    Return resource data for either users or for a course.
                   10578: #  Parameters:
                   10579: #     $name      - Course/user name.
                   10580: #     $domain    - Name of the domain the user/course is registered on.
1.1172.2.93.4  1(raebur 10581:7): #     $type      - Type of thing $name is (must be 'course' or 'user')
1.879     foxr     10582: #     @which     - Array of names of resources desired.
                   10583: #  Returns:
                   10584: #     The value of the first reasource in @which that is found in the
                   10585: #     resource hash.
                   10586: #  Exceptional Conditions:
                   10587: #     If the $type passed in is not valid (not the string 'course' or 
                   10588: #     'user', an undefined  reference is returned.
                   10589: #     If none of the resources are found, an undef is returned
1.624     albertel 10590: sub resdata {
                   10591:     my ($name,$domain,$type,@which)=@_;
                   10592:     my $result;
                   10593:     if ($type eq 'course') {
                   10594: 	$result=&get_courseresdata($name,$domain);
                   10595:     } elsif ($type eq 'user') {
                   10596: 	$result=&get_userresdata($name,$domain);
                   10597:     }
                   10598:     if (!ref($result)) { return $result; }    
1.251     albertel 10599:     foreach my $item (@which) {
1.1172.2.93.4  1(raebur 10600:7):         if (ref($item) eq 'ARRAY') {
                   10601:7): 	    if (defined($result->{$item->[0]})) {
                   10602:7): 	        return [$result->{$item->[0]},$item->[1]];
                   10603:7): 	    }
                   10604:7):         }
1.250     albertel 10605:     }
1.291     albertel 10606:     return undef;
1.200     www      10607: }
                   10608: 
1.1172.2.93.4  2(raebur 10609:7): sub get_domain_ltitools {
                   10610:7):     my ($cdom) = @_;
                   10611:7):     my %ltitools;
                   10612:7):     my ($result,$cached)=&is_cached_new('ltitools',$cdom);
                   10613:7):     if (defined($cached)) {
                   10614:7):         if (ref($result) eq 'HASH') {
                   10615:7):             %ltitools = %{$result};
                   10616:7):         }
                   10617:7):     } else {
                   10618:7):         my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
                   10619:7):         if (ref($domconfig{'ltitools'}) eq 'HASH') {
                   10620:7):             %ltitools = %{$domconfig{'ltitools'}};
                   10621:7):             my %encdomconfig = &get_dom('encconfig',['ltitools'],$cdom);
                   10622:7):             if (ref($encdomconfig{'ltitools'}) eq 'HASH') {
                   10623:7):                 foreach my $id (keys(%ltitools)) {
                   10624:7):                     if (ref($encdomconfig{'ltitools'}{$id}) eq 'HASH') {
                   10625:7):                         foreach my $item ('key','secret') {
                   10626:7):                             $ltitools{$id}{$item} = $encdomconfig{'ltitools'}{$id}{$item};
                   10627:7):                         }
                   10628:7):                     }
                   10629:7):                 }
                   10630:7):             }
                   10631:7):         }
                   10632:7):         my $cachetime = 24*60*60;
                   10633:7):         &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
                   10634:7):     }
                   10635:7):     return %ltitools;
                   10636:7): }
                   10637:7): 
1.1172.2.31  raeburn  10638: sub get_numsuppfiles {
                   10639:     my ($cnum,$cdom,$ignorecache)=@_;
                   10640:     my $hashid=$cnum.':'.$cdom;
                   10641:     my ($suppcount,$cached);
                   10642:     unless ($ignorecache) {
                   10643:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   10644:     }
                   10645:     unless (defined($cached)) {
                   10646:         my $chome=&homeserver($cnum,$cdom);
                   10647:         unless ($chome eq 'no_host') {
                   10648:             ($suppcount,my $errors) = (0,0);
                   10649:             my $suppmap = 'supplemental.sequence';
                   10650:             ($suppcount,$errors) =
                   10651:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   10652:         }
                   10653:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   10654:     }
                   10655:     return $suppcount;
                   10656: }
                   10657: 
1.379     matthew  10658: #
                   10659: # EXT resource caching routines
                   10660: #
                   10661: 
                   10662: sub clear_EXT_cache_status {
1.383     albertel 10663:     &delenv('cache.EXT.');
1.379     matthew  10664: }
                   10665: 
                   10666: sub EXT_cache_status {
                   10667:     my ($target_domain,$target_user) = @_;
1.383     albertel 10668:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 10669:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  10670:         # We know already the user has no data
                   10671:         return 1;
                   10672:     } else {
                   10673:         return 0;
                   10674:     }
                   10675: }
                   10676: 
                   10677: sub EXT_cache_set {
                   10678:     my ($target_domain,$target_user) = @_;
1.383     albertel 10679:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  10680:     #&appenv({$cachename => time});
1.379     matthew  10681: }
                   10682: 
1.28      www      10683: # --------------------------------------------------------- Value of a Variable
1.58      www      10684: sub EXT {
1.715     albertel 10685: 
1.1172.2.28  raeburn  10686:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      10687:     unless ($varname) { return ''; }
1.218     albertel 10688:     #get real user name/domain, courseid and symb
                   10689:     my $courseid;
1.359     albertel 10690:     my $publicuser;
1.427     www      10691:     if ($symbparm) {
                   10692: 	$symbparm=&get_symb_from_alias($symbparm);
                   10693:     }
1.218     albertel 10694:     if (!($uname && $udom)) {
1.790     albertel 10695:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 10696:       if (!$symbparm) {	$symbparm=$cursymb; }
                   10697:     } else {
1.620     albertel 10698: 	$courseid=$env{'request.course.id'};
1.218     albertel 10699:     }
1.48      www      10700:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   10701:     my $rest;
1.320     albertel 10702:     if (defined($therest[0])) {
1.48      www      10703:        $rest=join('.',@therest);
                   10704:     } else {
                   10705:        $rest='';
                   10706:     }
1.320     albertel 10707: 
1.57      www      10708:     my $qualifierrest=$qualifier;
                   10709:     if ($rest) { $qualifierrest.='.'.$rest; }
                   10710:     my $spacequalifierrest=$space;
                   10711:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      10712:     if ($realm eq 'user') {
1.48      www      10713: # --------------------------------------------------------------- user.resource
                   10714: 	if ($space eq 'resource') {
1.651     albertel 10715: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   10716: 		  || defined($Apache::lonhomework::parsing_a_task))
                   10717: 		 &&
1.744     albertel 10718: 		 ($symbparm eq &symbread()) ) {	
                   10719: 		# if we are in the middle of processing the resource the
                   10720: 		# get the value we are planning on committing
                   10721:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   10722:                     return $Apache::lonhomework::results{$qualifierrest};
                   10723:                 } else {
                   10724:                     return $Apache::lonhomework::history{$qualifierrest};
                   10725:                 }
1.335     albertel 10726: 	    } else {
1.359     albertel 10727: 		my %restored;
1.620     albertel 10728: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 10729: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   10730: 		} else {
                   10731: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   10732: 		}
1.335     albertel 10733: 		return $restored{$qualifierrest};
                   10734: 	    }
1.48      www      10735: # ----------------------------------------------------------------- user.access
                   10736:         } elsif ($space eq 'access') {
1.218     albertel 10737: 	    # FIXME - not supporting calls for a specific user
1.48      www      10738:             return &allowed($qualifier,$rest);
                   10739: # ------------------------------------------ user.preferences, user.environment
                   10740:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 10741: 	    if (($uname eq $env{'user.name'}) &&
                   10742: 		($udom eq $env{'user.domain'})) {
                   10743: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 10744: 	    } else {
1.359     albertel 10745: 		my %returnhash;
                   10746: 		if (!$publicuser) {
                   10747: 		    %returnhash=&userenvironment($udom,$uname,
                   10748: 						 $qualifierrest);
                   10749: 		}
1.218     albertel 10750: 		return $returnhash{$qualifierrest};
                   10751: 	    }
1.48      www      10752: # ----------------------------------------------------------------- user.course
                   10753:         } elsif ($space eq 'course') {
1.218     albertel 10754: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10755:             return $env{join('.',('request.course',$qualifier))};
1.48      www      10756: # ------------------------------------------------------------------- user.role
                   10757:         } elsif ($space eq 'role') {
1.218     albertel 10758: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10759:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      10760:             if ($qualifier eq 'value') {
                   10761: 		return $role;
                   10762:             } elsif ($qualifier eq 'extent') {
                   10763:                 return $where;
                   10764:             }
                   10765: # ----------------------------------------------------------------- user.domain
                   10766:         } elsif ($space eq 'domain') {
1.218     albertel 10767:             return $udom;
1.48      www      10768: # ------------------------------------------------------------------- user.name
                   10769:         } elsif ($space eq 'name') {
1.218     albertel 10770:             return $uname;
1.48      www      10771: # ---------------------------------------------------- Any other user namespace
1.29      www      10772:         } else {
1.359     albertel 10773: 	    my %reply;
                   10774: 	    if (!$publicuser) {
                   10775: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   10776: 	    }
                   10777: 	    return $reply{$qualifierrest};
1.48      www      10778:         }
1.236     www      10779:     } elsif ($realm eq 'query') {
                   10780: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 10781:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   10782: 						[$spacequalifierrest]);
1.620     albertel 10783: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      10784:    } elsif ($realm eq 'request') {
1.48      www      10785: # ------------------------------------------------------------- request.browser
                   10786:         if ($space eq 'browser') {
1.1145    bisitz   10787:             return $env{'browser.'.$qualifier};
1.57      www      10788: # ------------------------------------------------------------ request.filename
                   10789:         } else {
1.620     albertel 10790:             return $env{'request.'.$spacequalifierrest};
1.29      www      10791:         }
1.28      www      10792:     } elsif ($realm eq 'course') {
1.48      www      10793: # ---------------------------------------------------------- course.description
1.620     albertel 10794:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      10795:     } elsif ($realm eq 'resource') {
1.165     www      10796: 
1.620     albertel 10797: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 10798: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   10799: 	}
1.693     albertel 10800: 
1.1172.2.30  raeburn  10801:         if ($qualifier eq '') {
                   10802: 	    if ($space eq 'title') {
                   10803: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   10804: 	        return &gettitle($symbparm);
                   10805: 	    }
1.693     albertel 10806: 	
1.1172.2.30  raeburn  10807: 	    if ($space eq 'map') {
                   10808: 	        my ($map) = &decode_symb($symbparm);
                   10809: 	        return &symbread($map);
                   10810: 	    }
                   10811:             if ($space eq 'maptitle') {
                   10812:                 my ($map) = &decode_symb($symbparm);
                   10813:                 return &gettitle($map);
                   10814:             }
                   10815: 	    if ($space eq 'filename') {
                   10816: 	        if ($symbparm) {
                   10817: 		    return &clutter((&decode_symb($symbparm))[2]);
                   10818: 	        }
                   10819: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 10820: 	    }
1.1172.2.30  raeburn  10821: 
                   10822:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   10823:                 if ($space eq 'visibleparts') {
                   10824:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10825:                     my $item;
                   10826:                     if (ref($navmap)) {
                   10827:                         my $res = $navmap->getBySymb($symbparm);
                   10828:                         my $parts = $res->parts();
                   10829:                         if (ref($parts) eq 'ARRAY') {
                   10830:                             $item = join(',',@{$parts});
                   10831:                         }
                   10832:                         undef($navmap);
                   10833:                     }
                   10834:                     return $item;
                   10835:                 }
                   10836:             }
                   10837:         }
1.693     albertel 10838: 
                   10839: 	my ($section, $group, @groups);
1.593     albertel 10840: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  10841:         if (($courseid eq '') && ($cid)) {
                   10842:             $courseid = $cid;
                   10843:         }
                   10844: 	if (($symbparm && $courseid) && 
                   10845: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      10846: 
1.218     albertel 10847: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      10848: 
1.60      www      10849: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 10850: 	    my $symbp=$symbparm;
1.735     albertel 10851: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 10852: 
                   10853: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   10854: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   10855: 
1.620     albertel 10856: 	    if (($env{'user.name'} eq $uname) &&
                   10857: 		($env{'user.domain'} eq $udom)) {
                   10858: 		$section=$env{'request.course.sec'};
1.733     raeburn  10859:                 @groups = split(/:/,$env{'request.course.groups'});  
                   10860:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 10861: 	    } else {
1.539     albertel 10862: 		if (! defined($usection)) {
1.551     albertel 10863: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 10864: 		} else {
                   10865: 		    $section = $usection;
                   10866: 		}
1.733     raeburn  10867:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 10868: 	    }
                   10869: 
                   10870: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   10871: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   10872: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   10873: 
1.593     albertel 10874: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 10875: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 10876: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      10877: 
1.60      www      10878: # ----------------------------------------------------------- first, check user
1.624     albertel 10879: 
                   10880: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 10881: 				       ([$courselevelr,'resource'],
                   10882: 					[$courselevelm,'map'     ],
                   10883: 					[$courselevel, 'course'  ]));
1.931     albertel 10884: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      10885: 
1.594     albertel 10886: # ------------------------------------------------ second, check some of course
1.684     raeburn  10887:             my $coursereply;
1.691     raeburn  10888:             if (@groups > 0) {
                   10889:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   10890:                                        $mapparm,$spacequalifierrest);
1.927     albertel 10891:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  10892:             }
1.96      www      10893: 
1.684     raeburn  10894: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 10895: 				  $env{'course.'.$courseid.'.domain'},
                   10896: 				  'course',
                   10897: 				  ([$seclevelr,   'resource'],
                   10898: 				   [$seclevelm,   'map'     ],
                   10899: 				   [$seclevel,    'course'  ],
                   10900: 				   [$courselevelr,'resource']));
                   10901: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      10902: 
1.60      www      10903: # ------------------------------------------------------ third, check map parms
1.218     albertel 10904: 	    my %parmhash=();
                   10905: 	    my $thisparm='';
                   10906: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 10907: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 10908: 		    &GDBM_READER(),0640)) {
1.218     albertel 10909: 		$thisparm=$parmhash{$symbparm};
                   10910: 		untie(%parmhash);
                   10911: 	    }
1.927     albertel 10912: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 10913: 	}
1.594     albertel 10914: # ------------------------------------------ fourth, look in resource metadata
1.71      www      10915: 
1.218     albertel 10916: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 10917: 	my $filename;
                   10918: 	if (!$symbparm) { $symbparm=&symbread(); }
                   10919: 	if ($symbparm) {
1.409     www      10920: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 10921: 	} else {
1.620     albertel 10922: 	    $filename=$env{'request.filename'};
1.282     albertel 10923: 	}
                   10924: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 10925: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 10926: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 10927: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      10928: 
1.927     albertel 10929: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 10930: 	if ($symbparm && defined($courseid) && 
1.620     albertel 10931: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 10932: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   10933: 				     $env{'course.'.$courseid.'.domain'},
                   10934: 				     'course',
1.927     albertel 10935: 				     ([$courselevelm,'map'   ],
                   10936: 				      [$courselevel, 'course']));
                   10937: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 10938: 	}
1.145     www      10939: # ------------------------------------------------------------------ Cascade up
1.218     albertel 10940: 	unless ($space eq '0') {
1.336     albertel 10941: 	    my @parts=split(/_/,$space);
                   10942: 	    my $id=pop(@parts);
                   10943: 	    my $part=join('_',@parts);
                   10944: 	    if ($part eq '') { $part='0'; }
1.927     albertel 10945: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 10946: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  10947: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 10948: 	}
1.395     albertel 10949: 	if ($recurse) { return undef; }
                   10950: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 10951: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      10952: # ---------------------------------------------------- Any other user namespace
                   10953:     } elsif ($realm eq 'environment') {
                   10954: # ----------------------------------------------------------------- environment
1.620     albertel 10955: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   10956: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 10957: 	} else {
1.770     albertel 10958: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   10959: 		return '';
                   10960: 	    }
1.219     albertel 10961: 	    my %returnhash=&userenvironment($udom,$uname,
                   10962: 					    $spacequalifierrest);
                   10963: 	    return $returnhash{$spacequalifierrest};
                   10964: 	}
1.28      www      10965:     } elsif ($realm eq 'system') {
1.48      www      10966: # ----------------------------------------------------------------- system.time
                   10967: 	if ($space eq 'time') {
                   10968: 	    return time;
                   10969:         }
1.696     albertel 10970:     } elsif ($realm eq 'server') {
                   10971: # ----------------------------------------------------------------- system.time
                   10972: 	if ($space eq 'name') {
                   10973: 	    return $ENV{'SERVER_NAME'};
                   10974:         }
1.28      www      10975:     }
1.48      www      10976:     return '';
1.61      www      10977: }
                   10978: 
1.927     albertel 10979: sub get_reply {
                   10980:     my ($reply_value) = @_;
1.940     raeburn  10981:     if (ref($reply_value) eq 'ARRAY') {
                   10982:         if (wantarray) {
                   10983: 	    return @$reply_value;
                   10984:         }
                   10985:         return $reply_value->[0];
                   10986:     } else {
                   10987:         return $reply_value;
1.927     albertel 10988:     }
                   10989: }
                   10990: 
1.691     raeburn  10991: sub check_group_parms {
                   10992:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   10993:     my @groupitems = ();
                   10994:     my $resultitem;
1.927     albertel 10995:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  10996:     foreach my $group (@{$groups}) {
                   10997:         foreach my $level (@levels) {
1.927     albertel 10998:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   10999:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11000:         }
                   11001:     }
                   11002:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11003:                             $env{'course.'.$courseid.'.domain'},
                   11004:                                      'course',@groupitems);
                   11005:     return $coursereply;
                   11006: }
                   11007: 
                   11008: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11009:     my ($courseid,@groups) = @_;
                   11010:     @groups = sort(@groups);
1.691     raeburn  11011:     return @groups;
                   11012: }
                   11013: 
1.395     albertel 11014: sub packages_tab_default {
                   11015:     my ($uri,$varname)=@_;
                   11016:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11017: 
                   11018:     my (@extension,@specifics,$do_default);
                   11019:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11020: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11021: 	if ($pack_type eq 'default') {
                   11022: 	    $do_default=1;
                   11023: 	} elsif ($pack_type eq 'extension') {
                   11024: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11025: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11026: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11027: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11028: 	}
                   11029:     }
                   11030:     # first look for a package that matches the requested part id
                   11031:     foreach my $package (@specifics) {
                   11032: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11033: 	next if ($pack_part ne $part);
                   11034: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11035: 	    return $packagetab{"$pack_type&$name&default"};
                   11036: 	}
                   11037:     }
                   11038:     # look for any possible matching non extension_ package
                   11039:     foreach my $package (@specifics) {
                   11040: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11041: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11042: 	    return $packagetab{"$pack_type&$name&default"};
                   11043: 	}
1.585     albertel 11044: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11045: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11046: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11047: 	}
                   11048:     }
1.738     albertel 11049:     # look for any posible extension_ match
                   11050:     foreach my $package (@extension) {
                   11051: 	my ($package,$pack_type)=@{$package};
                   11052: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11053: 	    return $packagetab{"$pack_type&$name&default"};
                   11054: 	}
                   11055: 	if (defined($packagetab{$package."&$name&default"})) {
                   11056: 	    return $packagetab{$package."&$name&default"};
                   11057: 	}
                   11058:     }
                   11059:     # look for a global default setting
                   11060:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11061: 	return $packagetab{"default&$name&default"};
                   11062:     }
1.395     albertel 11063:     return undef;
                   11064: }
                   11065: 
1.334     albertel 11066: sub add_prefix_and_part {
                   11067:     my ($prefix,$part)=@_;
                   11068:     my $keyroot;
                   11069:     if (defined($prefix) && $prefix !~ /^__/) {
                   11070: 	# prefix that has a part already
                   11071: 	$keyroot=$prefix;
                   11072:     } elsif (defined($prefix)) {
                   11073: 	# prefix that is missing a part
                   11074: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11075:     } else {
                   11076: 	# no prefix at all
                   11077: 	if (defined($part)) { $keyroot='_'.$part; }
                   11078:     }
                   11079:     return $keyroot;
                   11080: }
                   11081: 
1.71      www      11082: # ---------------------------------------------------------------- Get metadata
                   11083: 
1.599     albertel 11084: my %metaentry;
1.1070    www      11085: my %importedpartids;
1.1172.2.93.4  8(raebur 11086:8): my %importedrespids;
1.71      www      11087: sub metadata {
1.176     www      11088:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11089:     $uri=&declutter($uri);
1.288     albertel 11090:     # if it is a non metadata possible uri return quickly
1.529     albertel 11091:     if (($uri eq '') || 
                   11092: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.93.4  2(raebur 11093:7): 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  11094:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11095: 	return undef;
                   11096:     }
1.1172.2.49  raeburn  11097:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11098: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11099: 	return undef;
1.288     albertel 11100:     }
1.73      www      11101:     my $filename=$uri;
                   11102:     $uri=~s/\.meta$//;
1.172     www      11103: #
                   11104: # Is the metadata already cached?
1.177     www      11105: # Look at timestamp of caching
1.172     www      11106: # Everything is cached by the main uri, libraries are never directly cached
                   11107: #
1.428     albertel 11108:     if (!defined($liburi)) {
1.599     albertel 11109: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11110: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11111:     }
                   11112:     {
1.1069    www      11113: # Imported parts would go here
1.1172.2.93.4  8(raebur 11114:8):         my @origfiletagids=();
1.1069    www      11115:         my $importedparts=0;
1.1172.2.93.4  8(raebur 11116:8): 
                   11117:8): # Imported responseids would go here
                   11118:8):         my $importedresponses=0;
1.172     www      11119: #
                   11120: # Is this a recursive call for a library?
                   11121: #
1.599     albertel 11122: #	if (! exists($metacache{$uri})) {
                   11123: #	    $metacache{$uri}={};
                   11124: #	}
1.924     albertel 11125: 	my $cachetime = 60*60;
1.171     www      11126:         if ($liburi) {
                   11127: 	    $liburi=&declutter($liburi);
                   11128:             $filename=$liburi;
1.401     bowersj2 11129:         } else {
1.599     albertel 11130: 	    &devalidate_cache_new('meta',$uri);
                   11131: 	    undef(%metaentry);
1.401     bowersj2 11132: 	}
1.140     www      11133:         my %metathesekeys=();
1.73      www      11134:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11135: 	my $metastring;
1.1140    www      11136: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11137: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11138: 	    $metastring = 
1.929     albertel 11139: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11140: 					  ('grade_target' => 'meta'));
                   11141: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11142: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11143:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11144: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11145: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11146: 	    $metastring=&getfile($file);
1.489     albertel 11147: 	}
1.208     albertel 11148:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11149:         my $token;
1.140     www      11150:         undef %metathesekeys;
1.71      www      11151:         while ($token=$parser->get_token) {
1.339     albertel 11152: 	    if ($token->[0] eq 'S') {
                   11153: 		if (defined($token->[2]->{'package'})) {
1.172     www      11154: #
                   11155: # This is a package - get package info
                   11156: #
1.339     albertel 11157: 		    my $package=$token->[2]->{'package'};
                   11158: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11159: 		    if (defined($token->[2]->{'id'})) { 
                   11160: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11161: 		    }
1.599     albertel 11162: 		    if ($metaentry{':packages'}) {
                   11163: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11164: 		    } else {
1.599     albertel 11165: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11166: 		    }
1.736     albertel 11167: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11168: 			my $part=$keyroot;
                   11169: 			$part=~s/^\_//;
1.736     albertel 11170: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11171: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11172: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11173: 			    # ignore package.tab specified default values
                   11174:                             # here &package_tab_default() will fetch those
                   11175: 			    if ($subp eq 'default') { next; }
1.736     albertel 11176: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11177: 			    my $unikey;
                   11178: 			    if ($pack =~ /_0$/) {
                   11179: 				$unikey='parameter_0_'.$name;
                   11180: 				$part=0;
                   11181: 			    } else {
                   11182: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11183: 			    }
1.339     albertel 11184: 			    if ($subp eq 'display') {
                   11185: 				$value.=' [Part: '.$part.']';
                   11186: 			    }
1.599     albertel 11187: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11188: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11189: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11190: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11191: 			    }
1.599     albertel 11192: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11193: 				$metaentry{':'.$unikey}=
                   11194: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11195: 			    }
1.339     albertel 11196: 			}
                   11197: 		    }
                   11198: 		} else {
1.172     www      11199: #
                   11200: # This is not a package - some other kind of start tag
1.339     albertel 11201: #
                   11202: 		    my $entry=$token->[1];
1.1068    www      11203: 		    my $unikey='';
1.175     www      11204: 
1.339     albertel 11205: 		    if ($entry eq 'import') {
1.175     www      11206: #
                   11207: # Importing a library here
1.339     albertel 11208: #
1.1067    www      11209:                         my $location=$parser->get_text('/import');
                   11210:                         my $dir=$filename;
                   11211:                         $dir=~s|[^/]*$||;
                   11212:                         $location=&filelocation($dir,$location);
1.1172.2.93.4  8(raebur 11213:8): 
                   11214:8):                         my $importid=$token->[2]->{'id'};
1.1068    www      11215:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.93.4  8(raebur 11216:8): #
                   11217:8): # Check metadata for imported file to
                   11218:8): # see if it contained response items
                   11219:8): #
          9(raebur 11220:8):                         my %currmetaentry = %metaentry;
          8(raebur 11221:8):                         my $libresponseorder = &metadata($location,'responseorder');
                   11222:8):                         my $origfile;
                   11223:8):                         if ($libresponseorder ne '') {
                   11224:8):                             if ($#origfiletagids<0) {
                   11225:8):                                 undef(%importedrespids);
                   11226:8):                                 undef(%importedpartids);
                   11227:8):                             }
                   11228:8):                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   11229:8):                             if (@{$importedrespids{$importid}} > 0) {
                   11230:8):                                 $importedresponses = 1;
                   11231:8): # We need to get the original file and the imported file to get the response order correct
                   11232:8): # Load and inspect original file
                   11233:8):                                 if ($#origfiletagids<0) {
                   11234:8):                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11235:8):                                     $origfile=&getfile($origfilelocation);
                   11236:8):                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11237:8):                                 }
                   11238:8):                             }
                   11239:8):                         }
          9(raebur 11240:8): # Do not overwrite contents of %metaentry hash for resource itself with 
                   11241:8): # hash populated for imported library file
                   11242:8):                         %metaentry = %currmetaentry;
                   11243:8):                         undef(%currmetaentry);
1.1068    www      11244:                         if ($importmode eq 'problem') {
1.1069    www      11245: # Import as problem/response
1.1068    www      11246:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11247:                         } elsif ($importmode eq 'part') {
                   11248: # Import as part(s)
1.1069    www      11249:                            $importedparts=1;
                   11250: # We need to get the original file and the imported file to get the part order correct
                   11251: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.93.4  8(raebur 11252:8): # Load and inspect original file if we didn't do that already
          9(raebur 11253:8):                            if ($#origfiletagids<0) {
          8(raebur 11254:8):                                undef(%importedrespids);
                   11255:8):                                undef(%importedpartids);
                   11256:8):                                if ($origfile eq '') {
                   11257:8):                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11258:8):                                    $origfile=&getfile($origfilelocation);
                   11259:8):                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11260:8):                                }
1.1070    www      11261:                            }
                   11262: 
1.1069    www      11263: # Load and inspect imported file
                   11264:                            my $impfile=&getfile($location);
                   11265:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11266:                            if ($#impfilepartids>=0) {
                   11267: # This problem had parts
1.1070    www      11268:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11269:                            } else {
                   11270: # Importing by turning a single problem into a problem part
                   11271: # It gets the import-tags ID as part-ID
                   11272:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11273:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11274:                            }
1.1068    www      11275:                         } else {
                   11276: # Normal import
                   11277:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11278:                            if (defined($token->[2]->{'id'})) {
                   11279:                               $unikey.='_'.$token->[2]->{'id'};
                   11280:                            }
1.1067    www      11281:                         }
                   11282: 
1.339     albertel 11283: 			if ($depthcount<20) {
1.736     albertel 11284: 			    my $metadata = 
                   11285: 				&metadata($uri,'keys', $location,$unikey,
                   11286: 					  $depthcount+1);
                   11287: 			    foreach my $meta (split(',',$metadata)) {
                   11288: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   11289: 				$metathesekeys{$meta}=1;
1.339     albertel 11290: 			    }
1.1068    www      11291: 			
                   11292:                         }
1.1067    www      11293: 		    } else {
                   11294: #
                   11295: # Not importing, some other kind of non-package, non-library start tag
                   11296: # 
                   11297:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11298:                         if (defined($token->[2]->{'id'})) {
                   11299:                             $unikey.='_'.$token->[2]->{'id'};
                   11300:                         }
1.339     albertel 11301: 			if (defined($token->[2]->{'name'})) { 
                   11302: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   11303: 			}
                   11304: 			$metathesekeys{$unikey}=1;
1.736     albertel 11305: 			foreach my $param (@{$token->[3]}) {
                   11306: 			    $metaentry{':'.$unikey.'.'.$param} =
                   11307: 				$token->[2]->{$param};
1.339     albertel 11308: 			}
                   11309: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 11310: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 11311: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   11312: 		 # only ws inside the tag, and not in default, so use default
                   11313: 		 # as value
1.599     albertel 11314: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 11315: 			} elsif ( $internaltext =~ /\S/ ) {
                   11316: 		  # something interesting inside the tag
                   11317: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 11318: 			} else {
1.908     albertel 11319: 		  # no interesting values, don't set a default
1.339     albertel 11320: 			}
1.172     www      11321: # end of not-a-package not-a-library import
1.339     albertel 11322: 		    }
1.172     www      11323: # end of not-a-package start tag
1.339     albertel 11324: 		}
1.172     www      11325: # the next is the end of "start tag"
1.339     albertel 11326: 	    }
                   11327: 	}
1.483     albertel 11328: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 11329: 	$extension = lc($extension);
                   11330: 	if ($extension eq 'htm') { $extension='html'; }
                   11331: 
1.737     albertel 11332: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 11333: 	    #no specific packages #how's our extension
                   11334: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 11335: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 11336: 					 \%metathesekeys);
                   11337: 	}
1.883     albertel 11338: 
                   11339: 	if (!exists($metaentry{':packages'})
                   11340: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 11341: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 11342: 		#no specific packages well let's get default then
                   11343: 		if ($key!~/^default&/) { next; }
1.488     albertel 11344: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 11345: 					     \%metathesekeys);
                   11346: 	    }
                   11347: 	}
1.338     www      11348: # are there custom rights to evaluate
1.599     albertel 11349: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 11350: 
1.338     www      11351:     #
                   11352:     # Importing a rights file here
1.339     albertel 11353:     #
                   11354: 	    unless ($depthcount) {
1.599     albertel 11355: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 11356: 		my $dir=$filename;
                   11357: 		$dir=~s|[^/]*$||;
                   11358: 		$location=&filelocation($dir,$location);
1.736     albertel 11359: 		my $rights_metadata =
                   11360: 		    &metadata($uri,'keys',$location,'_rights',
                   11361: 			      $depthcount+1);
                   11362: 		foreach my $rights (split(',',$rights_metadata)) {
                   11363: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   11364: 		    $metathesekeys{$rights}=1;
1.339     albertel 11365: 		}
                   11366: 	    }
                   11367: 	}
1.737     albertel 11368: 	# uniqifiy package listing
                   11369: 	my %seen;
                   11370: 	my @uniq_packages =
                   11371: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   11372: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   11373: 
1.1172.2.93.4  8(raebur 11374:8):         if (($importedresponses) || ($importedparts)) {
                   11375:8):             if ($importedparts) {
1.1070    www      11376: # We had imported parts and need to rebuild partorder
1.1172.2.93.4  8(raebur 11377:8):                 $metaentry{':partorder'}='';
                   11378:8):                 $metathesekeys{'partorder'}=1;
                   11379:8):             }
                   11380:8):             if ($importedresponses) {
                   11381:8): # We had imported responses and need to rebuild responseorder
                   11382:8):                 $metaentry{':responseorder'}='';
                   11383:8):                 $metathesekeys{'responseorder'}=1;
                   11384:8):             }
                   11385:8):             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   11386:8):                 my $origid = $origfiletagids[$index+1];
                   11387:8):                 if ($origfiletagids[$index] eq 'part') {
                   11388:8): # Original part, part of the problem
                   11389:8):                     if ($importedparts) {
                   11390:8):                         $metaentry{':partorder'}.=','.$origid;
                   11391:8):                     }
                   11392:8):                 } elsif ($origfiletagids[$index] eq 'import') {
                   11393:8):                     if ($importedparts) {
                   11394:8): # We have imported parts at this position
                   11395:8):                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   11396:8):                     }
                   11397:8):                     if ($importedresponses) {
                   11398:8): # We have imported responses at this position
                   11399:8):                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   11400:8):                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   11401:8):                         }
                   11402:8):                     }
                   11403:8):                 } else {
                   11404:8): # Original response item, part of the problem
                   11405:8):                     if ($importedresponses) {
                   11406:8):                         $metaentry{':responseorder'}.=','.$origid;
                   11407:8):                     }
                   11408:8):                 }
                   11409:8):             }
                   11410:8):             if ($importedparts) {
                   11411:8):                 $metaentry{':partorder'}=~s/^\,//;
                   11412:8):             }
                   11413:8):             if ($importedresponses) {
                   11414:8):                 $metaentry{':responseorder'}=~s/^\,//;
                   11415:8):             }
1.1070    www      11416:         }
                   11417: 
1.737     albertel 11418: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 11419: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  11420: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 11421: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      11422: # this is the end of "was not already recently cached
1.71      www      11423:     }
1.599     albertel 11424:     return $metaentry{':'.$what};
1.261     albertel 11425: }
                   11426: 
1.488     albertel 11427: sub metadata_create_package_def {
1.483     albertel 11428:     my ($uri,$key,$package,$metathesekeys)=@_;
                   11429:     my ($pack,$name,$subp)=split(/\&/,$key);
                   11430:     if ($subp eq 'default') { next; }
                   11431:     
1.599     albertel 11432:     if (defined($metaentry{':packages'})) {
                   11433: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 11434:     } else {
1.599     albertel 11435: 	$metaentry{':packages'}=$package;
1.483     albertel 11436:     }
                   11437:     my $value=$packagetab{$key};
                   11438:     my $unikey;
                   11439:     $unikey='parameter_0_'.$name;
1.599     albertel 11440:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 11441:     $$metathesekeys{$unikey}=1;
1.599     albertel 11442:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11443: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 11444:     }
1.599     albertel 11445:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   11446: 	$metaentry{':'.$unikey}=
                   11447: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 11448:     }
                   11449: }
                   11450: 
1.261     albertel 11451: sub metadata_generate_part0 {
                   11452:     my ($metadata,$metacache,$uri) = @_;
                   11453:     my %allnames;
1.737     albertel 11454:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 11455: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 11456: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   11457: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 11458: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 11459: 	    $allnames{$name}=$part;
                   11460: 	  }
                   11461: 	}
                   11462:     }
                   11463:     foreach my $name (keys(%allnames)) {
                   11464:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 11465:       my $key=":parameter_0_$name";
1.261     albertel 11466:       $$metacache{"$key.part"}='0';
                   11467:       $$metacache{"$key.name"}=$name;
1.428     albertel 11468:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 11469: 					   $allnames{$name}.'_'.$name.
                   11470: 					   '.type'};
1.428     albertel 11471:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 11472: 			     '.display'};
1.644     www      11473:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 11474:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 11475:       $$metacache{"$key.display"}=$olddis;
                   11476:     }
1.71      www      11477: }
                   11478: 
1.764     albertel 11479: # ------------------------------------------------------ Devalidate title cache
                   11480: 
                   11481: sub devalidate_title_cache {
                   11482:     my ($url)=@_;
                   11483:     if (!$env{'request.course.id'}) { return; }
                   11484:     my $symb=&symbread($url);
                   11485:     if (!$symb) { return; }
                   11486:     my $key=$env{'request.course.id'}."\0".$symb;
                   11487:     &devalidate_cache_new('title',$key);
                   11488: }
                   11489: 
1.1014    droeschl 11490: # ------------------------------------------------- Get the title of a course
                   11491: 
                   11492: sub current_course_title {
                   11493:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   11494: }
1.301     www      11495: # ------------------------------------------------- Get the title of a resource
                   11496: 
                   11497: sub gettitle {
                   11498:     my $urlsymb=shift;
                   11499:     my $symb=&symbread($urlsymb);
1.534     albertel 11500:     if ($symb) {
1.620     albertel 11501: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 11502: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 11503: 	if (defined($cached)) { 
                   11504: 	    return $result;
                   11505: 	}
1.534     albertel 11506: 	my ($map,$resid,$url)=&decode_symb($symb);
                   11507: 	my $title='';
1.907     albertel 11508: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   11509: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   11510: 	} else {
                   11511: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11512: 		    &GDBM_READER(),0640)) {
                   11513: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   11514: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   11515: 		untie(%bighash);
                   11516: 	    }
1.534     albertel 11517: 	}
                   11518: 	$title=~s/\&colon\;/\:/gs;
                   11519: 	if ($title) {
1.1159    www      11520: # Remember both $symb and $title for dynamic metadata
                   11521:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      11522:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      11523: # Cache this title and then return it
1.599     albertel 11524: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 11525: 	}
                   11526: 	$urlsymb=$url;
                   11527:     }
                   11528:     my $title=&metadata($urlsymb,'title');
                   11529:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   11530:     return $title;
1.301     www      11531: }
1.613     albertel 11532: 
1.614     albertel 11533: sub get_slot {
                   11534:     my ($which,$cnum,$cdom)=@_;
                   11535:     if (!$cnum || !$cdom) {
1.790     albertel 11536: 	(undef,my $courseid)=&whichuser();
1.620     albertel 11537: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   11538: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 11539:     }
1.703     albertel 11540:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   11541:     my %slotinfo;
                   11542:     if (exists($remembered{$key})) {
                   11543: 	$slotinfo{$which} = $remembered{$key};
                   11544:     } else {
                   11545: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   11546: 	&Apache::lonhomework::showhash(%slotinfo);
                   11547: 	my ($tmp)=keys(%slotinfo);
                   11548: 	if ($tmp=~/^error:/) { return (); }
                   11549: 	$remembered{$key} = $slotinfo{$which};
                   11550:     }
1.616     albertel 11551:     if (ref($slotinfo{$which}) eq 'HASH') {
                   11552: 	return %{$slotinfo{$which}};
                   11553:     }
                   11554:     return $slotinfo{$which};
1.614     albertel 11555: }
1.1150    raeburn  11556: 
                   11557: sub get_reservable_slots {
                   11558:     my ($cnum,$cdom,$uname,$udom) = @_;
                   11559:     my $now = time;
                   11560:     my $reservable_info;
                   11561:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   11562:     if (exists($remembered{$key})) {
                   11563:         $reservable_info = $remembered{$key};
                   11564:     } else {
                   11565:         my %resv;
                   11566:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   11567:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   11568:         $reservable_info = \%resv;
                   11569:         $remembered{$key} = $reservable_info;
                   11570:     }
                   11571:     return $reservable_info;
                   11572: }
                   11573: 
                   11574: sub get_course_slots {
                   11575:     my ($cnum,$cdom) = @_;
                   11576:     my $hashid=$cnum.':'.$cdom;
                   11577:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   11578:     if (defined($cached)) {
                   11579:         if (ref($result) eq 'HASH') {
                   11580:             return %{$result};
                   11581:         }
                   11582:     } else {
                   11583:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   11584:         my ($tmp) = keys(%slots);
                   11585:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  11586:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  11587:             return %slots;
                   11588:         }
                   11589:     }
                   11590:     return;
                   11591: }
                   11592: 
                   11593: sub devalidate_slots_cache {
                   11594:     my ($cnum,$cdom)=@_;
                   11595:     my $hashid=$cnum.':'.$cdom;
                   11596:     &devalidate_cache_new('allslots',$hashid);
                   11597: }
                   11598: 
1.1172.2.8  raeburn  11599: sub get_coursechange {
                   11600:     my ($cdom,$cnum) = @_;
                   11601:     if ($cdom eq '' || $cnum eq '') {
                   11602:         return unless ($env{'request.course.id'});
                   11603:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   11604:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11605:     }
                   11606:     my $hashid=$cdom.'_'.$cnum;
                   11607:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   11608:     if ((defined($cached)) && ($change ne '')) {
                   11609:         return $change;
                   11610:     } else {
                   11611:         my %crshash;
                   11612:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   11613:         if ($crshash{'internal.contentchange'} eq '') {
                   11614:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   11615:             if ($change eq '') {
                   11616:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   11617:                 $change = $crshash{'internal.created'};
                   11618:             }
                   11619:         } else {
                   11620:             $change = $crshash{'internal.contentchange'};
                   11621:         }
                   11622:         my $cachetime = 600;
                   11623:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   11624:     }
                   11625:     return $change;
                   11626: }
                   11627: 
                   11628: sub devalidate_coursechange_cache {
                   11629:     my ($cnum,$cdom)=@_;
                   11630:     my $hashid=$cnum.':'.$cdom;
                   11631:     &devalidate_cache_new('crschange',$hashid);
                   11632: }
                   11633: 
1.31      www      11634: # ------------------------------------------------- Update symbolic store links
                   11635: 
                   11636: sub symblist {
                   11637:     my ($mapname,%newhash)=@_;
1.438     www      11638:     $mapname=&deversion(&declutter($mapname));
1.31      www      11639:     my %hash;
1.620     albertel 11640:     if (($env{'request.course.fn'}) && (%newhash)) {
                   11641:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11642:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  11643: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 11644: 		next if ($url eq 'last_known'
                   11645: 			 && $env{'form.no_update_last_known'});
                   11646: 		$hash{declutter($url)}=&encode_symb($mapname,
                   11647: 						    $newhash{$url}->[1],
                   11648: 						    $newhash{$url}->[0]);
1.191     harris41 11649:             }
1.31      www      11650:             if (untie(%hash)) {
                   11651: 		return 'ok';
                   11652:             }
                   11653:         }
                   11654:     }
                   11655:     return 'error';
1.212     www      11656: }
                   11657: 
                   11658: # --------------------------------------------------------------- Verify a symb
                   11659: 
                   11660: sub symbverify {
1.1172.2.11  raeburn  11661:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      11662:     my $thisfn=$thisurl;
1.439     www      11663:     $thisfn=&declutter($thisfn);
1.215     www      11664: # direct jump to resource in page or to a sequence - will construct own symbs
                   11665:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   11666: # check URL part
1.409     www      11667:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      11668: 
1.431     www      11669:     unless ($url eq $thisfn) { return 0; }
1.213     www      11670: 
1.216     www      11671:     $symb=&symbclean($symb);
1.510     www      11672:     $thisurl=&deversion($thisurl);
1.439     www      11673:     $thisfn=&deversion($thisfn);
1.213     www      11674: 
                   11675:     my %bighash;
                   11676:     my $okay=0;
1.431     www      11677: 
1.620     albertel 11678:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11679:                             &GDBM_READER(),0640)) {
1.1172.2.13  raeburn  11680:         my $noclutter;
1.1032    raeburn  11681:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   11682:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  11683:             if ($map =~ m{^uploaded/.+\.page$}) {
                   11684:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   11685:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   11686:                 $noclutter = 1;
                   11687:             }
                   11688:         }
                   11689:         my $ids;
                   11690:         if ($noclutter) {
                   11691:             $ids=$bighash{'ids_'.$thisurl};
                   11692:         } else {
                   11693:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  11694:         }
1.1102    raeburn  11695:         unless ($ids) {
1.1172.2.13  raeburn  11696:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  11697:             $ids=$bighash{$idkey};
1.216     www      11698:         }
                   11699:         if ($ids) {
                   11700: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  11701:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   11702:                 $symb =~ s/\?.+$//;
                   11703:             }
1.800     albertel 11704: 	    foreach my $id (split(/\,/,$ids)) {
                   11705: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      11706:                if (
                   11707:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  11708:    eq $symb) {
1.1172.2.11  raeburn  11709:                    if (ref($encstate)) {
                   11710:                        $$encstate = $bighash{'encrypted_'.$id};
                   11711:                    }
1.1172.2.13  raeburn  11712:                    if (($env{'request.role.adv'}) ||
                   11713:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  11714:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  11715:                        $okay=1;
                   11716:                        last;
                   11717:                    }
                   11718:                }
                   11719:            }
1.216     www      11720:         }
1.213     www      11721: 	untie(%bighash);
                   11722:     }
                   11723:     return $okay;
1.31      www      11724: }
                   11725: 
1.210     www      11726: # --------------------------------------------------------------- Clean-up symb
                   11727: 
                   11728: sub symbclean {
                   11729:     my $symb=shift;
1.568     albertel 11730:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      11731: # remove version from map
                   11732:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      11733: 
1.210     www      11734: # remove version from URL
                   11735:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      11736: 
1.507     www      11737: # remove wrapper
                   11738: 
1.510     www      11739:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 11740:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      11741:     return $symb;
1.409     www      11742: }
                   11743: 
                   11744: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 11745: 
                   11746: sub encode_symb {
                   11747:     my ($map,$resid,$url)=@_;
                   11748:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   11749: }
1.409     www      11750: 
                   11751: sub decode_symb {
1.568     albertel 11752:     my $symb=shift;
                   11753:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   11754:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      11755:     return (&fixversion($map),$resid,&fixversion($url));
                   11756: }
                   11757: 
                   11758: sub fixversion {
                   11759:     my $fn=shift;
1.609     banghart 11760:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      11761:     my %bighash;
                   11762:     my $uri=&clutter($fn);
1.620     albertel 11763:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      11764: # is this cached?
1.599     albertel 11765:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      11766:     if (defined($cached)) { return $result; }
                   11767: # unfortunately not cached, or expired
1.620     albertel 11768:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      11769: 	    &GDBM_READER(),0640)) {
                   11770:  	if ($bighash{'version_'.$uri}) {
                   11771:  	    my $version=$bighash{'version_'.$uri};
1.444     www      11772:  	    unless (($version eq 'mostrecent') || 
                   11773: 		    ($version==&getversion($uri))) {
1.440     www      11774:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   11775:  	    }
                   11776:  	}
                   11777:  	untie %bighash;
1.413     www      11778:     }
1.599     albertel 11779:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      11780: }
                   11781: 
                   11782: sub deversion {
                   11783:     my $url=shift;
                   11784:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   11785:     return $url;
1.210     www      11786: }
                   11787: 
1.31      www      11788: # ------------------------------------------------------ Return symb list entry
                   11789: 
                   11790: sub symbread {
1.1172.2.66  raeburn  11791:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54  raeburn  11792:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66  raeburn  11793:     if (defined($env{$cache_str})) {
                   11794:         if ($ignorecachednull) {
                   11795:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   11796:         } else {
                   11797:             return $env{$cache_str};
                   11798:         }
                   11799:     }
1.242     www      11800: # no filename provided? try from environment
1.1172.2.54  raeburn  11801:     unless ($thisfn) {
1.620     albertel 11802:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  11803:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   11804:         }
                   11805:         $thisfn=$env{'request.filename'};
1.44      www      11806:     }
1.569     albertel 11807:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      11808: # is that filename actually a symb? Verify, clean, and return
                   11809:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 11810: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 11811: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 11812: 	}
1.242     www      11813:     }
1.44      www      11814:     $thisfn=declutter($thisfn);
1.31      www      11815:     my %hash;
1.37      www      11816:     my %bighash;
                   11817:     my $syval='';
1.620     albertel 11818:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  11819:         my $targetfn = $thisfn;
1.609     banghart 11820:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  11821:             $targetfn = 'adm/wrapper/'.$thisfn;
                   11822:         }
1.687     albertel 11823: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   11824: 	    $targetfn=$1;
                   11825: 	}
1.620     albertel 11826:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11827:                       &GDBM_READER(),0640)) {
1.481     raeburn  11828: 	    $syval=$hash{$targetfn};
1.37      www      11829:             untie(%hash);
                   11830:         }
                   11831: # ---------------------------------------------------------- There was an entry
                   11832:         if ($syval) {
1.601     albertel 11833: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 11834: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  11835: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11836: 		    #return $env{$cache_str}='';
1.601     albertel 11837: 		#}    
                   11838: 		#$syval.=$1;
                   11839: 	    #}
1.37      www      11840:         } else {
                   11841: # ------------------------------------------------------- Was not in symb table
1.620     albertel 11842:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11843:                             &GDBM_READER(),0640)) {
1.37      www      11844: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      11845:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      11846:               unless ($ids) { 
                   11847:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      11848:               }
                   11849:               unless ($ids) {
                   11850: # alias?
                   11851: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      11852:               }
1.37      www      11853:               if ($ids) {
                   11854: # ------------------------------------------------------------------- Has ID(s)
                   11855:                  my @possibilities=split(/\,/,$ids);
1.39      www      11856:                  if ($#possibilities==0) {
                   11857: # ----------------------------------------------- There is only one possibility
1.37      www      11858: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 11859: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11860: 						    $resid,$thisfn);
1.1172.2.66  raeburn  11861:                      if (ref($possibles) eq 'HASH') {
                   11862:                          $possibles->{$syval} = 1;
                   11863:                      }
                   11864:                      if ($checkforblock) {
                   11865:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   11866:                          if (@blockers) {
                   11867:                              $syval = '';
                   11868:                              return;
                   11869:                          }
                   11870:                      }
                   11871:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      11872: # ------------------------------------------ There is more than one possibility
                   11873:                      my $realpossible=0;
1.800     albertel 11874:                      foreach my $id (@possibilities) {
                   11875: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  11876:                          my $canaccess;
                   11877:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   11878:                              $canaccess = 1;
                   11879:                          } else {
                   11880:                              $canaccess = &allowed('bre',$file);
                   11881:                          }
                   11882:                          if ($canaccess) {
                   11883:          		     my ($mapid,$resid)=split(/\./,$id);
                   11884:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   11885:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11886:                                                              $resid,$thisfn);
                   11887:                                  if (ref($possibles) eq 'HASH') {
                   11888:                                      $possibles->{$syval} = 1;
                   11889:                                  }
                   11890:                                  if ($checkforblock) {
                   11891:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   11892:                                      unless (@blockers > 0) {
                   11893:                                          $syval = $poss_syval;
                   11894:                                          $realpossible++;
                   11895:                                      }
                   11896:                                  } else {
                   11897:                                      $syval = $poss_syval;
                   11898:                                      $realpossible++;
                   11899:                                  }
                   11900:                              }
1.39      www      11901: 			 }
1.191     harris41 11902:                      }
1.39      www      11903: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      11904:                  } else {
                   11905:                      $syval='';
1.37      www      11906:                  }
                   11907: 	      }
1.1172.2.66  raeburn  11908:               untie(%bighash);
1.481     raeburn  11909:            }
1.31      www      11910:         }
1.62      www      11911:         if ($syval) {
1.620     albertel 11912: 	    return $env{$cache_str}=$syval;
1.62      www      11913:         }
1.31      www      11914:     }
1.949     raeburn  11915:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11916:     return $env{$cache_str}='';
1.31      www      11917: }
                   11918: 
                   11919: # ---------------------------------------------------------- Return random seed
                   11920: 
1.32      www      11921: sub numval {
                   11922:     my $txt=shift;
                   11923:     $txt=~tr/A-J/0-9/;
                   11924:     $txt=~tr/a-j/0-9/;
                   11925:     $txt=~tr/K-T/0-9/;
                   11926:     $txt=~tr/k-t/0-9/;
                   11927:     $txt=~tr/U-Z/0-5/;
                   11928:     $txt=~tr/u-z/0-5/;
                   11929:     $txt=~s/\D//g;
1.564     albertel 11930:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      11931:     return int($txt);
1.368     albertel 11932: }
                   11933: 
1.484     albertel 11934: sub numval2 {
                   11935:     my $txt=shift;
                   11936:     $txt=~tr/A-J/0-9/;
                   11937:     $txt=~tr/a-j/0-9/;
                   11938:     $txt=~tr/K-T/0-9/;
                   11939:     $txt=~tr/k-t/0-9/;
                   11940:     $txt=~tr/U-Z/0-5/;
                   11941:     $txt=~tr/u-z/0-5/;
                   11942:     $txt=~s/\D//g;
                   11943:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11944:     my $total;
                   11945:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 11946:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 11947:     return int($total);
                   11948: }
                   11949: 
1.575     albertel 11950: sub numval3 {
                   11951:     use integer;
                   11952:     my $txt=shift;
                   11953:     $txt=~tr/A-J/0-9/;
                   11954:     $txt=~tr/a-j/0-9/;
                   11955:     $txt=~tr/K-T/0-9/;
                   11956:     $txt=~tr/k-t/0-9/;
                   11957:     $txt=~tr/U-Z/0-5/;
                   11958:     $txt=~tr/u-z/0-5/;
                   11959:     $txt=~s/\D//g;
                   11960:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11961:     my $total;
                   11962:     foreach my $val (@txts) { $total+=$val; }
                   11963:     if ($_64bit) { $total=(($total<<32)>>32); }
                   11964:     return $total;
                   11965: }
                   11966: 
1.675     albertel 11967: sub digest {
                   11968:     my ($data)=@_;
                   11969:     my $digest=&Digest::MD5::md5($data);
                   11970:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   11971:     my ($e,$f);
                   11972:     {
                   11973:         use integer;
                   11974:         $e=($a+$b);
                   11975:         $f=($c+$d);
                   11976:         if ($_64bit) {
                   11977:             $e=(($e<<32)>>32);
                   11978:             $f=(($f<<32)>>32);
                   11979:         }
                   11980:     }
                   11981:     if (wantarray) {
                   11982: 	return ($e,$f);
                   11983:     } else {
                   11984: 	my $g;
                   11985: 	{
                   11986: 	    use integer;
                   11987: 	    $g=($e+$f);
                   11988: 	    if ($_64bit) {
                   11989: 		$g=(($g<<32)>>32);
                   11990: 	    }
                   11991: 	}
                   11992: 	return $g;
                   11993:     }
                   11994: }
                   11995: 
1.368     albertel 11996: sub latest_rnd_algorithm_id {
1.675     albertel 11997:     return '64bit5';
1.366     albertel 11998: }
1.32      www      11999: 
1.503     albertel 12000: sub get_rand_alg {
                   12001:     my ($courseid)=@_;
1.790     albertel 12002:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12003:     if ($courseid) {
1.620     albertel 12004: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12005:     }
                   12006:     return &latest_rnd_algorithm_id();
                   12007: }
                   12008: 
1.562     albertel 12009: sub validCODE {
                   12010:     my ($CODE)=@_;
                   12011:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12012:     return 0;
                   12013: }
                   12014: 
1.491     albertel 12015: sub getCODE {
1.620     albertel 12016:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12017:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12018: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12019: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12020: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12021:     }
                   12022:     return undef;
                   12023: }
1.1133    foxr     12024: #
                   12025: #  Determines the random seed for a specific context:
                   12026: #
                   12027: # parameters:
                   12028: #   symb      - in course context the symb for the seed.
                   12029: #   course_id - The course id of the form domain_coursenum.
                   12030: #   domain    - Domain for the user.
                   12031: #   course    - Course for the user.
                   12032: #   cenv      - environment of the course.
                   12033: #
                   12034: # NOTE:
                   12035: #   All parameters are picked out of the environment if missing
                   12036: #   or not defined.
                   12037: #   If a symb cannot be determined the current time is used instead.
                   12038: #
                   12039: #  For a given well defined symb, courside, domain, username,
                   12040: #  and course environment, the seed is reproducible.
                   12041: #
1.31      www      12042: sub rndseed {
1.1133    foxr     12043:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12044:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12045:     if (!defined($symb)) {
1.366     albertel 12046: 	unless ($symb=$wsymb) { return time; }
                   12047:     }
1.1146    foxr     12048:     if (!defined $courseid) { 
                   12049: 	$courseid=$wcourseid; 
                   12050:     }
                   12051:     if (!defined $domain) { $domain=$wdomain; }
                   12052:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12053: 
                   12054:     my $which;
                   12055:     if (defined($cenv->{'rndseed'})) {
                   12056: 	$which = $cenv->{'rndseed'};
                   12057:     } else {
                   12058: 	$which =&get_rand_alg($courseid);
                   12059:     }
1.491     albertel 12060:     if (defined(&getCODE())) {
1.675     albertel 12061: 	if ($which eq '64bit5') {
                   12062: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12063: 	} elsif ($which eq '64bit4') {
1.575     albertel 12064: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12065: 	} else {
                   12066: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12067: 	}
1.675     albertel 12068:     } elsif ($which eq '64bit5') {
                   12069: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12070:     } elsif ($which eq '64bit4') {
                   12071: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12072:     } elsif ($which eq '64bit3') {
                   12073: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12074:     } elsif ($which eq '64bit2') {
                   12075: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12076:     } elsif ($which eq '64bit') {
                   12077: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12078:     }
                   12079:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12080: }
                   12081: 
                   12082: sub rndseed_32bit {
                   12083:     my ($symb,$courseid,$domain,$username)=@_;
                   12084:     {
                   12085: 	use integer;
                   12086: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12087: 	my $symbseed=numval($symb) << 22;
                   12088: 	my $namechck=unpack("%32C*",$username) << 17;
                   12089: 	my $nameseed=numval($username) << 12;
                   12090: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12091: 	my $courseseed=unpack("%32C*",$courseid);
                   12092: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12093: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12094: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12095: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12096: 	return $num;
                   12097:     }
                   12098: }
                   12099: 
                   12100: sub rndseed_64bit {
                   12101:     my ($symb,$courseid,$domain,$username)=@_;
                   12102:     {
                   12103: 	use integer;
                   12104: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12105: 	my $symbseed=numval($symb) << 10;
                   12106: 	my $namechck=unpack("%32S*",$username);
                   12107: 	
                   12108: 	my $nameseed=numval($username) << 21;
                   12109: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12110: 	my $courseseed=unpack("%32S*",$courseid);
                   12111: 	
                   12112: 	my $num1=$symbchck+$symbseed+$namechck;
                   12113: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12114: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12115: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12116: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12117: 	return "$num1,$num2";
1.155     albertel 12118:     }
1.366     albertel 12119: }
                   12120: 
1.443     albertel 12121: sub rndseed_64bit2 {
                   12122:     my ($symb,$courseid,$domain,$username)=@_;
                   12123:     {
                   12124: 	use integer;
                   12125: 	# strings need to be an even # of cahracters long, it it is odd the
                   12126:         # last characters gets thrown away
                   12127: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12128: 	my $symbseed=numval($symb) << 10;
                   12129: 	my $namechck=unpack("%32S*",$username.' ');
                   12130: 	
                   12131: 	my $nameseed=numval($username) << 21;
1.501     albertel 12132: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12133: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12134: 	
                   12135: 	my $num1=$symbchck+$symbseed+$namechck;
                   12136: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12137: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12138: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12139: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12140: 	return "$num1,$num2";
                   12141:     }
                   12142: }
                   12143: 
                   12144: sub rndseed_64bit3 {
                   12145:     my ($symb,$courseid,$domain,$username)=@_;
                   12146:     {
                   12147: 	use integer;
                   12148: 	# strings need to be an even # of cahracters long, it it is odd the
                   12149:         # last characters gets thrown away
                   12150: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12151: 	my $symbseed=numval2($symb) << 10;
                   12152: 	my $namechck=unpack("%32S*",$username.' ');
                   12153: 	
                   12154: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12155: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12156: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12157: 	
                   12158: 	my $num1=$symbchck+$symbseed+$namechck;
                   12159: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12160: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12161: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12162: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12163: 	
1.503     albertel 12164: 	return "$num1:$num2";
1.443     albertel 12165:     }
                   12166: }
                   12167: 
1.575     albertel 12168: sub rndseed_64bit4 {
                   12169:     my ($symb,$courseid,$domain,$username)=@_;
                   12170:     {
                   12171: 	use integer;
                   12172: 	# strings need to be an even # of cahracters long, it it is odd the
                   12173:         # last characters gets thrown away
                   12174: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12175: 	my $symbseed=numval3($symb) << 10;
                   12176: 	my $namechck=unpack("%32S*",$username.' ');
                   12177: 	
                   12178: 	my $nameseed=numval3($username) << 21;
                   12179: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12180: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12181: 	
                   12182: 	my $num1=$symbchck+$symbseed+$namechck;
                   12183: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12184: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12185: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12186: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12187: 	
1.575     albertel 12188: 	return "$num1:$num2";
                   12189:     }
                   12190: }
                   12191: 
1.675     albertel 12192: sub rndseed_64bit5 {
                   12193:     my ($symb,$courseid,$domain,$username)=@_;
                   12194:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12195:     return "$num1:$num2";
                   12196: }
                   12197: 
1.366     albertel 12198: sub rndseed_CODE_64bit {
                   12199:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12200:     {
1.366     albertel 12201: 	use integer;
1.443     albertel 12202: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12203: 	my $symbseed=numval2($symb);
1.491     albertel 12204: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12205: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12206: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12207: 	my $num1=$symbseed+$CODEchck;
                   12208: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12209: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12210: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12211: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12212: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12213: 	return "$num1:$num2";
1.366     albertel 12214:     }
                   12215: }
                   12216: 
1.575     albertel 12217: sub rndseed_CODE_64bit4 {
                   12218:     my ($symb,$courseid,$domain,$username)=@_;
                   12219:     {
                   12220: 	use integer;
                   12221: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12222: 	my $symbseed=numval3($symb);
                   12223: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12224: 	my $CODEseed=numval3(&getCODE());
                   12225: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12226: 	my $num1=$symbseed+$CODEchck;
                   12227: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12228: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12229: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12230: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12231: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12232: 	return "$num1:$num2";
                   12233:     }
                   12234: }
                   12235: 
1.675     albertel 12236: sub rndseed_CODE_64bit5 {
                   12237:     my ($symb,$courseid,$domain,$username)=@_;
                   12238:     my $code = &getCODE();
                   12239:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12240:     return "$num1:$num2";
                   12241: }
                   12242: 
1.366     albertel 12243: sub setup_random_from_rndseed {
                   12244:     my ($rndseed)=@_;
1.503     albertel 12245:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  12246: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12247:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12248:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   12249:         } else {
                   12250:             &Math::Random::random_set_seed($num1,$num2);
                   12251:         }
1.366     albertel 12252:     } else {
                   12253: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12254:     }
1.36      albertel 12255: }
                   12256: 
1.474     albertel 12257: sub latest_receipt_algorithm_id {
1.835     albertel 12258:     return 'receipt3';
1.474     albertel 12259: }
                   12260: 
1.480     www      12261: sub recunique {
                   12262:     my $fucourseid=shift;
                   12263:     my $unique;
1.835     albertel 12264:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   12265: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12266: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      12267:     } else {
                   12268: 	$unique=$perlvar{'lonReceipt'};
                   12269:     }
                   12270:     return unpack("%32C*",$unique);
                   12271: }
                   12272: 
                   12273: sub recprefix {
                   12274:     my $fucourseid=shift;
                   12275:     my $prefix;
1.835     albertel 12276:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   12277: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12278: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      12279:     } else {
                   12280: 	$prefix=$perlvar{'lonHostID'};
                   12281:     }
                   12282:     return unpack("%32C*",$prefix);
                   12283: }
                   12284: 
1.76      www      12285: sub ireceipt {
1.474     albertel 12286:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 12287: 
                   12288:     my $return =&recprefix($fucourseid).'-';
                   12289: 
                   12290:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   12291: 	$env{'request.state'} eq 'construct') {
                   12292: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   12293: 	return $return;
                   12294:     }
                   12295: 
1.76      www      12296:     my $cuname=unpack("%32C*",$funame);
                   12297:     my $cudom=unpack("%32C*",$fudom);
                   12298:     my $cucourseid=unpack("%32C*",$fucourseid);
                   12299:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      12300:     my $cunique=&recunique($fucourseid);
1.474     albertel 12301:     my $cpart=unpack("%32S*",$part);
1.835     albertel 12302:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   12303: 
1.790     albertel 12304: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 12305: 			       
                   12306: 	$return.= ($cunique%$cuname+
                   12307: 		   $cunique%$cudom+
                   12308: 		   $cusymb%$cuname+
                   12309: 		   $cusymb%$cudom+
                   12310: 		   $cucourseid%$cuname+
                   12311: 		   $cucourseid%$cudom+
                   12312: 		   $cpart%$cuname+
                   12313: 		   $cpart%$cudom);
                   12314:     } else {
                   12315: 	$return.= ($cunique%$cuname+
                   12316: 		   $cunique%$cudom+
                   12317: 		   $cusymb%$cuname+
                   12318: 		   $cusymb%$cudom+
                   12319: 		   $cucourseid%$cuname+
                   12320: 		   $cucourseid%$cudom);
                   12321:     }
                   12322:     return $return;
1.76      www      12323: }
                   12324: 
                   12325: sub receipt {
1.474     albertel 12326:     my ($part)=@_;
1.790     albertel 12327:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 12328:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      12329: }
1.260     ng       12330: 
1.790     albertel 12331: sub whichuser {
                   12332:     my ($passedsymb)=@_;
                   12333:     my ($symb,$courseid,$domain,$name,$publicuser);
                   12334:     if (defined($env{'form.grade_symb'})) {
                   12335: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   12336: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   12337: 	if (!$allowed &&
                   12338: 	    exists($env{'request.course.sec'}) &&
                   12339: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   12340: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   12341: 			      '/'.$env{'request.course.sec'});
                   12342: 	}
                   12343: 	if ($allowed) {
                   12344: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   12345: 	    $courseid=$tmp_courseid;
                   12346: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   12347: 	    ($name)=&get_env_multiple('form.grade_username');
                   12348: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   12349: 	}
                   12350:     }
                   12351:     if (!$passedsymb) {
                   12352: 	$symb=&symbread();
                   12353:     } else {
                   12354: 	$symb=$passedsymb;
                   12355:     }
                   12356:     $courseid=$env{'request.course.id'};
                   12357:     $domain=$env{'user.domain'};
                   12358:     $name=$env{'user.name'};
                   12359:     if ($name eq 'public' && $domain eq 'public') {
                   12360: 	if (!defined($env{'form.username'})) {
                   12361: 	    $env{'form.username'}.=time.rand(10000000);
                   12362: 	}
                   12363: 	$name.=$env{'form.username'};
                   12364:     }
                   12365:     return ($symb,$courseid,$domain,$name,$publicuser);
                   12366: 
                   12367: }
                   12368: 
1.36      albertel 12369: # ------------------------------------------------------------ Serves up a file
1.472     albertel 12370: # returns either the contents of the file or 
                   12371: # -1 if the file doesn't exist
1.481     raeburn  12372: #
                   12373: # if the target is a file that was uploaded via DOCS, 
                   12374: # a check will be made to see if a current copy exists on the local server,
                   12375: # if it does this will be served, otherwise a copy will be retrieved from
                   12376: # the home server for the course and stored in /home/httpd/html/userfiles on
                   12377: # the local server.   
1.472     albertel 12378: 
1.36      albertel 12379: sub getfile {
1.538     albertel 12380:     my ($file) = @_;
1.609     banghart 12381:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 12382:     &repcopy($file);
                   12383:     return &readfile($file);
                   12384: }
                   12385: 
                   12386: sub repcopy_userfile {
                   12387:     my ($file)=@_;
1.1142    raeburn  12388:     my $londocroot = $perlvar{'lonDocRoot'};
                   12389:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  12390:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 12391:     my ($cdom,$cnum,$filename) = 
1.811     albertel 12392: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 12393:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   12394:     if (-e "$file") {
1.828     www      12395: # we already have a local copy, check it out
1.538     albertel 12396: 	my @fileinfo = stat($file);
1.828     www      12397: 	my $rtncode;
                   12398: 	my $info;
1.538     albertel 12399: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 12400: 	if ($lwpresp ne 'ok') {
1.828     www      12401: # there is no such file anymore, even though we had a local copy
1.482     albertel 12402: 	    if ($rtncode eq '404') {
1.538     albertel 12403: 		unlink($file);
1.482     albertel 12404: 	    }
                   12405: 	    return -1;
                   12406: 	}
                   12407: 	if ($info < $fileinfo[9]) {
1.828     www      12408: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  12409: 	    return 'ok';
1.828     www      12410: 	} else {
                   12411: # the file is outdated, get rid of it
                   12412: 	    unlink($file);
1.482     albertel 12413: 	}
1.828     www      12414:     }
                   12415: # one way or the other, at this point, we don't have the file
                   12416: # construct the correct path for the file
                   12417:     my @parts = ($cdom,$cnum); 
                   12418:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   12419: 	push @parts, split(/\//,$1);
                   12420:     }
                   12421:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   12422:     foreach my $part (@parts) {
                   12423: 	$path .= '/'.$part;
                   12424: 	if (!-e $path) {
                   12425: 	    mkdir($path,0770);
1.482     albertel 12426: 	}
                   12427:     }
1.828     www      12428: # now the path exists for sure
                   12429: # get a user agent
                   12430:     my $ua=new LWP::UserAgent;
                   12431:     my $transferfile=$file.'.in.transfer';
                   12432: # FIXME: this should flock
                   12433:     if (-e $transferfile) { return 'ok'; }
                   12434:     my $request;
                   12435:     $uri=~s/^\///;
1.980     raeburn  12436:     my $homeserver = &homeserver($cnum,$cdom);
                   12437:     my $protocol = $protocol{$homeserver};
                   12438:     $protocol = 'http' if ($protocol ne 'https');
                   12439:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      12440:     my $response=$ua->request($request,$transferfile);
                   12441: # did it work?
                   12442:     if ($response->is_error()) {
                   12443: 	unlink($transferfile);
                   12444: 	&logthis("Userfile repcopy failed for $uri");
                   12445: 	return -1;
                   12446:     }
                   12447: # worked, rename the transfer file
                   12448:     rename($transferfile,$file);
1.607     raeburn  12449:     return 'ok';
1.481     raeburn  12450: }
                   12451: 
1.517     albertel 12452: sub tokenwrapper {
                   12453:     my $uri=shift;
1.980     raeburn  12454:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 12455:     $uri=~s|^/||;
1.620     albertel 12456:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 12457:     my $token=$1;
1.552     albertel 12458:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   12459:     if ($udom && $uname && $file) {
                   12460: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  12461:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  12462:         my $homeserver = &homeserver($uname,$udom);
                   12463:         my $protocol = $protocol{$homeserver};
                   12464:         $protocol = 'http' if ($protocol ne 'https');
                   12465:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 12466:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   12467:                                '&tokenissued='.$perlvar{'lonHostID'};
                   12468:     } else {
                   12469:         return '/adm/notfound.html';
                   12470:     }
                   12471: }
                   12472: 
1.828     www      12473: # call with reqtype HEAD: get last modification time
                   12474: # call with reqtype GET: get the file contents
                   12475: # Do not call this with reqtype GET for large files! It loads everything into memory
                   12476: #
1.481     raeburn  12477: sub getuploaded {
                   12478:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   12479:     $uri=~s/^\///;
1.980     raeburn  12480:     my $homeserver = &homeserver($cnum,$cdom);
                   12481:     my $protocol = $protocol{$homeserver};
                   12482:     $protocol = 'http' if ($protocol ne 'https');
                   12483:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  12484:     my $ua=new LWP::UserAgent;
                   12485:     my $request=new HTTP::Request($reqtype,$uri);
                   12486:     my $response=$ua->request($request);
                   12487:     $$rtncode = $response->code;
1.482     albertel 12488:     if (! $response->is_success()) {
                   12489: 	return 'failed';
                   12490:     }      
                   12491:     if ($reqtype eq 'HEAD') {
1.486     www      12492: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 12493:     } elsif ($reqtype eq 'GET') {
                   12494: 	$$info = $response->content;
1.472     albertel 12495:     }
1.482     albertel 12496:     return 'ok';
1.36      albertel 12497: }
                   12498: 
1.481     raeburn  12499: sub readfile {
                   12500:     my $file = shift;
                   12501:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   12502:     my $fh;
1.1172.2.93.4  7(raebur 12503:7):     open($fh,"<",$file);
1.481     raeburn  12504:     my $a='';
1.800     albertel 12505:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  12506:     return $a;
                   12507: }
                   12508: 
1.36      albertel 12509: sub filelocation {
1.590     banghart 12510:     my ($dir,$file) = @_;
                   12511:     my $location;
                   12512:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 12513: 
                   12514:     if ($file =~ m-^/adm/-) {
                   12515: 	$file=~s-^/adm/wrapper/-/-;
                   12516: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   12517:     }
1.882     albertel 12518: 
1.1139    www      12519:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  12520:         $location = $file;
1.609     banghart 12521:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 12522:         my ($udom,$uname,$filename)=
1.811     albertel 12523:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 12524:         my $home=&homeserver($uname,$udom);
                   12525:         my $is_me=0;
                   12526:         my @ids=&current_machine_ids();
                   12527:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   12528:         if ($is_me) {
1.1117    foxr     12529:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 12530:         } else {
                   12531:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   12532:   	      $udom.'/'.$uname.'/'.$filename;
                   12533:         }
1.882     albertel 12534:     } elsif ($file =~ m-^/adm/-) {
                   12535: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 12536:     } else {
                   12537:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      12538:         $file=~s:^/(res|priv)/:/:;
                   12539:         my $space=$1;
1.590     banghart 12540:         if ( !( $file =~ m:^/:) ) {
                   12541:             $location = $dir. '/'.$file;
                   12542:         } else {
1.1142    raeburn  12543:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 12544:         }
1.59      albertel 12545:     }
1.590     banghart 12546:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 12547:     while ($location=~m{/\.\./}) {
                   12548: 	if ($location =~ m{/[^/]+/\.\./}) {
                   12549: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   12550: 	} else {
                   12551: 	    $location=~ s{/\.\./}{/}g;
                   12552: 	}
                   12553:     } #remove dir/..
1.590     banghart 12554:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   12555:     return $location;
1.46      www      12556: }
1.36      albertel 12557: 
1.46      www      12558: sub hreflocation {
                   12559:     my ($dir,$file)=@_;
1.980     raeburn  12560:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 12561: 	$file=filelocation($dir,$file);
1.700     albertel 12562:     } elsif ($file=~m-^/adm/-) {
                   12563: 	$file=~s-^/adm/wrapper/-/-;
                   12564: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 12565:     }
                   12566:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   12567: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   12568:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  12569: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   12570: 	        {/uploaded/$1/$2/}x;
1.46      www      12571:     }
1.913     albertel 12572:     if ($file=~ m{^/userfiles/}) {
                   12573: 	$file =~ s{^/userfiles/}{/uploaded/};
                   12574:     }
1.462     albertel 12575:     return $file;
1.465     albertel 12576: }
                   12577: 
1.1139    www      12578: 
                   12579: 
                   12580: 
                   12581: 
1.465     albertel 12582: sub current_machine_domains {
1.853     albertel 12583:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   12584: }
                   12585: 
                   12586: sub machine_domains {
                   12587:     my ($hostname) = @_;
1.465     albertel 12588:     my @domains;
1.838     albertel 12589:     my %hostname = &all_hostnames();
1.465     albertel 12590:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  12591: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 12592: 	if ($hostname eq $name) {
1.844     albertel 12593: 	    push(@domains,&host_domain($id));
1.465     albertel 12594: 	}
                   12595:     }
                   12596:     return @domains;
                   12597: }
                   12598: 
                   12599: sub current_machine_ids {
1.853     albertel 12600:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   12601: }
                   12602: 
                   12603: sub machine_ids {
                   12604:     my ($hostname) = @_;
                   12605:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 12606:     my @ids;
1.888     albertel 12607:     my %name_to_host = &all_names();
1.889     albertel 12608:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   12609: 	return @{ $name_to_host{$hostname} };
                   12610:     }
                   12611:     return;
1.31      www      12612: }
                   12613: 
1.824     raeburn  12614: sub additional_machine_domains {
                   12615:     my @domains;
1.1172.2.93.4  7(raebur 12616:7):     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  12617:     while( my $line = <$fh>) {
                   12618:         $line =~ s/\s//g;
                   12619:         push(@domains,$line);
                   12620:     }
                   12621:     return @domains;
                   12622: }
                   12623: 
                   12624: sub default_login_domain {
                   12625:     my $domain = $perlvar{'lonDefDomain'};
                   12626:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   12627:     foreach my $posdom (&current_machine_domains(),
                   12628:                         &additional_machine_domains()) {
                   12629:         if (lc($posdom) eq lc($testdomain)) {
                   12630:             $domain=$posdom;
                   12631:             last;
                   12632:         }
                   12633:     }
                   12634:     return $domain;
                   12635: }
                   12636: 
1.31      www      12637: # ------------------------------------------------------------- Declutters URLs
                   12638: 
                   12639: sub declutter {
                   12640:     my $thisfn=shift;
1.569     albertel 12641:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  12642:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   12643:         $thisfn=~s{^/home/httpd/html}{};
                   12644:     }
1.31      www      12645:     $thisfn=~s/^\///;
1.697     albertel 12646:     $thisfn=~s|^adm/wrapper/||;
                   12647:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      12648:     $thisfn=~s/^res\///;
1.1172    bisitz   12649:     $thisfn=~s/^priv\///;
1.1032    raeburn  12650:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   12651:         $thisfn=~s/\?.+$//;
                   12652:     }
1.268     www      12653:     return $thisfn;
                   12654: }
                   12655: 
                   12656: # ------------------------------------------------------------- Clutter up URLs
                   12657: 
                   12658: sub clutter {
                   12659:     my $thisfn='/'.&declutter(shift);
1.887     albertel 12660:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 12661: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      12662:        $thisfn='/res'.$thisfn; 
                   12663:     }
1.1031    raeburn  12664:     if ($thisfn !~m|^/adm|) {
                   12665: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 12666: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 12667: 	} else {
                   12668: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   12669: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 12670: 	    if ($embstyle eq 'ssi'
                   12671: 		|| ($embstyle eq 'hdn')
                   12672: 		|| ($embstyle eq 'rat')
                   12673: 		|| ($embstyle eq 'prv')
                   12674: 		|| ($embstyle eq 'ign')) {
                   12675: 		#do nothing with these
                   12676: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 12677: 		|| ($embstyle eq 'emb')
                   12678: 		|| ($embstyle eq 'wrp')) {
                   12679: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 12680: 	    } elsif ($embstyle eq 'unk'
                   12681: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 12682: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 12683: 	    } else {
1.718     www      12684: #		&logthis("Got a blank emb style");
1.695     albertel 12685: 	    }
1.694     albertel 12686: 	}
1.1172.2.93.4  2(raebur 12687:7):     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
                   12688:7):         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 12689:     }
1.31      www      12690:     return $thisfn;
1.12      www      12691: }
                   12692: 
1.787     albertel 12693: sub clutter_with_no_wrapper {
                   12694:     my $uri = &clutter(shift);
                   12695:     if ($uri =~ m-^/adm/-) {
                   12696: 	$uri =~ s-^/adm/wrapper/-/-;
                   12697: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   12698:     }
                   12699:     return $uri;
                   12700: }
                   12701: 
1.557     albertel 12702: sub freeze_escape {
                   12703:     my ($value)=@_;
                   12704:     if (ref($value)) {
                   12705: 	$value=&nfreeze($value);
                   12706: 	return '__FROZEN__'.&escape($value);
                   12707:     }
                   12708:     return &escape($value);
                   12709: }
                   12710: 
1.11      www      12711: 
1.557     albertel 12712: sub thaw_unescape {
                   12713:     my ($value)=@_;
                   12714:     if ($value =~ /^__FROZEN__/) {
                   12715: 	substr($value,0,10,undef);
                   12716: 	$value=&unescape($value);
                   12717: 	return &thaw($value);
                   12718:     }
                   12719:     return &unescape($value);
                   12720: }
                   12721: 
1.436     albertel 12722: sub correct_line_ends {
                   12723:     my ($result)=@_;
                   12724:     $$result =~s/\r\n/\n/mg;
                   12725:     $$result =~s/\r/\n/mg;
1.415     albertel 12726: }
1.1       albertel 12727: # ================================================================ Main Program
                   12728: 
1.184     www      12729: sub goodbye {
1.204     albertel 12730:    &logthis("Starting Shut down");
1.443     albertel 12731: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 12732:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 12733: #converted
1.599     albertel 12734: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 12735:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   12736: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   12737: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 12738: #1.1 only
1.870     albertel 12739: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   12740: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   12741: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   12742: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   12743:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 12744:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   12745:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      12746:    &flushcourselogs();
                   12747:    &logthis("Shutting down");
                   12748: }
                   12749: 
1.852     albertel 12750: sub get_dns {
1.1172.2.17  raeburn  12751:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 12752:     if (!$ignore_cache) {
                   12753: 	my ($content,$cached)=
                   12754: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   12755: 	if ($cached) {
1.1172.2.17  raeburn  12756: 	    &$func($content,$hashref);
1.869     albertel 12757: 	    return;
                   12758: 	}
                   12759:     }
                   12760: 
                   12761:     my %alldns;
1.1172.2.93.4  7(raebur 12762:7):     open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 12763:     foreach my $dns (<$config>) {
                   12764: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  12765:         my $line = $1;
                   12766:         my ($host,$protocol) = split(/:/,$line);
                   12767:         if ($protocol ne 'https') {
                   12768:             $protocol = 'http';
                   12769:         }
                   12770: 	$alldns{$host} = $protocol;
1.869     albertel 12771:     }
                   12772:     while (%alldns) {
1.1172.2.52  raeburn  12773: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 12774: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  12775:         $ua->timeout(30);
1.979     raeburn  12776: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 12777: 	my $response=$ua->request($request);
1.979     raeburn  12778:         delete($alldns{$dns});
1.852     albertel 12779: 	next if ($response->is_error());
                   12780: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  12781:         unless ($nocache) {
1.1172.2.23  raeburn  12782: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  12783:         }
                   12784: 	&$func(\@content,$hashref);
1.869     albertel 12785: 	return;
1.852     albertel 12786:     }
                   12787:     close($config);
1.871     albertel 12788:     my $which = (split('/',$url))[3];
                   12789:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.93.4  7(raebur 12790:7):     open($config,"<","$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 12791:     my @content = <$config>;
1.1172.2.17  raeburn  12792:     &$func(\@content,$hashref);
                   12793:     return;
                   12794: }
                   12795: 
                   12796: # ------------------------------------------------------Get DNS checksums file
                   12797: sub parse_dns_checksums_tab {
                   12798:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  12799:     my $lonhost = $perlvar{'lonHostID'};
                   12800:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  12801:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  12802:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   12803:     my $webconfdir = '/etc/httpd/conf';
                   12804:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   12805:         $webconfdir = '/etc/apache2';
                   12806:     } elsif ($distro =~ /^sles(\d+)$/) {
                   12807:         if ($1 >= 10) {
                   12808:             $webconfdir = '/etc/apache2';
                   12809:         }
                   12810:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   12811:         if ($1 >= 10.0) {
                   12812:             $webconfdir = '/etc/apache2';
                   12813:         }
                   12814:     }
1.1172.2.17  raeburn  12815:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12816:     my (%chksum,%revnum);
                   12817:     if (ref($lines) eq 'ARRAY') {
                   12818:         chomp(@{$lines});
1.1172.2.34  raeburn  12819:         my $version = shift(@{$lines});
                   12820:         if ($version eq $release) {
1.1172.2.17  raeburn  12821:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  12822:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  12823:                 if ($file =~ m{^/etc/httpd/conf}) {
                   12824:                     if ($webconfdir eq '/etc/apache2') {
                   12825:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   12826:                     }
                   12827:                 }
1.1172.2.34  raeburn  12828:                 $chksum{$file} = $shasum;
                   12829:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  12830:             }
                   12831:             if (ref($hashref) eq 'HASH') {
                   12832:                 %{$hashref} = (
                   12833:                                 sums     => \%chksum,
                   12834:                                 versions => \%revnum,
                   12835:                               );
                   12836:             }
                   12837:         }
                   12838:     }
1.869     albertel 12839:     return;
1.852     albertel 12840: }
1.1172.2.17  raeburn  12841: 
                   12842: sub fetch_dns_checksums {
                   12843:     my %checksums;
1.1172.2.34  raeburn  12844:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  12845:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  12846:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12847:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  12848:              \%checksums);
                   12849:     return \%checksums;
                   12850: }
                   12851: 
1.327     albertel 12852: # ------------------------------------------------------------ Read domain file
                   12853: {
1.852     albertel 12854:     my $loaded;
1.846     albertel 12855:     my %domain;
                   12856: 
1.852     albertel 12857:     sub parse_domain_tab {
                   12858: 	my ($lines) = @_;
                   12859: 	foreach my $line (@$lines) {
                   12860: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      12861: 
1.846     albertel 12862: 	    chomp($line);
1.852     albertel 12863: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 12864: 	    my %this_domain;
                   12865: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   12866: 			       'lang_def', 'city', 'longi', 'lati',
                   12867: 			       'primary') {
                   12868: 		$this_domain{$field} = shift(@elements);
                   12869: 	    }
                   12870: 	    $domain{$name} = \%this_domain;
1.852     albertel 12871: 	}
                   12872:     }
1.864     albertel 12873: 
                   12874:     sub reset_domain_info {
                   12875: 	undef($loaded);
                   12876: 	undef(%domain);
                   12877:     }
                   12878: 
1.852     albertel 12879:     sub load_domain_tab {
1.1172.2.70  raeburn  12880: 	my ($ignore_cache,$nocache) = @_;
                   12881: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 12882: 	my $fh;
1.1172.2.93.4  7(raebur 12883:7): 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 12884: 	    my @lines = <$fh>;
                   12885: 	    &parse_domain_tab(\@lines);
1.448     albertel 12886: 	}
1.852     albertel 12887: 	close($fh);
                   12888: 	$loaded = 1;
1.327     albertel 12889:     }
1.846     albertel 12890: 
                   12891:     sub domain {
1.852     albertel 12892: 	&load_domain_tab() if (!$loaded);
                   12893: 
1.846     albertel 12894: 	my ($name,$what) = @_;
                   12895: 	return if ( !exists($domain{$name}) );
                   12896: 
                   12897: 	if (!$what) {
                   12898: 	    return $domain{$name}{'description'};
                   12899: 	}
                   12900: 	return $domain{$name}{$what};
                   12901:     }
1.974     raeburn  12902: 
                   12903:     sub domain_info {
                   12904:         &load_domain_tab() if (!$loaded);
                   12905:         return %domain;
                   12906:     }
                   12907: 
1.327     albertel 12908: }
                   12909: 
                   12910: 
1.1       albertel 12911: # ------------------------------------------------------------- Read hosts file
                   12912: {
1.838     albertel 12913:     my %hostname;
1.844     albertel 12914:     my %hostdom;
1.845     albertel 12915:     my %libserv;
1.852     albertel 12916:     my $loaded;
1.888     albertel 12917:     my %name_to_host;
1.1074    raeburn  12918:     my %internetdom;
1.1107    raeburn  12919:     my %LC_dns_serv;
1.852     albertel 12920: 
                   12921:     sub parse_hosts_tab {
                   12922: 	my ($file) = @_;
                   12923: 	foreach my $configline (@$file) {
                   12924: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  12925:             chomp($configline);
                   12926: 	    if ($configline =~ /^\^/) {
                   12927:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   12928:                     $LC_dns_serv{$1} = 1;
                   12929:                 }
                   12930:                 next;
                   12931:             }
1.1074    raeburn  12932: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 12933: 	    $name=~s/\s//g;
                   12934: 	    if ($id && $domain && $role && $name) {
1.1172.2.93.4  3(raebur 12935:7):                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   12936:7):                     my $curr = $hostname{$id};
                   12937:7):                     my $skip;
                   12938:7):                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   12939:7):                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   12940:7):                             $skip = 1;
                   12941:7):                         } else {
                   12942:7):                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   12943:7):                         }
                   12944:7):                     }
                   12945:7):                     unless ($skip) {
                   12946:7):                         push(@{$name_to_host{$name}},$id);
                   12947:7):                     }
                   12948:7):                 } else {
                   12949:7):                     push(@{$name_to_host{$name}},$id);
                   12950:7):                 }
1.852     albertel 12951: 		$hostname{$id}=$name;
                   12952: 		$hostdom{$id}=$domain;
                   12953: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  12954:                 if (defined($protocol)) {
                   12955:                     if ($protocol eq 'https') {
                   12956:                         $protocol{$id} = $protocol;
                   12957:                     } else {
                   12958:                         $protocol{$id} = 'http'; 
                   12959:                     }
1.968     raeburn  12960:                 } else {
1.969     raeburn  12961:                     $protocol{$id} = 'http';
1.968     raeburn  12962:                 }
1.1074    raeburn  12963:                 if (defined($intdom)) {
                   12964:                     $internetdom{$id} = $intdom;
                   12965:                 }
1.852     albertel 12966: 	    }
                   12967: 	}
                   12968:     }
1.864     albertel 12969:     
                   12970:     sub reset_hosts_info {
1.897     albertel 12971: 	&purge_remembered();
1.864     albertel 12972: 	&reset_domain_info();
                   12973: 	&reset_hosts_ip_info();
1.892     albertel 12974: 	undef(%name_to_host);
1.864     albertel 12975: 	undef(%hostname);
                   12976: 	undef(%hostdom);
                   12977: 	undef(%libserv);
                   12978: 	undef($loaded);
                   12979:     }
1.1       albertel 12980: 
1.852     albertel 12981:     sub load_hosts_tab {
1.1172.2.70  raeburn  12982: 	my ($ignore_cache,$nocache) = @_;
                   12983: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.93.4  7(raebur 12984:7): 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 12985: 	my @config = <$config>;
                   12986: 	&parse_hosts_tab(\@config);
                   12987: 	close($config);
                   12988: 	$loaded=1;
1.1       albertel 12989:     }
1.852     albertel 12990: 
1.838     albertel 12991:     sub hostname {
1.852     albertel 12992: 	&load_hosts_tab() if (!$loaded);
                   12993: 
1.838     albertel 12994: 	my ($lonid) = @_;
                   12995: 	return $hostname{$lonid};
                   12996:     }
1.845     albertel 12997: 
1.838     albertel 12998:     sub all_hostnames {
1.852     albertel 12999: 	&load_hosts_tab() if (!$loaded);
                   13000: 
1.838     albertel 13001: 	return %hostname;
                   13002:     }
1.845     albertel 13003: 
1.888     albertel 13004:     sub all_names {
1.1172.2.70  raeburn  13005:         my ($ignore_cache,$nocache) = @_;
                   13006: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13007: 
                   13008: 	return %name_to_host;
                   13009:     }
                   13010: 
1.974     raeburn  13011:     sub all_host_domain {
                   13012:         &load_hosts_tab() if (!$loaded);
                   13013:         return %hostdom;
                   13014:     }
                   13015: 
1.845     albertel 13016:     sub is_library {
1.852     albertel 13017: 	&load_hosts_tab() if (!$loaded);
                   13018: 
1.845     albertel 13019: 	return exists($libserv{$_[0]});
                   13020:     }
                   13021: 
                   13022:     sub all_library {
1.852     albertel 13023: 	&load_hosts_tab() if (!$loaded);
                   13024: 
1.845     albertel 13025: 	return %libserv;
                   13026:     }
                   13027: 
1.1062    droeschl 13028:     sub unique_library {
                   13029: 	#2x reverse removes all hostnames that appear more than once
                   13030:         my %unique = reverse &all_library();
                   13031:         return reverse %unique;
                   13032:     }
                   13033: 
1.841     albertel 13034:     sub get_servers {
1.852     albertel 13035: 	&load_hosts_tab() if (!$loaded);
                   13036: 
1.841     albertel 13037: 	my ($domain,$type) = @_;
                   13038: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13039: 	                                          : %hostname;
                   13040: 	my %result;
1.842     albertel 13041: 	if (ref($domain) eq 'ARRAY') {
                   13042: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13043: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13044: 		    $result{$host} = $hostname;
                   13045: 		}
                   13046: 	    }
                   13047: 	} else {
                   13048: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13049: 		if ($hostdom{$host} eq $domain) {
                   13050: 		    $result{$host} = $hostname;
                   13051: 		}
1.841     albertel 13052: 	    }
                   13053: 	}
                   13054: 	return %result;
                   13055:     }
1.845     albertel 13056: 
1.1062    droeschl 13057:     sub get_unique_servers {
                   13058:         my %unique = reverse &get_servers(@_);
                   13059: 	return reverse %unique;
                   13060:     }
                   13061: 
1.844     albertel 13062:     sub host_domain {
1.852     albertel 13063: 	&load_hosts_tab() if (!$loaded);
                   13064: 
1.844     albertel 13065: 	my ($lonid) = @_;
                   13066: 	return $hostdom{$lonid};
                   13067:     }
                   13068: 
1.841     albertel 13069:     sub all_domains {
1.852     albertel 13070: 	&load_hosts_tab() if (!$loaded);
                   13071: 
1.841     albertel 13072: 	my %seen;
                   13073: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13074: 	return @uniq;
                   13075:     }
1.1074    raeburn  13076: 
                   13077:     sub internet_dom {
                   13078:         &load_hosts_tab() if (!$loaded);
                   13079: 
                   13080:         my ($lonid) = @_;
                   13081:         return $internetdom{$lonid};
                   13082:     }
1.1107    raeburn  13083: 
                   13084:     sub is_LC_dns {
                   13085:         &load_hosts_tab() if (!$loaded);
                   13086: 
                   13087:         my ($hostname) = @_;
                   13088:         return exists($LC_dns_serv{$hostname});
                   13089:     }
                   13090: 
1.1       albertel 13091: }
                   13092: 
1.847     albertel 13093: { 
                   13094:     my %iphost;
1.856     albertel 13095:     my %name_to_ip;
                   13096:     my %lonid_to_ip;
1.869     albertel 13097: 
1.847     albertel 13098:     sub get_hosts_from_ip {
                   13099: 	my ($ip) = @_;
                   13100: 	my %iphosts = &get_iphost();
                   13101: 	if (ref($iphosts{$ip})) {
                   13102: 	    return @{$iphosts{$ip}};
                   13103: 	}
                   13104: 	return;
1.839     albertel 13105:     }
1.864     albertel 13106:     
                   13107:     sub reset_hosts_ip_info {
                   13108: 	undef(%iphost);
                   13109: 	undef(%name_to_ip);
                   13110: 	undef(%lonid_to_ip);
                   13111:     }
1.856     albertel 13112: 
                   13113:     sub get_host_ip {
                   13114: 	my ($lonid) = @_;
                   13115: 	if (exists($lonid_to_ip{$lonid})) {
                   13116: 	    return $lonid_to_ip{$lonid};
                   13117: 	}
                   13118: 	my $name=&hostname($lonid);
                   13119:    	my $ip = gethostbyname($name);
                   13120: 	return if (!$ip || length($ip) ne 4);
                   13121: 	$ip=inet_ntoa($ip);
                   13122: 	$name_to_ip{$name}   = $ip;
                   13123: 	$lonid_to_ip{$lonid} = $ip;
                   13124: 	return $ip;
                   13125:     }
1.847     albertel 13126:     
                   13127:     sub get_iphost {
1.1172.2.70  raeburn  13128: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13129: 
1.869     albertel 13130: 	if (!$ignore_cache) {
                   13131: 	    if (%iphost) {
                   13132: 		return %iphost;
                   13133: 	    }
                   13134: 	    my ($ip_info,$cached)=
                   13135: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13136: 	    if ($cached) {
                   13137: 		%iphost      = %{$ip_info->[0]};
                   13138: 		%name_to_ip  = %{$ip_info->[1]};
                   13139: 		%lonid_to_ip = %{$ip_info->[2]};
                   13140: 		return %iphost;
                   13141: 	    }
                   13142: 	}
1.894     albertel 13143: 
                   13144: 	# get yesterday's info for fallback
                   13145: 	my %old_name_to_ip;
                   13146: 	my ($ip_info,$cached)=
                   13147: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13148: 	if ($cached) {
                   13149: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13150: 	}
                   13151: 
1.1172.2.70  raeburn  13152: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13153: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13154: 	    my $ip;
                   13155: 	    if (!exists($name_to_ip{$name})) {
                   13156: 		$ip = gethostbyname($name);
                   13157: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13158: 		    if (defined($old_name_to_ip{$name})) {
                   13159: 			$ip = $old_name_to_ip{$name};
                   13160: 			&logthis("Can't find $name defaulting to old $ip");
                   13161: 		    } else {
                   13162: 			&logthis("Name $name no IP found");
                   13163: 			next;
                   13164: 		    }
                   13165: 		} else {
                   13166: 		    $ip=inet_ntoa($ip);
1.847     albertel 13167: 		}
                   13168: 		$name_to_ip{$name} = $ip;
                   13169: 	    } else {
                   13170: 		$ip = $name_to_ip{$name};
1.653     albertel 13171: 	    }
1.888     albertel 13172: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13173: 		$lonid_to_ip{$id} = $ip;
                   13174: 	    }
                   13175: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13176: 	}
1.1172.2.70  raeburn  13177:         unless ($nocache) {
                   13178: 	    &do_cache_new('iphost','iphost',
                   13179: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   13180: 		          48*60*60);
                   13181:         }
1.869     albertel 13182: 
1.847     albertel 13183: 	return %iphost;
1.598     albertel 13184:     }
                   13185: 
1.992     raeburn  13186:     #
                   13187:     #  Given a DNS returns the loncapa host name for that DNS 
                   13188:     # 
                   13189:     sub host_from_dns {
                   13190:         my ($dns) = @_;
                   13191:         my @hosts;
                   13192:         my $ip;
                   13193: 
1.993     raeburn  13194:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  13195:             $ip = $name_to_ip{$dns};
                   13196:         }
                   13197:         if (!$ip) {
                   13198:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   13199:             if (length($ip) == 4) { 
                   13200: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   13201:             }
                   13202:         }
                   13203:         if ($ip) {
                   13204: 	    @hosts = get_hosts_from_ip($ip);
                   13205: 	    return $hosts[0];
                   13206:         }
                   13207:         return undef;
1.986     foxr     13208:     }
1.992     raeburn  13209: 
1.1074    raeburn  13210:     sub get_internet_names {
                   13211:         my ($lonid) = @_;
                   13212:         return if ($lonid eq '');
                   13213:         my ($idnref,$cached)=
                   13214:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   13215:         if ($cached) {
                   13216:             return $idnref;
                   13217:         }
                   13218:         my $ip = &get_host_ip($lonid);
                   13219:         my @hosts = &get_hosts_from_ip($ip);
                   13220:         my %iphost = &get_iphost();
                   13221:         my (@idns,%seen);
                   13222:         foreach my $id (@hosts) {
                   13223:             my $dom = &host_domain($id);
                   13224:             my $prim_id = &domain($dom,'primary');
                   13225:             my $prim_ip = &get_host_ip($prim_id);
                   13226:             next if ($seen{$prim_ip});
                   13227:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   13228:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   13229:                     my $intdom = &internet_dom($id);
                   13230:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   13231:                         push(@idns,$intdom);
                   13232:                     }
                   13233:                 }
                   13234:             }
                   13235:             $seen{$prim_ip} = 1;
                   13236:         }
1.1172.2.23  raeburn  13237:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  13238:     }
                   13239: 
1.986     foxr     13240: }
                   13241: 
1.1079    raeburn  13242: sub all_loncaparevs {
1.1172.2.39  raeburn  13243:     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  13244: }
                   13245: 
1.1172.2.27  raeburn  13246: # ------------------------------------------------------- Read loncaparev table
                   13247: {
                   13248:     sub load_loncaparevs {
                   13249:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.93.4  7(raebur 13250:7):             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  13251:                 while (my $configline=<$config>) {
                   13252:                     chomp($configline);
                   13253:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   13254:                     $loncaparevs{$hostid}=$loncaparev;
                   13255:                 }
                   13256:                 close($config);
                   13257:             }
                   13258:         }
                   13259:     }
                   13260: }
                   13261: 
                   13262: # ----------------------------------------------------- Read serverhostID table
                   13263: {
                   13264:     sub load_serverhomeIDs {
                   13265:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.93.4  7(raebur 13266:7):             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  13267:                 while (my $configline=<$config>) {
                   13268:                     chomp($configline);
                   13269:                     my ($name,$id)=split(/:/,$configline);
                   13270:                     $serverhomeIDs{$name}=$id;
                   13271:                 }
                   13272:                 close($config);
                   13273:             }
                   13274:         }
                   13275:     }
                   13276: }
                   13277: 
                   13278: 
1.862     albertel 13279: BEGIN {
                   13280: 
                   13281: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   13282:     unless ($readit) {
                   13283: {
                   13284:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   13285:     %perlvar = (%perlvar,%{$configvars});
                   13286: }
                   13287: 
                   13288: 
1.1       albertel 13289: # ------------------------------------------------------ Read spare server file
                   13290: {
1.1172.2.93.4  7(raebur 13291:7):     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 13292: 
                   13293:     while (my $configline=<$config>) {
                   13294:        chomp($configline);
1.284     matthew  13295:        if ($configline) {
1.784     albertel 13296: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 13297: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 13298: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 13299:        }
                   13300:     }
1.448     albertel 13301:     close($config);
1.1       albertel 13302: }
1.11      www      13303: # ------------------------------------------------------------ Read permissions
                   13304: {
1.1172.2.93.4  7(raebur 13305:7):     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      13306: 
                   13307:     while (my $configline=<$config>) {
1.448     albertel 13308: 	chomp($configline);
                   13309: 	if ($configline) {
                   13310: 	    my ($role,$perm)=split(/ /,$configline);
                   13311: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   13312: 	}
1.11      www      13313:     }
1.448     albertel 13314:     close($config);
1.11      www      13315: }
                   13316: 
                   13317: # -------------------------------------------- Read plain texts for permissions
                   13318: {
1.1172.2.93.4  7(raebur 13319:7):     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      13320: 
                   13321:     while (my $configline=<$config>) {
1.448     albertel 13322: 	chomp($configline);
                   13323: 	if ($configline) {
1.742     raeburn  13324: 	    my ($short,@plain)=split(/:/,$configline);
                   13325:             %{$prp{$short}} = ();
                   13326: 	    if (@plain > 0) {
                   13327:                 $prp{$short}{'std'} = $plain[0];
                   13328:                 for (my $i=1; $i<@plain; $i++) {
                   13329:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   13330:                 }
                   13331:             }
1.448     albertel 13332: 	}
1.135     www      13333:     }
1.448     albertel 13334:     close($config);
1.135     www      13335: }
                   13336: 
                   13337: # ---------------------------------------------------------- Read package table
                   13338: {
1.1172.2.93.4  7(raebur 13339:7):     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      13340: 
                   13341:     while (my $configline=<$config>) {
1.483     albertel 13342: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 13343: 	chomp($configline);
                   13344: 	my ($short,$plain)=split(/:/,$configline);
                   13345: 	my ($pack,$name)=split(/\&/,$short);
                   13346: 	if ($plain ne '') {
                   13347: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   13348: 	    $packagetab{$short}=$plain; 
                   13349: 	}
1.11      www      13350:     }
1.448     albertel 13351:     close($config);
1.329     matthew  13352: }
                   13353: 
1.1172.2.27  raeburn  13354: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  13355: 
1.1172.2.27  raeburn  13356: &load_loncaparevs();
                   13357: 
                   13358: # ------------------------------------------------------- Read serverhostID table
                   13359: 
                   13360: &load_serverhomeIDs();
1.1074    raeburn  13361: 
1.1172.2.27  raeburn  13362: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  13363: {
                   13364:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   13365:     if (-e $file) {
                   13366:         my $parser = HTML::LCParser->new($file);
                   13367:         while (my $token = $parser->get_token()) {
                   13368:             if ($token->[0] eq 'S') {
                   13369:                 my $item = $token->[1];
                   13370:                 my $name = $token->[2]{'name'};
                   13371:                 my $value = $token->[2]{'value'};
                   13372:                 if ($item ne '' && $name ne '' && $value ne '') {
                   13373:                     my $release = $parser->get_text();
                   13374:                     $release =~ s/(^\s*|\s*$ )//gx;
                   13375:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   13376:                 }
                   13377:             }
                   13378:         }
                   13379:     }
1.1073    raeburn  13380: }
                   13381: 
1.1138    raeburn  13382: # ---------------------------------------------------------- Read managers table
                   13383: {
                   13384:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.93.4  7(raebur 13385:7):         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  13386:             while (my $configline=<$config>) {
                   13387:                 chomp($configline);
                   13388:                 next if ($configline =~ /^\#/);
                   13389:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   13390:                     $managerstab{$configline} = 1;
                   13391:                 }
                   13392:             }
                   13393:             close($config);
                   13394:         }
                   13395:     }
                   13396: }
                   13397: 
1.329     matthew  13398: # ------------- set up temporary directory
                   13399: {
1.1117    foxr     13400:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  13401: 
1.11      www      13402: }
                   13403: 
1.794     albertel 13404: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   13405: 				'compress_threshold'=> 20_000,
                   13406:  			        });
1.185     www      13407: 
1.281     www      13408: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      13409: $dumpcount=0;
1.958     www      13410: $locknum=0;
1.22      www      13411: 
1.163     harris41 13412: &logtouch();
1.672     albertel 13413: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      13414: $readit=1;
1.564     albertel 13415:     {
                   13416: 	use integer;
                   13417: 	my $test=(2**32)+1;
1.568     albertel 13418: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 13419: 	&logthis(" Detected 64bit platform ($_64bit)");
                   13420:     }
1.195     www      13421: }
1.1       albertel 13422: }
1.179     www      13423: 
1.1       albertel 13424: 1;
1.191     harris41 13425: __END__
                   13426: 
1.243     albertel 13427: =pod
                   13428: 
1.191     harris41 13429: =head1 NAME
                   13430: 
1.243     albertel 13431: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 13432: 
                   13433: =head1 SYNOPSIS
                   13434: 
1.243     albertel 13435: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 13436: 
                   13437:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   13438: 
1.243     albertel 13439: Common parameters:
                   13440: 
                   13441: =over 4
                   13442: 
                   13443: =item *
                   13444: 
                   13445: $uname : an internal username (if $cname expecting a course Id specifically)
                   13446: 
                   13447: =item *
                   13448: 
                   13449: $udom : a domain (if $cdom expecting a course's domain specifically)
                   13450: 
                   13451: =item *
                   13452: 
                   13453: $symb : a resource instance identifier
                   13454: 
                   13455: =item *
                   13456: 
                   13457: $namespace : the name of a .db file that contains the data needed or
                   13458: being set.
                   13459: 
                   13460: =back
                   13461: 
1.394     bowersj2 13462: =head1 OVERVIEW
1.191     harris41 13463: 
1.394     bowersj2 13464: lonnet provides subroutines which interact with the
                   13465: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   13466: about classes, users, and resources.
1.243     albertel 13467: 
                   13468: For many of these objects you can also use this to store data about
                   13469: them or modify them in various ways.
1.191     harris41 13470: 
1.394     bowersj2 13471: =head2 Symbs
1.191     harris41 13472: 
1.394     bowersj2 13473: To identify a specific instance of a resource, LON-CAPA uses symbols
                   13474: or "symbs"X<symb>. These identifiers are built from the URL of the
                   13475: map, the resource number of the resource in the map, and the URL of
                   13476: the resource itself. The latter is somewhat redundant, but might help
                   13477: if maps change.
                   13478: 
                   13479: An example is
                   13480: 
                   13481:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   13482: 
                   13483: The respective map entry is
                   13484: 
                   13485:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   13486:   title="Problem 2">
                   13487:  </resource>
                   13488: 
                   13489: Symbs are used by the random number generator, as well as to store and
                   13490: restore data specific to a certain instance of for example a problem.
                   13491: 
                   13492: =head2 Storing And Retrieving Data
                   13493: 
                   13494: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   13495: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   13496: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   13497: is is the non-critical message twin of cstore. These functions are for
                   13498: handlers to store a perl hash to a user's permanent data space in an
                   13499: easy manner, and to retrieve it again on another call. It is expected
                   13500: that a handler would use this once at the beginning to retrieve data,
                   13501: and then again once at the end to send only the new data back.
                   13502: 
                   13503: The data is stored in the user's data directory on the user's
                   13504: homeserver under the ID of the course.
                   13505: 
                   13506: The hash that is returned by restore will have all of the previous
                   13507: value for all of the elements of the hash.
                   13508: 
                   13509: Example:
                   13510: 
                   13511:  #creating a hash
                   13512:  my %hash;
                   13513:  $hash{'foo'}='bar';
                   13514: 
                   13515:  #storing it
                   13516:  &Apache::lonnet::cstore(\%hash);
                   13517: 
                   13518:  #changing a value
                   13519:  $hash{'foo'}='notbar';
                   13520: 
                   13521:  #adding a new value
                   13522:  $hash{'bar'}='foo';
                   13523:  &Apache::lonnet::cstore(\%hash);
                   13524: 
                   13525:  #retrieving the hash
                   13526:  my %history=&Apache::lonnet::restore();
                   13527: 
                   13528:  #print the hash
                   13529:  foreach my $key (sort(keys(%history))) {
                   13530:    print("\%history{$key} = $history{$key}");
                   13531:  }
                   13532: 
                   13533: Will print out:
1.191     harris41 13534: 
1.394     bowersj2 13535:  %history{1:foo} = bar
                   13536:  %history{1:keys} = foo:timestamp
                   13537:  %history{1:timestamp} = 990455579
                   13538:  %history{2:bar} = foo
                   13539:  %history{2:foo} = notbar
                   13540:  %history{2:keys} = foo:bar:timestamp
                   13541:  %history{2:timestamp} = 990455580
                   13542:  %history{bar} = foo
                   13543:  %history{foo} = notbar
                   13544:  %history{timestamp} = 990455580
                   13545:  %history{version} = 2
                   13546: 
                   13547: Note that the special hash entries C<keys>, C<version> and
                   13548: C<timestamp> were added to the hash. C<version> will be equal to the
                   13549: total number of versions of the data that have been stored. The
                   13550: C<timestamp> attribute will be the UNIX time the hash was
                   13551: stored. C<keys> is available in every historical section to list which
                   13552: keys were added or changed at a specific historical revision of a
                   13553: hash.
                   13554: 
                   13555: B<Warning>: do not store the hash that restore returns directly. This
                   13556: will cause a mess since it will restore the historical keys as if the
                   13557: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 13558: 
1.394     bowersj2 13559: Calling convention:
1.191     harris41 13560: 
1.1172.2.27  raeburn  13561:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  13562:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 13563: 
1.394     bowersj2 13564: For more detailed information, see lonnet specific documentation.
1.191     harris41 13565: 
1.394     bowersj2 13566: =head1 RETURN MESSAGES
1.191     harris41 13567: 
1.394     bowersj2 13568: =over 4
1.191     harris41 13569: 
1.394     bowersj2 13570: =item * B<con_lost>: unable to contact remote host
1.191     harris41 13571: 
1.394     bowersj2 13572: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   13573: when the connection is brought back up
1.191     harris41 13574: 
1.394     bowersj2 13575: =item * B<con_failed>: unable to contact remote host and unable to save message
                   13576: for later delivery
1.191     harris41 13577: 
1.967     bisitz   13578: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 13579: 
1.394     bowersj2 13580: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 13581: that was requested
1.191     harris41 13582: 
1.243     albertel 13583: =back
1.191     harris41 13584: 
1.243     albertel 13585: =head1 PUBLIC SUBROUTINES
1.191     harris41 13586: 
1.243     albertel 13587: =head2 Session Environment Functions
1.191     harris41 13588: 
1.243     albertel 13589: =over 4
1.191     harris41 13590: 
1.394     bowersj2 13591: =item * 
                   13592: X<appenv()>
1.949     raeburn  13593: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 13594: the user envirnoment file, and will be restored for each access this
1.620     albertel 13595: user makes during this session, also modifies the %env for the current
1.949     raeburn  13596: process. Optional rolesarrayref - if defined contains a reference to an array
                   13597: of roles which are exempt from the restriction on modifying user.role entries 
                   13598: in the user's environment.db and in %env.    
1.191     harris41 13599: 
                   13600: =item *
1.394     bowersj2 13601: X<delenv()>
1.987     raeburn  13602: B<delenv($delthis,$regexp)>: removes all items from the session
                   13603: environment file that begin with $delthis. If the 
                   13604: optional second arg - $regexp - is true, $delthis is treated as a 
                   13605: regular expression, otherwise \Q$delthis\E is used. 
                   13606: The values are also deleted from the current processes %env.
1.191     harris41 13607: 
1.795     albertel 13608: =item * get_env_multiple($name) 
                   13609: 
                   13610: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   13611: values may be defined and end up as an array ref.
                   13612: 
                   13613: returns an array of values
                   13614: 
1.243     albertel 13615: =back
                   13616: 
                   13617: =head2 User Information
1.191     harris41 13618: 
1.243     albertel 13619: =over 4
1.191     harris41 13620: 
                   13621: =item *
1.394     bowersj2 13622: X<queryauthenticate()>
                   13623: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 13624: authentication scheme
                   13625: 
                   13626: =item *
1.394     bowersj2 13627: X<authenticate()>
1.1073    raeburn  13628: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 13629: authenticate user from domain's lib servers (first use the current
                   13630: one). C<$upass> should be the users password.
1.1073    raeburn  13631: $checkdefauth is optional (value is 1 if a check should be made to
                   13632:    authenticate user using default authentication method, and allow
                   13633:    account creation if username does not have account in the domain).
                   13634: $clientcancheckhost is optional (value is 1 if checking whether the
                   13635:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 13636: 
                   13637: =item *
1.394     bowersj2 13638: X<homeserver()>
                   13639: B<homeserver($uname,$udom)>: find the server which has
                   13640: the user's directory and files (there must be only one), this caches
                   13641: the answer, and also caches if there is a borken connection.
1.191     harris41 13642: 
                   13643: =item *
1.394     bowersj2 13644: X<idget()>
                   13645: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   13646: (IDs are a unique resource in a domain, there must be only 1 ID per
                   13647: username, and only 1 username per ID in a specific domain) (returns
                   13648: hash: id=>name,id=>name)
1.191     harris41 13649: 
                   13650: =item *
1.394     bowersj2 13651: X<idrget()>
                   13652: B<idrget($udom,@unames)>: find the IDs behind a list of
                   13653: usernames (returns hash: name=>id,name=>id)
1.191     harris41 13654: 
                   13655: =item *
1.394     bowersj2 13656: X<idput()>
                   13657: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 13658: 
                   13659: =item *
1.394     bowersj2 13660: X<rolesinit()>
1.1169    droeschl 13661: B<rolesinit($udom,$username)>: get user privileges.
                   13662: returns user role, first access and timer interval hashes
1.243     albertel 13663: 
                   13664: =item *
1.1171    droeschl 13665: X<privileged()>
                   13666: B<privileged($username,$domain)>: returns a true if user has a
                   13667: privileged and active role (i.e. su or dc), false otherwise.
                   13668: 
                   13669: =item *
1.551     albertel 13670: X<getsection()>
                   13671: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 13672: course $cname, return section name/number or '' for "not in course"
                   13673: and '-1' for "no section"
                   13674: 
                   13675: =item *
1.394     bowersj2 13676: X<userenvironment()>
                   13677: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 13678: passed in @what from the requested user's environment, returns a hash
                   13679: 
1.858     raeburn  13680: =item * 
                   13681: X<userlog_query()>
1.859     albertel 13682: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   13683: activity.log file. %filters defines filters applied when parsing the
                   13684: log file. These can be start or end timestamps, or the type of action
                   13685: - log to look for Login or Logout events, check for Checkin or
                   13686: Checkout, role for role selection. The response is in the form
                   13687: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   13688: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  13689: 
1.243     albertel 13690: =back
                   13691: 
                   13692: =head2 User Roles
                   13693: 
                   13694: =over 4
                   13695: 
                   13696: =item *
                   13697: 
1.1172.2.65  raeburn  13698: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   13699: returns codes for allowed actions.
                   13700: 
                   13701: The first argument is required, all others are optional.
                   13702: 
                   13703: $priv is the privilege being checked.
                   13704: $uri contains additional information about what is being checked for access (e.g.,
                   13705: URL, course ID etc.).
                   13706: $symb is the unique resource instance identifier in a course; if needed,
                   13707: but not provided, it will be retrieved via a call to &symbread().
                   13708: $role is the role for which a priv is being checked (only used if priv is evb).
                   13709: $clientip is the user's IP address (only used when checking for access to portfolio
                   13710: files).
                   13711: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   13712: prevents recursive calls to &allowed.
                   13713: 
1.243     albertel 13714:  F: full access
                   13715:  U,I,K: authentication modes (cxx only)
                   13716:  '': forbidden
                   13717:  1: user needs to choose course
                   13718:  2: browse allowed
1.766     albertel 13719:  A: passphrase authentication needed
1.1172.2.65  raeburn  13720:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 13721: 
                   13722: =item *
                   13723: 
1.1172.2.13  raeburn  13724: constructaccess($url,$setpriv) : check for access to construction space URL
                   13725: 
                   13726: See if the owner domain and name in the URL match those in the
                   13727: expected environment.  If so, return three element list
                   13728: ($ownername,$ownerdomain,$ownerhome).
                   13729: 
                   13730: Otherwise return the null string.
                   13731: 
                   13732: If second argument 'setpriv' is true, it assigns the privileges,
                   13733: and returns the same three element list, unless the owner has
                   13734: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   13735: in which case the null string is returned.
                   13736: 
                   13737: =item *
                   13738: 
1.1172.2.84  raeburn  13739: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   13740: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   13741: for system, domain, and course level. $uname and $udom are optional (current
                   13742: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 13743: 
                   13744: =item *
                   13745: 
1.988     raeburn  13746: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   13747: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  13748: $type is Course (default) or Community.
1.988     raeburn  13749: If $forcedefault evaluates to true, text returned will be default 
                   13750: text for $type. Otherwise, if this is a course, the text returned 
                   13751: will be a custom name for the role (if defined in the course's 
                   13752: environment).  If no custom name is defined the default is returned.
                   13753:    
1.832     raeburn  13754: =item *
                   13755: 
1.1172.2.23  raeburn  13756: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  13757: All arguments are optional. Returns a hash of a roles, either for
                   13758: co-author/assistant author roles for a user's Construction Space
1.906     albertel 13759: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  13760: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   13761: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   13762: For each key, value is set to colon-separated start and end times for
                   13763: the role.  If no username and domain are specified, will default to
1.934     raeburn  13764: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  13765: of role statuses (active, future or previous), roles 
                   13766: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   13767: to restrict the list of roles reported. If no array ref is 
                   13768: provided for types, will default to return only active roles.
1.834     albertel 13769: 
1.1172.2.13  raeburn  13770: =item *
                   13771: 
                   13772: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   13773: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   13774: 
                   13775: Additional optional arguments are: $type (if role checking is to be restricted
                   13776: to certain user status types -- previous (expired roles), active (currently
                   13777: available roles) or future (roles available in the future), and
                   13778: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  13779: have active Domain Coordinator role in course's domain or in additional
                   13780: domains (specified in 'Domains to check for privileged users' in course
                   13781: environment -- set via:  Course Settings -> Classlists and staff listing).
                   13782: 
                   13783: =item *
                   13784: 
                   13785: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   13786: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   13787: $possdomains and $possroles are optional array refs -- to domains to check and
                   13788: roles to check.  If $possdomains is not specified, a dump will be done of the
                   13789: users' roles.db to check for a dc or su role in any domain. This can be
                   13790: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   13791: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   13792: this then allows &privileged_by_domain() to be used, which caches the identity
                   13793: of privileged users, eliminating the need for repeated calls to &dump().
                   13794: 
                   13795: =item *
                   13796: 
                   13797: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   13798: where the outer hash keys are domains specified in the $possdomains array ref,
                   13799: next inner hash keys are privileged roles specified in the $roles array ref,
                   13800: and the innermost hash contains key = value pairs for username:domain = end:start
                   13801: for active or future "privileged" users with that role in that domain. To avoid
                   13802: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   13803: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  13804: 
1.243     albertel 13805: =back
                   13806: 
                   13807: =head2 User Modification
                   13808: 
                   13809: =over 4
                   13810: 
                   13811: =item *
                   13812: 
1.957     raeburn  13813: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 13814: user for the level given by URL.  Optional start and end dates (leave empty
                   13815: string or zero for "no date")
1.191     harris41 13816: 
                   13817: =item *
                   13818: 
1.243     albertel 13819: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   13820: change a users, password, possible return values are: ok,
                   13821: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   13822: refused
1.191     harris41 13823: 
                   13824: =item *
                   13825: 
1.243     albertel 13826: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 13827: 
                   13828: =item *
                   13829: 
1.1058    raeburn  13830: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   13831:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   13832: 
                   13833: will update user information (firstname,middlename,lastname,generation,
                   13834: permanentemail), and if forceid is true, student/employee ID also.
                   13835: A user's institutional affiliation(s) can also be updated.
                   13836: User information fields will not be overwritten with empty entries 
                   13837: unless the field is included in the $candelete array reference.
                   13838: This array is included when a single user is modified via "Manage Users",
                   13839: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 13840: 
                   13841: =item *
                   13842: 
1.286     matthew  13843: modifystudent
                   13844: 
1.957     raeburn  13845: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  13846: The course id is resolved based on the current user's environment.  
                   13847: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  13848: associated with a course.
                   13849: 
1.297     matthew  13850: This call is essentially a wrapper for lonnet::modifyuser and
                   13851: lonnet::modify_student_enrollment
1.286     matthew  13852: 
                   13853: Inputs: 
                   13854: 
                   13855: =over 4
                   13856: 
1.957     raeburn  13857: =item B<$udom> Student's loncapa domain
1.286     matthew  13858: 
1.957     raeburn  13859: =item B<$uname> Student's loncapa login name
1.286     matthew  13860: 
1.964     bisitz   13861: =item B<$uid> Student/Employee ID
1.286     matthew  13862: 
1.957     raeburn  13863: =item B<$umode> Student's authentication mode
1.286     matthew  13864: 
1.957     raeburn  13865: =item B<$upass> Student's password
1.286     matthew  13866: 
1.957     raeburn  13867: =item B<$first> Student's first name
1.286     matthew  13868: 
1.957     raeburn  13869: =item B<$middle> Student's middle name
1.286     matthew  13870: 
1.957     raeburn  13871: =item B<$last> Student's last name
1.286     matthew  13872: 
1.957     raeburn  13873: =item B<$gene> Student's generation
1.286     matthew  13874: 
1.957     raeburn  13875: =item B<$usec> Student's section in course
1.286     matthew  13876: 
                   13877: =item B<$end> Unix time of the roles expiration
                   13878: 
                   13879: =item B<$start> Unix time of the roles start date
                   13880: 
                   13881: =item B<$forceid> If defined, allow $uid to be changed
                   13882: 
                   13883: =item B<$desiredhome> server to use as home server for student
                   13884: 
1.957     raeburn  13885: =item B<$email> Student's permanent e-mail address
                   13886: 
                   13887: =item B<$type> Type of enrollment (auto or manual)
                   13888: 
1.963     raeburn  13889: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   13890: 
                   13891: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  13892: 
1.963     raeburn  13893: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  13894: 
1.963     raeburn  13895: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  13896: 
1.1172.2.19  raeburn  13897: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   13898: 
                   13899: =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  13900: 
1.286     matthew  13901: =back
1.297     matthew  13902: 
                   13903: =item *
                   13904: 
                   13905: modify_student_enrollment
                   13906: 
1.1172.2.31  raeburn  13907: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  13908: 'role.request.course' must be defined for this function to proceed.
                   13909: 
                   13910: Inputs:
                   13911: 
                   13912: =over 4
                   13913: 
1.1172.2.31  raeburn  13914: =item $udom, student's domain
1.297     matthew  13915: 
1.1172.2.31  raeburn  13916: =item $uname, student's name
1.297     matthew  13917: 
1.1172.2.31  raeburn  13918: =item $uid, student's user id
1.297     matthew  13919: 
1.1172.2.31  raeburn  13920: =item $first, student's first name
1.297     matthew  13921: 
                   13922: =item $middle
                   13923: 
                   13924: =item $last
                   13925: 
                   13926: =item $gene
                   13927: 
                   13928: =item $usec
                   13929: 
                   13930: =item $end
                   13931: 
                   13932: =item $start
                   13933: 
1.957     raeburn  13934: =item $type
                   13935: 
                   13936: =item $locktype
                   13937: 
                   13938: =item $cid
                   13939: 
                   13940: =item $selfenroll
                   13941: 
                   13942: =item $context
                   13943: 
1.1172.2.19  raeburn  13944: =item $credits, number of credits student will earn from this class
                   13945: 
1.1172.2.76  raeburn  13946: =item $instsec, institutional course section code for student
                   13947: 
1.297     matthew  13948: =back
                   13949: 
1.191     harris41 13950: 
                   13951: =item *
                   13952: 
1.243     albertel 13953: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   13954: custom role; give a custom role to a user for the level given by URL.  Specify
                   13955: name and domain of role author, and role name
1.191     harris41 13956: 
                   13957: =item *
                   13958: 
1.243     albertel 13959: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 13960: 
                   13961: =item *
                   13962: 
1.243     albertel 13963: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   13964: 
                   13965: =back
                   13966: 
                   13967: =head2 Course Infomation
                   13968: 
                   13969: =over 4
1.191     harris41 13970: 
                   13971: =item *
                   13972: 
1.1118    foxr     13973: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 13974: specified course id, including all environment settings for the
                   13975: course, the description of the course will be in the hash under the
                   13976: key 'description'
1.191     harris41 13977: 
1.1118    foxr     13978: $options is an optional parameter that if supplied is a hash reference that controls
                   13979: what how this function works.  It has the following key/values:
                   13980: 
                   13981: =over 4
                   13982: 
                   13983: =item freshen_cache
                   13984: 
                   13985: If defined, and the environment cache for the course is valid, it is 
                   13986: returned in the returned hash.
                   13987: 
                   13988: =item one_time
                   13989: 
                   13990: If defined, the last cache time is set to _now_
                   13991: 
                   13992: =item user
                   13993: 
                   13994: If defined, the supplied username is used instead of the current user.
                   13995: 
                   13996: 
                   13997: =back
                   13998: 
1.191     harris41 13999: =item *
                   14000: 
1.624     albertel 14001: resdata($name,$domain,$type,@which) : request for current parameter
                   14002: setting for a specific $type, where $type is either 'course' or 'user',
                   14003: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  14004: answers for 10 minutes.
1.243     albertel 14005: 
1.877     foxr     14006: =item *
                   14007: 
                   14008: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14009: data base, returning a hash that is keyed by the resource name and has
                   14010: values that are the resource value.  I believe that the timestamps and
                   14011: versions are also returned.
                   14012: 
1.1172.2.31  raeburn  14013: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14014: supplemental content area. This routine caches the number of files for
                   14015: 10 minutes.
                   14016: 
1.243     albertel 14017: =back
                   14018: 
                   14019: =head2 Course Modification
                   14020: 
                   14021: =over 4
1.191     harris41 14022: 
                   14023: =item *
                   14024: 
1.243     albertel 14025: writecoursepref($courseid,%prefs) : write preferences (environment
                   14026: database) for a course
1.191     harris41 14027: 
                   14028: =item *
                   14029: 
1.1011    raeburn  14030: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14031: 
                   14032: =item *
                   14033: 
1.1038    raeburn  14034: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14035: 
1.1167    droeschl 14036: =item *
                   14037: 
                   14038: is_course($courseid), is_course($cdom, $cnum)
                   14039: 
                   14040: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14041: two component version $cdom, $cnum. It checks if the specified course exists.
                   14042: 
                   14043: Returns:
                   14044:     undef if the course doesn't exist, otherwise
                   14045:     in scalar context the combined courseid.
                   14046:     in list context the two components of the course identifier, domain and 
                   14047:     courseid.    
                   14048: 
1.243     albertel 14049: =back
                   14050: 
                   14051: =head2 Resource Subroutines
                   14052: 
                   14053: =over 4
1.191     harris41 14054: 
                   14055: =item *
                   14056: 
1.243     albertel 14057: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 14058: 
                   14059: =item *
                   14060: 
1.243     albertel 14061: repcopy($filename) : subscribes to the requested file, and attempts to
                   14062: replicate from the owning library server, Might return
1.607     raeburn  14063: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   14064: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 14065: resource. Expects the local filesystem pathname
                   14066: (/home/httpd/html/res/....)
                   14067: 
                   14068: =back
                   14069: 
                   14070: =head2 Resource Information
                   14071: 
                   14072: =over 4
1.191     harris41 14073: 
                   14074: =item *
                   14075: 
1.1172.2.28  raeburn  14076: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   14077: and returns the value of a variety of different possible values,
                   14078: $varname should be a request string, and the other parameters can be
                   14079: used to specify who and what one is asking about. Ordinarily, $cid 
                   14080: does not need to be specified, as it is retrived from 
                   14081: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14082: within lonuserstate::loadmap() when initializing a course, before
                   14083: $env{'request.course.id'} has been set, so it needs to be provided
                   14084: in that one case.
1.243     albertel 14085: 
                   14086: Possible values for $varname are environment.lastname (or other item
                   14087: from the envirnment hash), user.name (or someother aspect about the
                   14088: user), resource.0.maxtries (or some other part and parameter of a
                   14089: resource)
1.204     albertel 14090: 
                   14091: =item *
                   14092: 
1.243     albertel 14093: directcondval($number) : get current value of a condition; reads from a state
                   14094: string
1.204     albertel 14095: 
                   14096: =item *
                   14097: 
1.243     albertel 14098: condval($condidx) : value of condition index based on state
1.204     albertel 14099: 
                   14100: =item *
                   14101: 
1.243     albertel 14102: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   14103: resource's metadata, $what should be either a specific key, or either
                   14104: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   14105: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   14106: 
                   14107: this function automatically caches all requests
1.191     harris41 14108: 
                   14109: =item *
                   14110: 
1.243     albertel 14111: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   14112: network of library servers; returns file handle of where SQL and regex results
                   14113: will be stored for query
1.191     harris41 14114: 
                   14115: =item *
                   14116: 
1.1172.2.66  raeburn  14117: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   14118: return symbolic list entry (all arguments optional).
                   14119: 
                   14120: Args: filename is the filename (including path) for the file for which a symb
                   14121: is required; donotrecurse, if true will prevent calls to allowed() being made
                   14122: to check access status if more than one resource was found in the bighash
                   14123: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   14124: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   14125: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   14126: cause possible symbs to be checked to determine if they are subject to content
                   14127: blocking, if so they will not be included as possible symbs; possibles is a
                   14128: ref to a hash, which, as a side effect, will be populated with all possible
                   14129: symbs (content blocking not tested).
                   14130: 
1.243     albertel 14131: returns the data handle
1.191     harris41 14132: 
                   14133: =item *
                   14134: 
1.1172.2.17  raeburn  14135: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  14136: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 14137: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  14138: on failure, user must be in a course, as it assumes the existence of
                   14139: the course initial hash, and uses $env('request.course.id'}.  The third
                   14140: arg is an optional reference to a scalar.  If this arg is passed in the
                   14141: call to symbverify, it will be set to 1 if the symb has been set to be 
                   14142: encrypted; otherwise it will be null.
1.243     albertel 14143: 
1.191     harris41 14144: =item *
                   14145: 
1.243     albertel 14146: symbclean($symb) : removes versions numbers from a symb, returns the
                   14147: cleaned symb
1.191     harris41 14148: 
                   14149: =item *
                   14150: 
1.243     albertel 14151: is_on_map($uri) : checks if the $uri is somewhere on the current
                   14152: course map, user must be in a course for it to work.
1.191     harris41 14153: 
                   14154: =item *
                   14155: 
1.243     albertel 14156: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 14157: 
                   14158: =item *
                   14159: 
1.243     albertel 14160: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   14161: a random seed, all arguments are optional, if they aren't sent it uses the
                   14162: environment to derive them. Note: if symb isn't sent and it can't get one
                   14163: from &symbread it will use the current time as its return value
1.191     harris41 14164: 
                   14165: =item *
                   14166: 
1.243     albertel 14167: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   14168: unfakeable, receipt
1.191     harris41 14169: 
                   14170: =item *
                   14171: 
1.620     albertel 14172: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 14173: 
                   14174: =item *
                   14175: 
1.243     albertel 14176: countacc($url) : count the number of accesses to a given URL
1.191     harris41 14177: 
                   14178: =item *
                   14179: 
1.243     albertel 14180: 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 14181: 
                   14182: =item *
                   14183: 
1.243     albertel 14184: 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 14185: 
                   14186: =item *
                   14187: 
1.243     albertel 14188: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 14189: 
                   14190: =item *
                   14191: 
1.243     albertel 14192: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   14193: forcing spreadsheet to reevaluate the resource scores next time.
                   14194: 
1.1172.2.13  raeburn  14195: =item *
                   14196: 
                   14197: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   14198: when viewing in course context.
                   14199: 
                   14200:  input: six args -- filename (decluttered), course number, course domain,
                   14201:                     url, symb (if registered) and group (if this is a
                   14202:                     group item -- e.g., bulletin board, group page etc.).
                   14203: 
                   14204:  output: array of five scalars --
                   14205:          $cfile -- url for file editing if editable on current server
                   14206:          $home -- homeserver of resource (i.e., for author if published,
                   14207:                                           or course if uploaded.).
                   14208:          $switchserver --  1 if server switch will be needed.
                   14209:          $forceedit -- 1 if icon/link should be to go to edit mode
                   14210:          $forceview -- 1 if icon/link should be to go to view mode
                   14211: 
                   14212: =item *
                   14213: 
                   14214: is_course_upload($file,$cnum,$cdom)
                   14215: 
                   14216: Used in course context to determine if current file was uploaded to
                   14217: the course (i.e., would be found in /userfiles/docs on the course's
                   14218: homeserver.
                   14219: 
                   14220:   input: 3 args -- filename (decluttered), course number and course domain.
                   14221:   output: boolean -- 1 if file was uploaded.
                   14222: 
1.243     albertel 14223: =back
                   14224: 
                   14225: =head2 Storing/Retreiving Data
                   14226: 
                   14227: =over 4
1.191     harris41 14228: 
                   14229: =item *
                   14230: 
1.1172.2.64  raeburn  14231: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   14232: permanently for this url; hashref needs to be given and should be a \%hashname;
                   14233: the remaining args aren't required and if they aren't passed or are '' they will
                   14234: be derived from the env (with the exception of $laststore, which is an
                   14235: optional arg used when a user's submission is stored in grading).
                   14236: $laststore is $version=$timestamp, where $version is the most recent version
                   14237: number retrieved for the corresponding $symb in the $namespace db file, and
                   14238: $timestamp is the timestamp for that transaction (UNIX time).
                   14239: $laststore is currently only passed when cstore() is called by
                   14240: structuretags::finalize_storage().
1.191     harris41 14241: 
                   14242: =item *
                   14243: 
1.1172.2.64  raeburn  14244: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   14245: but uses critical subroutine
1.191     harris41 14246: 
                   14247: =item *
                   14248: 
1.243     albertel 14249: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   14250: all args are optional
1.191     harris41 14251: 
                   14252: =item *
                   14253: 
1.717     albertel 14254: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   14255: dumps the complete (or key matching regexp) namespace into a hash
                   14256: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   14257: normally &store()ed into
                   14258: 
                   14259: $range should be either an integer '100' (give me the first 100
                   14260:                                            matching records)
                   14261:               or be  two integers sperated by a - with no spaces
                   14262:                  '30-50' (give me the 30th through the 50th matching
                   14263:                           records)
                   14264: 
                   14265: 
                   14266: =item *
                   14267: 
1.1172.2.59  raeburn  14268: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 14269: replaces a &store() version of data with a replacement set of data
                   14270: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  14271: reference. If $tolog is true, the transaction is logged in the courselog
                   14272: with an action=PUTSTORE.
1.717     albertel 14273: 
                   14274: =item *
                   14275: 
1.243     albertel 14276: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   14277: works very similar to store/cstore, but all data is stored in a
                   14278: temporary location and can be reset using tmpreset, $storehash should
                   14279: be a hash reference, returns nothing on success
1.191     harris41 14280: 
                   14281: =item *
                   14282: 
1.243     albertel 14283: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   14284: similar to restore, but all data is stored in a temporary location and
                   14285: can be reset using tmpreset. Returns a hash of values on success,
                   14286: error string otherwise.
1.191     harris41 14287: 
                   14288: =item *
                   14289: 
1.243     albertel 14290: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   14291: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 14292: 
                   14293: =item *
                   14294: 
1.243     albertel 14295: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14296: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 14297: 
                   14298: =item *
                   14299: 
1.243     albertel 14300: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   14301: namesp ($udom and $uname are optional)
1.191     harris41 14302: 
                   14303: =item *
                   14304: 
1.702     albertel 14305: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 14306: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 14307: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  14308: 
1.702     albertel 14309: $range should be either an integer '100' (give me the first 100
                   14310:                                            matching records)
                   14311:               or be  two integers sperated by a - with no spaces
                   14312:                  '30-50' (give me the 30th through the 50th matching
                   14313:                           records)
1.449     matthew  14314: =item *
                   14315: 
                   14316: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   14317: $store can be a scalar, an array reference, or if the amount to be 
                   14318: incremented is > 1, a hash reference.
                   14319: 
                   14320: ($udom and $uname are optional)
1.191     harris41 14321: 
                   14322: =item *
                   14323: 
1.243     albertel 14324: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   14325: ($udom and $uname are optional)
1.191     harris41 14326: 
                   14327: =item *
                   14328: 
1.243     albertel 14329: cput($namespace,$storehash,$udom,$uname) : critical put
                   14330: ($udom and $uname are optional)
1.191     harris41 14331: 
                   14332: =item *
                   14333: 
1.748     albertel 14334: newput($namespace,$storehash,$udom,$uname) :
                   14335: 
                   14336: Attempts to store the items in the $storehash, but only if they don't
                   14337: currently exist, if this succeeds you can be certain that you have 
                   14338: successfully created a new key value pair in the $namespace db.
                   14339: 
                   14340: 
                   14341: Args:
                   14342:  $namespace: name of database to store values to
                   14343:  $storehash: hashref to store to the db
                   14344:  $udom: (optional) domain of user containing the db
                   14345:  $uname: (optional) name of user caontaining the db
                   14346: 
                   14347: Returns:
                   14348:  'ok' -> succeeded in storing all keys of $storehash
                   14349:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   14350:                         least <key> already existed in the db (other
                   14351:                         requested keys may also already exist)
1.967     bisitz   14352:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 14353:  'con_lost' -> unable to contact request server
                   14354:  'refused' -> action was not allowed by remote machine
                   14355: 
                   14356: 
                   14357: =item *
                   14358: 
1.243     albertel 14359: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14360: reference filled in from namesp (encrypts the return communication)
                   14361: ($udom and $uname are optional)
1.191     harris41 14362: 
                   14363: =item *
                   14364: 
1.243     albertel 14365: log($udom,$name,$home,$message) : write to permanent log for user; use
                   14366: critical subroutine
                   14367: 
1.806     raeburn  14368: =item *
                   14369: 
1.860     raeburn  14370: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   14371: array reference filled in from namespace found in domain level on either
                   14372: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  14373: 
                   14374: =item *
                   14375: 
1.860     raeburn  14376: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   14377: domain level either on specified domain server ($uhome) or primary domain 
                   14378: server ($udom and $uhome are optional)
1.806     raeburn  14379: 
1.943     raeburn  14380: =item * 
                   14381: 
1.1172.2.35  raeburn  14382: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   14383: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   14384: the target domain.
                   14385: 
                   14386: May also include additional key => value pairs for the following groups:
                   14387: 
                   14388: =over
                   14389: 
                   14390: =item
                   14391: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   14392: 
                   14393: =over
                   14394: 
                   14395: =item defaultquota, authorquota
                   14396: 
                   14397: =back
                   14398: 
                   14399: =item
                   14400: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   14401: portfolio for users).
                   14402: 
                   14403: =over
                   14404: 
                   14405: =item
                   14406: aboutme, blog, webdav, portfolio
                   14407: 
                   14408: =back
                   14409: 
                   14410: =item
                   14411: requestcourses: ability to request courses, and how requests are processed.
                   14412: 
                   14413: =over
                   14414: 
                   14415: =item
1.1172.2.37  raeburn  14416: official, unofficial, community, textbook
1.1172.2.35  raeburn  14417: 
                   14418: =back
                   14419: 
                   14420: =item
                   14421: inststatus: types of institutional affiliation, and order in which they are displayed.
                   14422: 
                   14423: =over
                   14424: 
                   14425: =item
1.1172.2.44  raeburn  14426: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  14427: 
                   14428: =back
                   14429: 
                   14430: =item
                   14431: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   14432: for course's uploaded content.
                   14433: 
                   14434: =over
                   14435: 
                   14436: =item
1.1172.2.68  raeburn  14437: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   14438: communityquota, textbookquota
1.1172.2.35  raeburn  14439: 
                   14440: =back
                   14441: 
                   14442: =item
                   14443: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   14444: on your servers.
                   14445: 
                   14446: =over
                   14447: 
                   14448: =item
                   14449: remotesessions, hostedsessions
                   14450: 
                   14451: =back
                   14452: 
                   14453: =back
                   14454: 
                   14455: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   14456: utility to create a configuration.db file on a domain's primary library server
                   14457: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   14458: -- corresponding values are authentication type (internal, krb4, krb5,
                   14459: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   14460: will be available. Values are retrieved from cache (if current), unless the
                   14461: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   14462: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   14463: 
                   14464: Typical usage:
1.943     raeburn  14465: 
1.1172.2.35  raeburn  14466: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  14467: 
1.243     albertel 14468: =back
                   14469: 
                   14470: =head2 Network Status Functions
                   14471: 
                   14472: =over 4
1.191     harris41 14473: 
                   14474: =item *
                   14475: 
1.1137    raeburn  14476: dirlist() : return directory list based on URI (first arg).
                   14477: 
                   14478: Inputs: 1 required, 5 optional.
                   14479: 
                   14480: =over
                   14481: 
                   14482: =item 
                   14483: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   14484: 
                   14485: =item
                   14486: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   14487: 
                   14488: =item
                   14489: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   14490: 
                   14491: =item
                   14492: $getpropath - boolean: 1 if prepend path using &propath(). 
                   14493: 
                   14494: =item
                   14495: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   14496: 
                   14497: =item 
                   14498: $alternateRoot - path to prepend in place of path from $uri.
                   14499: 
                   14500: =back
                   14501: 
                   14502: Returns: Array of up to two items.
                   14503: 
                   14504: =over
                   14505: 
                   14506: a reference to an array of files/subdirectories
                   14507: 
                   14508: =over
                   14509: 
                   14510: Each element in the array of files/subdirectories is a & separated list of
                   14511: item name and the result of running stat on the item.  If dirlist was requested
                   14512: for a file instead of a directory, the item name will be ''. For a directory 
                   14513: listing, if the item is a metadata file, the element will end &N&M 
                   14514: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   14515: default copyright set (1).  
                   14516: 
                   14517: =back
                   14518: 
                   14519: a scalar containing error condition (if encountered).
                   14520: 
                   14521: =over
                   14522: 
                   14523: =item 
                   14524: no_host (no homeserver identified for $username:$domain).
                   14525: 
                   14526: =item 
                   14527: no_such_host (server contacted for listing not identified as valid host).
                   14528: 
                   14529: =item 
                   14530: con_lost (connection to remote server failed).
                   14531: 
                   14532: =item 
                   14533: refused (invalid $username:$domain received on lond side).
                   14534: 
                   14535: =item 
                   14536: no_such_dir (directory at specified path on lond side does not exist). 
                   14537: 
                   14538: =item 
                   14539: empty (directory at specified path on lond side is empty).
                   14540: 
                   14541: =over
                   14542: 
                   14543: This is currently not encountered because the &ls3, &ls2, 
                   14544: &ls (_handler) routines on the lond side do not filter out
                   14545: . and .. from a directory listing. 
                   14546: 
                   14547: =back
                   14548: 
                   14549: =back
                   14550: 
                   14551: =back
1.191     harris41 14552: 
                   14553: =item *
                   14554: 
1.243     albertel 14555: spareserver() : find server with least workload from spare.tab
                   14556: 
1.986     foxr     14557: 
                   14558: =item *
                   14559: 
                   14560: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   14561: if there is no corresponding loncapa host.
                   14562: 
1.243     albertel 14563: =back
                   14564: 
1.986     foxr     14565: 
1.243     albertel 14566: =head2 Apache Request
                   14567: 
                   14568: =over 4
1.191     harris41 14569: 
                   14570: =item *
                   14571: 
1.243     albertel 14572: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   14573: localhost, posts hash
                   14574: 
                   14575: =back
                   14576: 
                   14577: =head2 Data to String to Data
                   14578: 
                   14579: =over 4
1.191     harris41 14580: 
                   14581: =item *
                   14582: 
1.243     albertel 14583: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   14584: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 14585: 
                   14586: =item *
                   14587: 
1.243     albertel 14588: hashref2str($hashref) : convert a hashref into a string complete with
                   14589: escaping and '=' and '&' separators, supports elements that are
                   14590: arrayrefs and hashrefs
1.191     harris41 14591: 
                   14592: =item *
                   14593: 
1.243     albertel 14594: arrayref2str($arrayref) : convert an arrayref into a string complete
                   14595: with escaping and '&' separators, supports elements that are arrayrefs
                   14596: and hashrefs
1.191     harris41 14597: 
                   14598: =item *
                   14599: 
1.243     albertel 14600: str2hash($string) : convert string to hash using unescaping and
                   14601: splitting on '=' and '&', supports elements that are arrayrefs and
                   14602: hashrefs
1.191     harris41 14603: 
                   14604: =item *
                   14605: 
1.243     albertel 14606: str2array($string) : convert string to hash using unescaping and
                   14607: splitting on '&', supports elements that are arrayrefs and hashrefs
                   14608: 
                   14609: =back
                   14610: 
                   14611: =head2 Logging Routines
                   14612: 
                   14613: 
                   14614: These routines allow one to make log messages in the lonnet.log and
                   14615: lonnet.perm logfiles.
1.191     harris41 14616: 
1.1119    foxr     14617: =over 4
                   14618: 
1.191     harris41 14619: =item *
                   14620: 
1.243     albertel 14621: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 14622: 
                   14623: =item *
                   14624: 
1.243     albertel 14625: logthis() : append message to the normal lonnet.log file, it gets
                   14626: preiodically rolled over and deleted.
1.191     harris41 14627: 
                   14628: =item *
                   14629: 
1.243     albertel 14630: logperm() : append a permanent message to lonnet.perm.log, this log
                   14631: file never gets deleted by any automated portion of the system, only
                   14632: messages of critical importance should go in here.
                   14633: 
1.1119    foxr     14634: 
1.243     albertel 14635: =back
                   14636: 
                   14637: =head2 General File Helper Routines
                   14638: 
                   14639: =over 4
1.191     harris41 14640: 
                   14641: =item *
                   14642: 
1.481     raeburn  14643: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   14644: (a) files in /uploaded
                   14645:   (i) If a local copy of the file exists - 
                   14646:       compares modification date of local copy with last-modified date for 
                   14647:       definitive version stored on home server for course. If local copy is 
                   14648:       stale, requests a new version from the home server and stores it. 
                   14649:       If the original has been removed from the home server, then local copy 
                   14650:       is unlinked.
                   14651:   (ii) If local copy does not exist -
                   14652:       requests the file from the home server and stores it. 
                   14653:   
                   14654:   If $caller is 'uploadrep':  
                   14655:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   14656:     for request for files originally uploaded via DOCS. 
                   14657:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   14658:   
                   14659:   Otherwise:
                   14660:      This indicates a call from the content generation phase of the request.
                   14661:      -  returns the entire contents of the file or -1.
                   14662:      
                   14663: (b) files in /res
                   14664:    - returns the entire contents of a file or -1; 
                   14665:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 14666: 
1.712     albertel 14667: 
                   14668: =item *
                   14669: 
                   14670: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   14671:                   reference
                   14672: 
                   14673: returns either a stat() list of data about the file or an empty list
                   14674: if the file doesn't exist or couldn't find out about it (connection
                   14675: problems or user unknown)
                   14676: 
1.191     harris41 14677: =item *
                   14678: 
1.243     albertel 14679: filelocation($dir,$file) : returns file system location of a file
                   14680: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   14681: directory that relative $file lookups are to looked in ($dir of /a/dir
                   14682: and a file of ../bob will become /a/bob)
1.191     harris41 14683: 
                   14684: =item *
                   14685: 
                   14686: hreflocation($dir,$file) : returns file system location or a URL; same as
                   14687: filelocation except for hrefs
                   14688: 
                   14689: =item *
                   14690: 
1.1172.2.49  raeburn  14691: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   14692: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 14693: 
1.243     albertel 14694: =back
                   14695: 
1.608     albertel 14696: =head2 Usererfile file routines (/uploaded*)
                   14697: 
                   14698: =over 4
                   14699: 
                   14700: =item *
                   14701: 
                   14702: userfileupload(): main rotine for putting a file in a user or course's
                   14703:                   filespace, arguments are,
                   14704: 
1.620     albertel 14705:  formname - required - this is the name of the element in $env where the
1.608     albertel 14706:            filename, and the contents of the file to create/modifed exist
1.620     albertel 14707:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   14708:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  14709:  context - if coursedoc, store the file in the course of the active role
                   14710:              of the current user; 
                   14711:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   14712:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 14713:  subdir - required - subdirectory to put the file in under ../userfiles/
                   14714:          if undefined, it will be placed in "unknown"
                   14715: 
                   14716:  (This routine calls clean_filename() to remove any dangerous
                   14717:  characters from the filename, and then calls finuserfileupload() to
                   14718:  complete the transaction)
                   14719: 
                   14720:  returns either the url of the uploaded file (/uploaded/....) if successful
                   14721:  and /adm/notfound.html if unsuccessful
                   14722: 
                   14723: =item *
                   14724: 
                   14725: clean_filename(): routine for cleaing a filename up for storage in
                   14726:                  userfile space, argument is:
                   14727: 
                   14728:  filename - proposed filename
                   14729: 
                   14730: returns: the new clean filename
                   14731: 
                   14732: =item *
                   14733: 
1.1090    raeburn  14734: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 14735: userspace, probably shouldn't be called directly
                   14736: 
                   14737:   docuname: username or courseid of destination for the file
                   14738:   docudom: domain of user/course of destination for the file
                   14739:   formname: same as for userfileupload()
1.1090    raeburn  14740:   fname: filename (including subdirectories) for the file
                   14741:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   14742:   allfiles: reference to hash used to store objects found by parser
                   14743:   codebase: reference to hash used for codebases of java objects found by parser
                   14744:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   14745:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   14746:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   14747:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   14748:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   14749:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  14750:   mimetype: reference to scalar to accommodate mime type determined
                   14751:             from File::MMagic if $parser = parse.
1.608     albertel 14752: 
                   14753:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  14754:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   14755:  was 'overwrite').
                   14756:  
1.608     albertel 14757: 
                   14758: =item *
                   14759: 
                   14760: renameuserfile(): renames an existing userfile to a new name
                   14761: 
                   14762:   Args:
                   14763:    docuname: username or courseid of destination for the file
                   14764:    docudom: domain of user/course of destination for the file
                   14765:    old: current file name (including any subdirs under userfiles)
                   14766:    new: desired file name (including any subdirs under userfiles)
                   14767: 
                   14768: =item *
                   14769: 
                   14770: mkdiruserfile(): creates a directory is a userfiles dir
                   14771: 
                   14772:   Args:
                   14773:    docuname: username or courseid of destination for the file
                   14774:    docudom: domain of user/course of destination for the file
                   14775:    dir: dir to create (including any subdirs under userfiles)
                   14776: 
                   14777: =item *
                   14778: 
                   14779: removeuserfile(): removes a file that exists in userfiles
                   14780: 
                   14781:   Args:
                   14782:    docuname: username or courseid of destination for the file
                   14783:    docudom: domain of user/course of destination for the file
                   14784:    fname: filname to delete (including any subdirs under userfiles)
                   14785: 
                   14786: =item *
                   14787: 
                   14788: removeuploadedurl(): convience function for removeuserfile()
                   14789: 
                   14790:   Args:
                   14791:    url:  a full /uploaded/... url to delete
                   14792: 
1.747     albertel 14793: =item * 
                   14794: 
                   14795: get_portfile_permissions():
                   14796:   Args:
                   14797:     domain: domain of user or course contain the portfolio files
                   14798:     user: name of user or num of course contain the portfolio files
                   14799:   Returns:
                   14800:     hashref of a dump of the proper file_permissions.db
                   14801:    
                   14802: 
                   14803: =item * 
                   14804: 
                   14805: get_access_controls():
                   14806: 
                   14807: Args:
                   14808:   current_permissions: the hash ref returned from get_portfile_permissions()
                   14809:   group: (optional) the group you want the files associated with
                   14810:   file: (optional) the file you want access info on
                   14811: 
                   14812: Returns:
1.749     raeburn  14813:     a hash (keys are file names) of hashes containing
                   14814:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   14815:         values are XML containing access control settings (see below) 
1.747     albertel 14816: 
                   14817: Internal notes:
                   14818: 
1.749     raeburn  14819:  access controls are stored in file_permissions.db as key=value pairs.
                   14820:     key -> path to file/file_name\0uniqueID:scope_end_start
                   14821:         where scope -> public,guest,course,group,domains or users.
                   14822:               end -> UNIX time for end of access (0 -> no end date)
                   14823:               start -> UNIX time for start of access
                   14824: 
                   14825:     value -> XML description of access control
                   14826:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   14827:             <start></start>
                   14828:             <end></end>
                   14829: 
                   14830:             <password></password>  for scope type = guest
                   14831: 
                   14832:             <domain></domain>     for scope type = course or group
                   14833:             <number></number>
                   14834:             <roles id="">
                   14835:              <role></role>
                   14836:              <access></access>
                   14837:              <section></section>
                   14838:              <group></group>
                   14839:             </roles>
                   14840: 
                   14841:             <dom></dom>         for scope type = domains
                   14842: 
                   14843:             <users>             for scope type = users
                   14844:              <user>
                   14845:               <uname></uname>
                   14846:               <udom></udom>
                   14847:              </user>
                   14848:             </users>
                   14849:            </scope> 
                   14850:               
                   14851:  Access data is also aggregated for each file in an additional key=value pair:
                   14852:  key -> path to file/file_name\0accesscontrol 
                   14853:  value -> reference to hash
                   14854:           hash contains key = value pairs
                   14855:           where key = uniqueID:scope_end_start
                   14856:                 value = UNIX time record was last updated
                   14857: 
                   14858:           Used to improve speed of look-ups of access controls for each file.  
                   14859:  
                   14860:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   14861: 
1.1172.2.13  raeburn  14862: =item *
                   14863: 
1.749     raeburn  14864: modify_access_controls():
                   14865: 
                   14866: Modifies access controls for a portfolio file
                   14867: Args
                   14868: 1. file name
                   14869: 2. reference to hash of required changes,
                   14870: 3. domain
                   14871: 4. username
                   14872:   where domain,username are the domain of the portfolio owner 
                   14873:   (either a user or a course) 
                   14874: 
                   14875: Returns:
                   14876: 1. result of additions or updates ('ok' or 'error', with error message). 
                   14877: 2. result of deletions ('ok' or 'error', with error message).
                   14878: 3. reference to hash of any new or updated access controls.
                   14879: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   14880:    key = integer (inbound ID)
1.1172.2.13  raeburn  14881:    value = uniqueID
                   14882: 
                   14883: =item *
                   14884: 
                   14885: get_timebased_id():
                   14886: 
                   14887: Attempts to get a unique timestamp-based suffix for use with items added to a
                   14888: course via the Course Editor (e.g., folders, composite pages,
                   14889: group bulletin boards).
                   14890: 
                   14891: Args: (first three required; six others optional)
                   14892: 
                   14893: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   14894:    docssequence, or name of group
                   14895: 
                   14896: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   14897:    e.g., num, boardids
                   14898: 
                   14899: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   14900:    file will be named nohist_namespace.db
                   14901: 
                   14902: 4. cdom: domain of course; default is current course domain from %env
                   14903: 
                   14904: 5. cnum: course number; default is current course number from %env
                   14905: 
                   14906: 6. idtype: set to concat if an additional digit is to be appended to the
                   14907:    unix timestamp to form the suffix, if the plain timestamp is already
                   14908:    in use.  Default is to not do this, but simply increment the unix
                   14909:    timestamp by 1 until a unique key is obtained.
                   14910: 
                   14911: 7. who: holder of locking key; defaults to user:domain for user.
                   14912: 
                   14913: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   14914:    retrying); default is 3.
                   14915: 
                   14916: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   14917: 
                   14918: Returns:
                   14919: 
                   14920: 1. suffix obtained (numeric)
                   14921: 
                   14922: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   14923: 
                   14924: 3. error: contains (localized) error message if an error occurred.
                   14925: 
1.747     albertel 14926: 
1.608     albertel 14927: =back
                   14928: 
1.243     albertel 14929: =head2 HTTP Helper Routines
                   14930: 
                   14931: =over 4
                   14932: 
1.191     harris41 14933: =item *
                   14934: 
                   14935: escape() : unpack non-word characters into CGI-compatible hex codes
                   14936: 
                   14937: =item *
                   14938: 
                   14939: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   14940: 
1.243     albertel 14941: =back
                   14942: 
                   14943: =head1 PRIVATE SUBROUTINES
                   14944: 
                   14945: =head2 Underlying communication routines (Shouldn't call)
                   14946: 
                   14947: =over 4
                   14948: 
                   14949: =item *
                   14950: 
                   14951: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   14952: 
                   14953: =item *
                   14954: 
                   14955: reply() : uses subreply to send a message to remote machine, logs all failures
                   14956: 
                   14957: =item *
                   14958: 
                   14959: critical() : passes a critical message to another server; if cannot
                   14960: get through then place message in connection buffer directory and
                   14961: returns con_delayed, if incapable of saving message, returns
                   14962: con_failed
                   14963: 
                   14964: =item *
                   14965: 
                   14966: reconlonc() : tries to reconnect lonc client processes.
                   14967: 
                   14968: =back
                   14969: 
                   14970: =head2 Resource Access Logging
                   14971: 
                   14972: =over 4
                   14973: 
                   14974: =item *
                   14975: 
                   14976: flushcourselogs() : flush (save) buffer logs and access logs
                   14977: 
                   14978: =item *
                   14979: 
                   14980: courselog($what) : save message for course in hash
                   14981: 
                   14982: =item *
                   14983: 
                   14984: courseacclog($what) : save message for course using &courselog().  Perform
                   14985: special processing for specific resource types (problems, exams, quizzes, etc).
                   14986: 
1.191     harris41 14987: =item *
                   14988: 
                   14989: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   14990: as a PerlChildExitHandler
1.243     albertel 14991: 
                   14992: =back
                   14993: 
                   14994: =head2 Other
                   14995: 
                   14996: =over 4
                   14997: 
                   14998: =item *
                   14999: 
                   15000: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15001: 
                   15002: =back
                   15003: 
                   15004: =cut
1.877     foxr     15005: 

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