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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.101! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.100 2018/09/21 03:58:53 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.96  raeburn   145: 	open(my $fh,">>","$execdir/logs/lonnet.log");
1.163     harris41  146: 	close $fh;
                    147:     }
                    148:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    149:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    150: }
                    151: 
1.1       albertel  152: sub logthis {
                    153:     my $message=shift;
                    154:     my $execdir=$perlvar{'lonDaemons'};
                    155:     my $now=time;
                    156:     my $local=localtime($now);
1.1172.2.96  raeburn   157:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986     foxr      158: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    159: 	print $fh $logstring;
1.448     albertel  160: 	close($fh);
                    161:     }
1.1       albertel  162:     return 1;
                    163: }
                    164: 
                    165: sub logperm {
                    166:     my $message=shift;
                    167:     my $execdir=$perlvar{'lonDaemons'};
                    168:     my $now=time;
                    169:     my $local=localtime($now);
1.1172.2.96  raeburn   170:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448     albertel  171: 	print $fh "$now:$message:$local\n";
                    172: 	close($fh);
                    173:     }
1.1       albertel  174:     return 1;
                    175: }
                    176: 
1.850     albertel  177: sub create_connection {
1.853     albertel  178:     my ($hostname,$lonid) = @_;
1.851     albertel  179:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  180: 				     Type    => SOCK_STREAM,
                    181: 				     Timeout => 10);
                    182:     return 0 if (!$client);
1.890     albertel  183:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  184:     my $result = <$client>;
                    185:     chomp($result);
                    186:     return 1 if ($result eq 'done');
                    187:     return 0;
                    188: }
                    189: 
1.983     raeburn   190: sub get_server_timezone {
                    191:     my ($cnum,$cdom) = @_;
                    192:     my $home=&homeserver($cnum,$cdom);
                    193:     if ($home ne 'no_host') {
                    194:         my $cachetime = 24*3600;
                    195:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    196:         if (defined($cached)) {
                    197:             return $timezone;
                    198:         } else {
                    199:             my $timezone = &reply('servertimezone',$home);
                    200:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    201:         }
                    202:     }
                    203: }
1.850     albertel  204: 
1.1106    raeburn   205: sub get_server_distarch {
                    206:     my ($lonhost,$ignore_cache) = @_;
                    207:     if (defined($lonhost)) {
                    208:         if (!defined(&hostname($lonhost))) {
                    209:             return;
                    210:         }
                    211:         my $cachetime = 12*3600;
                    212:         if (!$ignore_cache) {
                    213:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    214:             if (defined($cached)) {
                    215:                 return $distarch;
                    216:             }
                    217:         }
                    218:         my $rep = &reply('serverdistarch',$lonhost);
                    219:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    220:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    221:                 $rep eq '') {
                    222:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    223:         }
                    224:     }
                    225:     return;
                    226: }
                    227: 
1.993     raeburn   228: sub get_server_loncaparev {
1.1073    raeburn   229:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   230:     if (defined($lonhost)) {
                    231:         if (!defined(&hostname($lonhost))) {
                    232:             undef($lonhost);
                    233:         }
                    234:     }
                    235:     if (!defined($lonhost)) {
                    236:         if (defined(&domain($dom,'primary'))) {
                    237:             $lonhost=&domain($dom,'primary');
                    238:             if ($lonhost eq 'no_host') {
                    239:                 undef($lonhost);
                    240:             }
                    241:         }
                    242:     }
                    243:     if (defined($lonhost)) {
1.1073    raeburn   244:         my $cachetime = 12*3600;
                    245:         if (!$ignore_cache) {
                    246:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    247:             if (defined($cached)) {
                    248:                 return $loncaparev;
                    249:             }
                    250:         }
                    251:         my ($answer,$loncaparev);
                    252:         my @ids=&current_machine_ids();
                    253:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    254:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   255:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   256:                 $loncaparev = $1;
                    257:             }
                    258:         } else {
                    259:             $answer = &reply('serverloncaparev',$lonhost);
                    260:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    261:                 if ($caller eq 'loncron') {
                    262:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   263:                     $ua->timeout(4);
1.1073    raeburn   264:                     my $protocol = $protocol{$lonhost};
                    265:                     $protocol = 'http' if ($protocol ne 'https');
                    266:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    267:                     my $request=new HTTP::Request('GET',$url);
                    268:                     my $response=$ua->request($request);
                    269:                     unless ($response->is_error()) {
                    270:                         my $content = $response->content;
1.1081    raeburn   271:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   272:                             $loncaparev = $1;
                    273:                         }
                    274:                     }
                    275:                 } else {
                    276:                     $loncaparev = $loncaparevs{$lonhost};
                    277:                 }
1.1081    raeburn   278:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   279:                 $loncaparev = $1;
                    280:             }
1.993     raeburn   281:         }
1.1073    raeburn   282:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   283:     }
                    284: }
                    285: 
1.1074    raeburn   286: sub get_server_homeID {
                    287:     my ($hostname,$ignore_cache,$caller) = @_;
                    288:     unless ($ignore_cache) {
                    289:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    290:         if (defined($cached)) {
                    291:             return $serverhomeID;
                    292:         }
                    293:     }
                    294:     my $cachetime = 12*3600;
                    295:     my $serverhomeID;
                    296:     if ($caller eq 'loncron') { 
                    297:         my @machine_ids = &machine_ids($hostname);
                    298:         foreach my $id (@machine_ids) {
                    299:             my $response = &reply('serverhomeID',$id);
                    300:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    301:                 $serverhomeID = $response;
                    302:                 last;
                    303:             }
                    304:         }
                    305:         if ($serverhomeID eq '') {
                    306:             $serverhomeID = $machine_ids[-1];
                    307:         }
                    308:     } else {
                    309:         $serverhomeID = $serverhomeIDs{$hostname};
                    310:     }
                    311:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    312: }
                    313: 
1.1121    raeburn   314: sub get_remote_globals {
                    315:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   316:     my ($result,%returnhash,%whatneeded);
                    317:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   318:         foreach my $what (sort(keys(%{$whathash}))) {
                    319:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   320:             my ($response,$cached);
1.1121    raeburn   321:             unless ($ignore_cache) {
1.1125    raeburn   322:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   323:             }
                    324:             if (defined($cached)) {
1.1125    raeburn   325:                 $returnhash{$what} = $response;
1.1121    raeburn   326:             } else {
1.1125    raeburn   327:                 $whatneeded{$what} = 1;
1.1121    raeburn   328:             }
                    329:         }
1.1125    raeburn   330:         if (keys(%whatneeded) == 0) {
                    331:             $result = 'ok';
                    332:         } else {
1.1121    raeburn   333:             my $requested = &freeze_escape(\%whatneeded);
                    334:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   335:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    336:                 ($rep eq 'unknown_cmd')) {
                    337:                 $result = $rep;
                    338:             } else {
                    339:                 $result = 'ok';
1.1121    raeburn   340:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   341:                 foreach my $item (@pairs) {
                    342:                     my ($key,$value)=split(/=/,$item,2);
                    343:                     my $what = &unescape($key);
                    344:                     my $hashid = $lonhost.'-'.$what;
                    345:                     $returnhash{$what}=&thaw_unescape($value);
                    346:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   347:                 }
                    348:             }
                    349:         }
                    350:     }
1.1125    raeburn   351:     return ($result,\%returnhash);
1.1121    raeburn   352: }
                    353: 
1.1124    raeburn   354: sub remote_devalidate_cache {
1.1172.2.35  raeburn   355:     my ($lonhost,$cachekeys) = @_;
                    356:     my $items;
                    357:     return unless (ref($cachekeys) eq 'ARRAY');
                    358:     my $cachestr = join('&',@{$cachekeys});
                    359:     return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   360: }
                    361: 
1.1       albertel  362: # -------------------------------------------------- Non-critical communication
                    363: sub subreply {
                    364:     my ($cmd,$server)=@_;
1.838     albertel  365:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      366:     #
                    367:     #  With loncnew process trimming, there's a timing hole between lonc server
                    368:     #  process exit and the master server picking up the listen on the AF_UNIX
                    369:     #  socket.  In that time interval, a lock file will exist:
                    370: 
                    371:     my $lockfile=$peerfile.".lock";
                    372:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1172.2.79  raeburn   373: 	sleep(0.1);
1.549     foxr      374:     }
                    375:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      376:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      377:     #
1.550     foxr      378:     #   We'll give the connection a few tries before abandoning it.  If
                    379:     #   connection is not possible, we'll con_lost back to the client.
                    380:     #   
                    381:     my $client;
                    382:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    383: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    384: 				      Type    => SOCK_STREAM,
                    385: 				      Timeout => 10);
1.869     albertel  386: 	if ($client) {
1.550     foxr      387: 	    last;		# Connected!
1.850     albertel  388: 	} else {
1.853     albertel  389: 	    &create_connection(&hostname($server),$server);
1.550     foxr      390: 	}
1.1172.2.79  raeburn   391:         sleep(0.1);		# Try again later if failed connection.
1.550     foxr      392:     }
                    393:     my $answer;
                    394:     if ($client) {
1.704     albertel  395: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      396: 	$answer=<$client>;
                    397: 	if (!$answer) { $answer="con_lost"; }
                    398: 	chomp($answer);
                    399:     } else {
                    400: 	$answer = 'con_lost';	# Failed connection.
                    401:     }
1.1       albertel  402:     return $answer;
                    403: }
                    404: 
                    405: sub reply {
                    406:     my ($cmd,$server)=@_;
1.838     albertel  407:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  408:     my $answer=subreply($cmd,$server);
1.65      www       409:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  410:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       411:                 " $cmd to $server returned $answer</font>");
                    412:     }
1.1       albertel  413:     return $answer;
                    414: }
                    415: 
                    416: # ----------------------------------------------------------- Send USR1 to lonc
                    417: 
                    418: sub reconlonc {
1.891     albertel  419:     my ($lonid) = @_;
                    420:     if ($lonid) {
1.1172.2.72  raeburn   421:         my $hostname = &hostname($lonid);
1.891     albertel  422: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    423: 	if ($hostname && -e $peerfile) {
                    424: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    425: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    426: 					     Type    => SOCK_STREAM,
                    427: 					     Timeout => 10);
                    428: 	    if ($client) {
                    429: 		print $client ("reset_retries\n");
                    430: 		my $answer=<$client>;
                    431: 		#reset just this one.
                    432: 	    }
                    433: 	}
                    434: 	return;
                    435:     }
                    436: 
1.836     www       437:     &logthis("Trying to reconnect lonc");
1.1       albertel  438:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1172.2.96  raeburn   439:     if (open(my $fh,"<",$loncfile)) {
1.1       albertel  440: 	my $loncpid=<$fh>;
                    441:         chomp($loncpid);
                    442:         if (kill 0 => $loncpid) {
                    443: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    444:             kill USR1 => $loncpid;
                    445:             sleep 1;
1.836     www       446:          } else {
1.12      www       447: 	    &logthis(
1.672     albertel  448:                "<font color=\"blue\">WARNING:".
1.12      www       449:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  450:         }
                    451:     } else {
1.836     www       452: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  453:     }
                    454: }
                    455: 
                    456: # ------------------------------------------------------ Critical communication
1.12      www       457: 
1.1       albertel  458: sub critical {
                    459:     my ($cmd,$server)=@_;
1.838     albertel  460:     unless (&hostname($server)) {
1.672     albertel  461:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       462:                " Critical message to unknown server ($server)</font>");
                    463:         return 'no_such_host';
                    464:     }
1.1       albertel  465:     my $answer=reply($cmd,$server);
                    466:     if ($answer eq 'con_lost') {
1.1172.2.72  raeburn   467: 	&reconlonc($server);
1.589     albertel  468: 	my $answer=reply($cmd,$server);
1.1       albertel  469:         if ($answer eq 'con_lost') {
                    470:             my $now=time;
                    471:             my $middlename=$cmd;
1.5       www       472:             $middlename=substr($middlename,0,16);
1.1       albertel  473:             $middlename=~s/\W//g;
                    474:             my $dfilename=
1.305     www       475:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    476:             $dumpcount++;
1.1       albertel  477:             {
1.448     albertel  478: 		my $dfh;
1.1172.2.96  raeburn   479: 		if (open($dfh,">",$dfilename)) {
1.448     albertel  480: 		    print $dfh "$cmd\n"; 
                    481: 		    close($dfh);
                    482: 		}
1.1       albertel  483:             }
1.1172.2.79  raeburn   484:             sleep 1;
1.1       albertel  485:             my $wcmd='';
                    486:             {
1.448     albertel  487: 		my $dfh;
1.1172.2.96  raeburn   488: 		if (open($dfh,"<",$dfilename)) {
1.448     albertel  489: 		    $wcmd=<$dfh>; 
                    490: 		    close($dfh);
                    491: 		}
1.1       albertel  492:             }
                    493:             chomp($wcmd);
1.7       www       494:             if ($wcmd eq $cmd) {
1.672     albertel  495: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       496:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  497:                 &logperm("D:$server:$cmd");
                    498: 	        return 'con_delayed';
                    499:             } else {
1.672     albertel  500:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       501:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  502:                 &logperm("F:$server:$cmd");
                    503:                 return 'con_failed';
                    504:             }
                    505:         }
                    506:     }
                    507:     return $answer;
1.405     albertel  508: }
                    509: 
1.755     albertel  510: # ------------------------------------------- check if return value is an error
                    511: 
                    512: sub error {
                    513:     my ($result) = @_;
1.756     albertel  514:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  515: 	if ($2 == 2) { return undef; }
                    516: 	return $1;
                    517:     }
                    518:     return undef;
                    519: }
                    520: 
1.783     albertel  521: sub convert_and_load_session_env {
                    522:     my ($lonidsdir,$handle)=@_;
                    523:     my @profile;
                    524:     {
1.917     albertel  525: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    526: 	if (!$opened) {
1.915     albertel  527: 	    return 0;
                    528: 	}
1.783     albertel  529: 	flock($idf,LOCK_SH);
                    530: 	@profile=<$idf>;
                    531: 	close($idf);
                    532:     }
                    533:     my %temp_env;
                    534:     foreach my $line (@profile) {
1.786     albertel  535: 	if ($line !~ m/=/) {
                    536: 	    return 0;
                    537: 	}
1.783     albertel  538: 	chomp($line);
                    539: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    540: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    541:     }
                    542:     unlink("$lonidsdir/$handle.id");
                    543:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    544: 	    0640)) {
                    545: 	%disk_env = %temp_env;
                    546: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    547: 	untie(%disk_env);
                    548:     }
1.786     albertel  549:     return 1;
1.783     albertel  550: }
                    551: 
1.374     www       552: # ------------------------------------------- Transfer profile into environment
1.780     albertel  553: my $env_loaded;
                    554: sub transfer_profile_to_env {
1.788     albertel  555:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    556:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       557: 
1.720     albertel  558:     if (!defined($lonidsdir)) {
                    559: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    560:     }
                    561:     if (!defined($handle)) {
                    562:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    563:     }
                    564: 
1.786     albertel  565:     my $convert;
                    566:     {
1.917     albertel  567:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    568: 	if (!$opened) {
1.915     albertel  569: 	    return;
                    570: 	}
1.786     albertel  571: 	flock($idf,LOCK_SH);
                    572: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    573: 		&GDBM_READER(),0640)) {
                    574: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    575: 	    untie(%disk_env);
                    576: 	} else {
                    577: 	    $convert = 1;
                    578: 	}
                    579:     }
                    580:     if ($convert) {
                    581: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    582: 	    &logthis("Failed to load session, or convert session.");
                    583: 	}
1.374     www       584:     }
1.783     albertel  585: 
1.786     albertel  586:     my %remove;
1.783     albertel  587:     while ( my $envname = each(%env) ) {
1.433     matthew   588:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    589:             if ($time < time-300) {
1.783     albertel  590:                 $remove{$key}++;
1.433     matthew   591:             }
                    592:         }
                    593:     }
1.783     albertel  594: 
1.619     albertel  595:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  596:     $env_loaded=1;
1.783     albertel  597:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   598:         &delenv($expired_key);
1.374     www       599:     }
1.1       albertel  600: }
                    601: 
1.916     albertel  602: # ---------------------------------------------------- Check for valid session 
                    603: sub check_for_valid_session {
1.1172.2.96  raeburn   604:     my ($r,$name,$userhashref,$domref) = @_;
1.916     albertel  605:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155    raeburn   606:     if ($name eq '') {
                    607:         $name = 'lonID';
                    608:     }
                    609:     my $lonid=$cookies{$name};
1.916     albertel  610:     return undef if (!$lonid);
                    611: 
                    612:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155    raeburn   613:     my $lonidsdir;
                    614:     if ($name eq 'lonDAV') {
                    615:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    616:     } else {
                    617:         $lonidsdir=$r->dir_config('lonIDsDir');
                    618:     }
1.1172.2.96  raeburn   619:     if (!-e "$lonidsdir/$handle.id") {
                    620:         if ((ref($domref)) && ($name eq 'lonID') &&
                    621:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    622:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    623:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    624:                 $$domref = $possudom;
                    625:             }
                    626:         }
                    627:         return undef;
                    628:     }
1.916     albertel  629: 
1.917     albertel  630:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    631:     return undef if (!$opened);
1.916     albertel  632: 
                    633:     flock($idf,LOCK_SH);
                    634:     my %disk_env;
                    635:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    636: 	    &GDBM_READER(),0640)) {
                    637: 	return undef;	
                    638:     }
                    639: 
                    640:     if (!defined($disk_env{'user.name'})
                    641: 	|| !defined($disk_env{'user.domain'})) {
                    642: 	return undef;
                    643:     }
1.1172.2.18  raeburn   644: 
1.1172.2.36  raeburn   645:     if (ref($userhashref) eq 'HASH') {
                    646:         $userhashref->{'name'} = $disk_env{'user.name'};
                    647:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18  raeburn   648:     }
                    649: 
1.916     albertel  650:     return $handle;
                    651: }
                    652: 
1.830     albertel  653: sub timed_flock {
                    654:     my ($file,$lock_type) = @_;
                    655:     my $failed=0;
                    656:     eval {
                    657: 	local $SIG{__DIE__}='DEFAULT';
                    658: 	local $SIG{ALRM}=sub {
                    659: 	    $failed=1;
                    660: 	    die("failed lock");
                    661: 	};
                    662: 	alarm(13);
                    663: 	flock($file,$lock_type);
                    664: 	alarm(0);
                    665:     };
                    666:     if ($failed) {
                    667: 	return undef;
                    668:     } else {
                    669: 	return 1;
                    670:     }
                    671: }
                    672: 
1.5       www       673: # ---------------------------------------------------------- Append Environment
                    674: 
                    675: sub appenv {
1.949     raeburn   676:     my ($newenv,$roles) = @_;
                    677:     if (ref($newenv) eq 'HASH') {
                    678:         foreach my $key (keys(%{$newenv})) {
                    679:             my $refused = 0;
                    680: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    681:                 $refused = 1;
                    682:                 if (ref($roles) eq 'ARRAY') {
1.1172.2.40  raeburn   683:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   684:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    685:                         $refused = 0;
                    686:                     }
                    687:                 }
                    688:             }
                    689:             if ($refused) {
                    690:                 &logthis("<font color=\"blue\">WARNING: ".
                    691:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    692:                          .'</font>');
                    693: 	        delete($newenv->{$key});
                    694:             } else {
                    695:                 $env{$key}=$newenv->{$key};
                    696:             }
                    697:         }
1.1172.2.96  raeburn   698:         my $lonids = $perlvar{'lonIDsDir'};
                    699:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
                    700:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    701:             if ($opened
                    702: 	        && &timed_flock($env_file,LOCK_EX)
                    703: 	        &&
                    704: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    705: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    706: 	        while (my ($key,$value) = each(%{$newenv})) {
                    707: 	            $disk_env{$key} = $value;
                    708: 	        }
                    709: 	        untie(%disk_env);
                    710:             }
1.35      www       711:         }
1.191     harris41  712:     }
1.56      www       713:     return 'ok';
                    714: }
                    715: # ----------------------------------------------------- Delete from Environment
                    716: 
                    717: sub delenv {
1.1104    raeburn   718:     my ($delthis,$regexp,$roles) = @_;
                    719:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    720:         my $refused = 1;
                    721:         if (ref($roles) eq 'ARRAY') {
                    722:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    723:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    724:                 $refused = 0;
                    725:             }
                    726:         }
                    727:         if ($refused) {
                    728:             &logthis("<font color=\"blue\">WARNING: ".
                    729:                      "Attempt to delete from environment ".$delthis);
                    730:             return 'error';
                    731:         }
1.56      www       732:     }
1.917     albertel  733:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    734:     if ($opened
1.915     albertel  735: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  736: 	&&
                    737: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    738: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  739: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   740: 	    if ($regexp) {
                    741:                 if ($key=~/^$delthis/) {
                    742:                     delete($env{$key});
                    743:                     delete($disk_env{$key});
                    744:                 } 
                    745:             } else {
                    746:                 if ($key=~/^\Q$delthis\E/) {
                    747: 		    delete($env{$key});
                    748: 		    delete($disk_env{$key});
                    749: 	        }
                    750:             }
1.448     albertel  751: 	}
1.783     albertel  752: 	untie(%disk_env);
1.5       www       753:     }
                    754:     return 'ok';
1.369     albertel  755: }
                    756: 
1.790     albertel  757: sub get_env_multiple {
                    758:     my ($name) = @_;
                    759:     my @values;
                    760:     if (defined($env{$name})) {
                    761:         # exists is it an array
                    762:         if (ref($env{$name})) {
                    763:             @values=@{ $env{$name} };
                    764:         } else {
                    765:             $values[0]=$env{$name};
                    766:         }
                    767:     }
                    768:     return(@values);
                    769: }
                    770: 
1.958     www       771: # ------------------------------------------------------------------- Locking
                    772: 
                    773: sub set_lock {
                    774:     my ($text)=@_;
                    775:     $locknum++;
                    776:     my $id=$$.'-'.$locknum;
                    777:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    778:              'session.lock.'.$id => $text});
                    779:     return $id;
                    780: }
                    781: 
                    782: sub get_locks {
                    783:     my $num=0;
                    784:     my %texts=();
                    785:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    786:        if ($lock=~/\w/) {
                    787:           $num++;
                    788:           $texts{$lock}=$env{'session.lock.'.$lock};
                    789:        }
                    790:    }
                    791:    return ($num,%texts);
                    792: }
                    793: 
                    794: sub remove_lock {
                    795:     my ($id)=@_;
                    796:     my $newlocks='';
                    797:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    798:        if (($lock=~/\w/) && ($lock ne $id)) {
                    799:           $newlocks.=','.$lock;
                    800:        }
                    801:     }
                    802:     &appenv({'session.locks' => $newlocks});
                    803:     &delenv('session.lock.'.$id);
                    804: }
                    805: 
                    806: sub remove_all_locks {
                    807:     my $activelocks=$env{'session.locks'};
                    808:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    809:        if ($lock=~/\w/) {
                    810:           &remove_lock($lock);
                    811:        }
                    812:     }
                    813: }
                    814: 
                    815: 
1.369     albertel  816: # ------------------------------------------ Find out current server userload
                    817: sub userload {
                    818:     my $numusers=0;
                    819:     {
                    820: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    821: 	my $filename;
                    822: 	my $curtime=time;
                    823: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  824: 	    next if ($filename eq '.' || $filename eq '..');
                    825: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  826: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  827: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  828: 	}
                    829: 	closedir(LONIDS);
                    830:     }
                    831:     my $userloadpercent=0;
                    832:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    833:     if ($maxuserload) {
1.371     albertel  834: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  835:     }
1.372     albertel  836:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  837:     return $userloadpercent;
1.283     www       838: }
                    839: 
1.1       albertel  840: # ------------------------------ Find server with least workload from spare.tab
1.11      www       841: 
1.1       albertel  842: sub spareserver {
1.1083    raeburn   843:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  844:     my $spare_server;
1.370     albertel  845:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  846:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    847:                                                      :  $userloadpercent;
1.1083    raeburn   848:     my ($uint_dom,$remotesessions);
                    849:     if (($udom ne '') && (&domain($udom) ne '')) {
                    850:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    851:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    852:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    853:         $remotesessions = $udomdefaults{'remotesessions'};
                    854:     }
1.1123    raeburn   855:     my $spareshash = &this_host_spares($udom);
                    856:     if (ref($spareshash) eq 'HASH') {
                    857:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    858:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62  raeburn   859:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    860:                                              $try_server));
1.1123    raeburn   861: 	        ($spare_server, $lowest_load) =
                    862: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    863:             }
1.1083    raeburn   864:         }
1.784     albertel  865: 
1.1123    raeburn   866:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    867: 
                    868:         if (!$found_server) {
                    869:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    870: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62  raeburn   871:                     next unless (&spare_can_host($udom,$uint_dom,
                    872:                                                  $remotesessions,$try_server));
1.1123    raeburn   873: 	            ($spare_server, $lowest_load) =
                    874: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    875:                 }
                    876: 	    }
                    877:         }
1.784     albertel  878:     }
                    879: 
                    880:     if (!$want_server_name) {
1.968     raeburn   881:         my $protocol = 'http';
                    882:         if ($protocol{$spare_server} eq 'https') {
                    883:             $protocol = $protocol{$spare_server};
                    884:         }
1.1001    raeburn   885:         if (defined($spare_server)) {
                    886:             my $hostname = &hostname($spare_server);
1.1083    raeburn   887:             if (defined($hostname)) {
1.1001    raeburn   888: 	        $spare_server = $protocol.'://'.$hostname;
                    889:             }
                    890:         }
1.784     albertel  891:     }
                    892:     return $spare_server;
                    893: }
                    894: 
                    895: sub compare_server_load {
1.1172.2.41  raeburn   896:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    897: 
                    898:     if ($required) {
                    899:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    900:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    901:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    902:         if (($major eq '' && $minor eq '') ||
                    903:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    904:             return ($spare_server,$lowest_load);
                    905:         }
                    906:     }
1.784     albertel  907: 
                    908:     my $loadans     = &reply('load',    $try_server);
                    909:     my $userloadans = &reply('userload',$try_server);
                    910: 
                    911:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   912: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  913:     }
                    914: 
                    915:     my $load;
                    916:     if ($loadans =~ /\d/) {
                    917: 	if ($userloadans =~ /\d/) {
                    918: 	    #both are numbers, pick the bigger one
                    919: 	    $load = ($loadans > $userloadans) ? $loadans 
                    920: 		                              : $userloadans;
1.411     albertel  921: 	} else {
1.784     albertel  922: 	    $load = $loadans;
1.411     albertel  923: 	}
1.784     albertel  924:     } else {
                    925: 	$load = $userloadans;
                    926:     }
                    927: 
                    928:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    929: 	$spare_server = $try_server;
                    930: 	$lowest_load  = $load;
1.370     albertel  931:     }
1.784     albertel  932:     return ($spare_server,$lowest_load);
1.202     matthew   933: }
1.914     albertel  934: 
                    935: # --------------------------- ask offload servers if user already has a session
                    936: sub find_existing_session {
                    937:     my ($udom,$uname) = @_;
1.1123    raeburn   938:     my $spareshash = &this_host_spares($udom);
                    939:     if (ref($spareshash) eq 'HASH') {
                    940:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    941:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    942:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    943:             }
                    944:         }
                    945:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    946:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    947:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    948:             }
                    949:         }
1.914     albertel  950:     }
                    951:     return;
                    952: }
                    953: 
                    954: # -------------------------------- ask if server already has a session for user
                    955: sub has_user_session {
                    956:     my ($lonid,$udom,$uname) = @_;
                    957:     my $result = &reply(join(':','userhassession',
                    958: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    959:     return 1 if ($result eq 'ok');
                    960: 
                    961:     return 0;
                    962: }
                    963: 
1.1076    raeburn   964: # --------- determine least loaded server in a user's domain which allows login
                    965: 
                    966: sub choose_server {
1.1172.2.47  raeburn   967:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn   968:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   969:     my %servers = &get_servers($udom);
1.1076    raeburn   970:     my $lowest_load = 30000;
1.1172.2.47  raeburn   971:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                    972:     if ($skiploadbal) {
                    973:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                    974:         unless (defined($cached)) {
                    975:             my $cachetime = 60*60*24;
                    976:             my %domconfig =
                    977:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                    978:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                    979:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                    980:                                            $cachetime);
                    981:             }
                    982:         }
                    983:     }
1.1076    raeburn   984:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   985:         my $loginvia;
1.1172.2.47  raeburn   986:         if ($skiploadbal) {
                    987:             if (ref($balancers) eq 'HASH') {
                    988:                 next if (exists($balancers->{$lonhost}));
                    989:             }
                    990:         }
1.1115    raeburn   991:         if ($checkloginvia) {
                    992:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   993:             if ($loginvia) {
                    994:                 my ($server,$path) = split(/:/,$loginvia);
                    995:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn   996:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn   997:                 if ($login_host eq $server) {
                    998:                     $portal_path = $path;
1.1151    raeburn   999:                     $isredirect = 1;
1.1116    raeburn  1000:                 }
                   1001:             } else {
                   1002:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1003:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1004:                 if ($login_host eq $lonhost) {
                   1005:                     $portal_path = '';
1.1151    raeburn  1006:                     $isredirect = ''; 
1.1116    raeburn  1007:                 }
                   1008:             }
                   1009:         } else {
1.1076    raeburn  1010:             ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1011:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1012:         }
                   1013:     }
                   1014:     if ($login_host ne '') {
1.1116    raeburn  1015:         $hostname = &hostname($login_host);
1.1076    raeburn  1016:     }
1.1172.2.88  raeburn  1017:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1018: }
                   1019: 
1.202     matthew  1020: # --------------------------------------------- Try to change a user's password
                   1021: 
                   1022: sub changepass {
1.799     raeburn  1023:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1024:     $currentpass = &escape($currentpass);
                   1025:     $newpass     = &escape($newpass);
1.1030    raeburn  1026:     my $lonhost = $perlvar{'lonHostID'};
                   1027:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1028: 		       $server);
                   1029:     if (! $answer) {
                   1030: 	&logthis("No reply on password change request to $server ".
                   1031: 		 "by $uname in domain $udom.");
                   1032:     } elsif ($answer =~ "^ok") {
                   1033:         &logthis("$uname in $udom successfully changed their password ".
                   1034: 		 "on $server.");
                   1035:     } elsif ($answer =~ "^pwchange_failure") {
                   1036: 	&logthis("$uname in $udom was unable to change their password ".
                   1037: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1038: 		 "or pwchange");
                   1039:     } elsif ($answer =~ "^non_authorized") {
                   1040:         &logthis("$uname in $udom did not get their password correct when ".
                   1041: 		 "attempting to change it on $server.");
                   1042:     } elsif ($answer =~ "^auth_mode_error") {
                   1043:         &logthis("$uname in $udom attempted to change their password despite ".
                   1044: 		 "not being locally or internally authenticated on $server.");
                   1045:     } elsif ($answer =~ "^unknown_user") {
                   1046:         &logthis("$uname in $udom attempted to change their password ".
                   1047: 		 "on $server but were unable to because $server is not ".
                   1048: 		 "their home server.");
                   1049:     } elsif ($answer =~ "^refused") {
                   1050: 	&logthis("$server refused to change $uname in $udom password because ".
                   1051: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1052:     } elsif ($answer =~ "invalid_client") {
                   1053:         &logthis("$server refused to change $uname in $udom password because ".
                   1054:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1055:     }
                   1056:     return $answer;
1.1       albertel 1057: }
                   1058: 
1.169     harris41 1059: # ----------------------- Try to determine user's current authentication scheme
                   1060: 
                   1061: sub queryauthenticate {
                   1062:     my ($uname,$udom)=@_;
1.456     albertel 1063:     my $uhome=&homeserver($uname,$udom);
                   1064:     if (!$uhome) {
                   1065: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1066: 	return 'no_host';
                   1067:     }
                   1068:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1069:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1070: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1071:     }
1.456     albertel 1072:     return $answer;
1.169     harris41 1073: }
                   1074: 
1.1       albertel 1075: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1076: 
1.1       albertel 1077: sub authenticate {
1.1073    raeburn  1078:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1079:     $upass=&escape($upass);
                   1080:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1081:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1082:     my $newhome;
1.836     www      1083:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1084: # Maybe the machine was offline and only re-appeared again recently?
                   1085:         &reconlonc();
                   1086: # One more
1.952     raeburn  1087: 	$uhome=&homeserver($uname,$udom,1);
                   1088:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1089:             if (defined(&domain($udom,'primary'))) {
                   1090:                 $newhome=&domain($udom,'primary');
                   1091:             }
                   1092:             if ($newhome ne '') {
                   1093:                 $uhome = $newhome;
                   1094:             }
                   1095:         }
1.836     www      1096: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1097: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1098: 	    return 'no_host';
                   1099:         }
1.1       albertel 1100:     }
1.1073    raeburn  1101:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1102:     if ($answer eq 'authorized') {
1.952     raeburn  1103:         if ($newhome) {
                   1104:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1105:             return 'no_account_on_host'; 
                   1106:         } else {
                   1107:             &logthis("User $uname at $udom authorized by $uhome");
                   1108:             return $uhome;
                   1109:         }
1.471     albertel 1110:     }
                   1111:     if ($answer eq 'non_authorized') {
                   1112: 	&logthis("User $uname at $udom rejected by $uhome");
                   1113: 	return 'no_host'; 
1.9       www      1114:     }
1.471     albertel 1115:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1116:     return 'no_host';
                   1117: }
                   1118: 
1.1073    raeburn  1119: sub can_host_session {
1.1074    raeburn  1120:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1121:     my $canhost = 1;
1.1074    raeburn  1122:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1123:     if (ref($remotesessions) eq 'HASH') {
                   1124:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1125:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1126:                 $canhost = 0;
                   1127:             } else {
                   1128:                 $canhost = 1;
                   1129:             }
                   1130:         }
                   1131:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1132:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1133:                 $canhost = 1;
                   1134:             } else {
                   1135:                 $canhost = 0;
                   1136:             }
                   1137:         }
                   1138:         if ($canhost) {
                   1139:             if ($remotesessions->{'version'} ne '') {
                   1140:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1141:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1142:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1143:                         my $major = $1;
                   1144:                         my $minor = $2;
                   1145:                         if (($major < $reqmajor ) ||
                   1146:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1147:                             $canhost = 0;
                   1148:                         }
                   1149:                     } else {
                   1150:                         $canhost = 0;
                   1151:                     }
                   1152:                 }
                   1153:             }
                   1154:         }
                   1155:     }
                   1156:     if ($canhost) {
                   1157:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1158:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1159:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1160:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1161:                 if (($uint_dom ne '') && 
                   1162:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1163:                     $canhost = 0;
                   1164:                 } else {
                   1165:                     $canhost = 1;
                   1166:                 }
                   1167:             }
                   1168:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1169:                 if (($uint_dom ne '') && 
                   1170:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1171:                     $canhost = 1;
                   1172:                 } else {
                   1173:                     $canhost = 0;
                   1174:                 }
                   1175:             }
                   1176:         }
                   1177:     }
                   1178:     return $canhost;
                   1179: }
                   1180: 
1.1083    raeburn  1181: sub spare_can_host {
                   1182:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1183:     my $canhost=1;
1.1172.2.62  raeburn  1184:     my $try_server_hostname = &hostname($try_server);
                   1185:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1186:     my $serverhomedom = &host_domain($serverhomeID);
                   1187:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1188:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1189:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1190:             $canhost = 0;
                   1191:         }
                   1192:     }
                   1193:     if (($canhost) && ($uint_dom)) {
                   1194:         my @intdoms;
                   1195:         my $internet_names = &get_internet_names($try_server);
                   1196:         if (ref($internet_names) eq 'ARRAY') {
                   1197:             @intdoms = @{$internet_names};
                   1198:         }
                   1199:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1200:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1201:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1202:                                          $remotesessions,
                   1203:                                          $defdomdefaults{'hostedsessions'});
                   1204:         }
1.1083    raeburn  1205:     }
                   1206:     return $canhost;
                   1207: }
                   1208: 
1.1123    raeburn  1209: sub this_host_spares {
                   1210:     my ($dom) = @_;
1.1126    raeburn  1211:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1212:     my @hosts = &current_machine_ids();
                   1213:     foreach my $lonhost (@hosts) {
                   1214:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1215:             $dom_in_use = $dom;
                   1216:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1217:             last;
                   1218:         }
                   1219:     }
1.1126    raeburn  1220:     if ($dom_in_use ne '') {
                   1221:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1222:     }
                   1223:     if (ref($result) ne 'HASH') {
                   1224:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1225:         $dom_in_use = &host_domain($lonhost_in_use);
                   1226:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1227:         if (ref($result) ne 'HASH') {
                   1228:             $result = \%spareid;
                   1229:         }
                   1230:     }
                   1231:     return $result;
                   1232: }
                   1233: 
                   1234: sub spares_for_offload  {
                   1235:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1236:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1237:     if (defined($cached)) {
                   1238:         return $result;
                   1239:     } else {
1.1126    raeburn  1240:         my $cachetime = 60*60*24;
                   1241:         my %domconfig =
                   1242:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1243:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1244:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1245:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1246:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1247:                 }
                   1248:             }
                   1249:         }
                   1250:     }
1.1126    raeburn  1251:     return;
1.1123    raeburn  1252: }
                   1253: 
1.1129    raeburn  1254: sub get_lonbalancer_config {
                   1255:     my ($servers) = @_;
                   1256:     my ($currbalancer,$currtargets);
                   1257:     if (ref($servers) eq 'HASH') {
                   1258:         foreach my $server (keys(%{$servers})) {
                   1259:             my %what = (
                   1260:                          spareid => 1,
                   1261:                          perlvar => 1,
                   1262:                        );
                   1263:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1264:             if ($result eq 'ok') {
                   1265:                 if (ref($returnhash) eq 'HASH') {
                   1266:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1267:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1268:                             $currbalancer = $server;
                   1269:                             $currtargets = {};
                   1270:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1271:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1272:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1273:                                 }
                   1274:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1275:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1276:                                 }
                   1277:                             }
                   1278:                             last;
                   1279:                         }
                   1280:                     }
                   1281:                 }
                   1282:             }
                   1283:         }
                   1284:     }
                   1285:     return ($currbalancer,$currtargets);
                   1286: }
                   1287: 
                   1288: sub check_loadbalancing {
1.1172.2.88  raeburn  1289:     my ($uname,$udom,$caller) = @_;
1.1172.2.12  raeburn  1290:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1291:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1292:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1293:     my @hosts = &current_machine_ids();
1.1129    raeburn  1294:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1295:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1296:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1297:     my $serverhomedom = &host_domain($lonhost);
1.1172.2.75  raeburn  1298:     my $domneedscache; 
1.1129    raeburn  1299:     my $cachetime = 60*60*24;
                   1300: 
                   1301:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1302:         $dom_in_use = $udom;
                   1303:         $homeintdom = 1;
                   1304:     } else {
                   1305:         $dom_in_use = $serverhomedom;
                   1306:     }
                   1307:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1308:     unless (defined($cached)) {
                   1309:         my %domconfig =
                   1310:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1311:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1312:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75  raeburn  1313:         } else {
                   1314:             $domneedscache = $dom_in_use;
1.1129    raeburn  1315:         }
                   1316:     }
                   1317:     if (ref($result) eq 'HASH') {
1.1172.2.12  raeburn  1318:         ($is_balancer,$currtargets,$currrules) =
                   1319:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1320:         if ($is_balancer) {
                   1321:             if (ref($currrules) eq 'HASH') {
                   1322:                 if ($homeintdom) {
                   1323:                     if ($uname ne '') {
                   1324:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1325:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1326:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1327:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1328:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1329:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1330:                             }
                   1331:                         }
                   1332:                         if ($rule_in_effect eq '') {
                   1333:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1334:                             if ($userenv{'inststatus'} ne '') {
                   1335:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1336:                                 my ($othertitle,$usertypes,$types) =
                   1337:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1338:                                 if (ref($types) eq 'ARRAY') {
                   1339:                                     foreach my $type (@{$types}) {
                   1340:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1341:                                             if (exists($currrules->{$type})) {
                   1342:                                                 $rule_in_effect = $currrules->{$type};
                   1343:                                             }
                   1344:                                         }
                   1345:                                     }
                   1346:                                 }
                   1347:                             } else {
                   1348:                                 if (exists($currrules->{'default'})) {
                   1349:                                     $rule_in_effect = $currrules->{'default'};
                   1350:                                 }
                   1351:                             }
                   1352:                         }
                   1353:                     } else {
                   1354:                         if (exists($currrules->{'default'})) {
                   1355:                             $rule_in_effect = $currrules->{'default'};
                   1356:                         }
                   1357:                     }
                   1358:                 } else {
                   1359:                     if ($currrules->{'_LC_external'} ne '') {
                   1360:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1361:                     }
                   1362:                 }
                   1363:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1364:                                                        $uname,$udom);
                   1365:             }
                   1366:         }
                   1367:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35  raeburn  1368:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1369:         unless (defined($cached)) {
                   1370:             my %domconfig =
                   1371:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1372:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75  raeburn  1373:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1374:             } else {
                   1375:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1376:             }
                   1377:         }
                   1378:         if (ref($result) eq 'HASH') {
1.1172.2.12  raeburn  1379:             ($is_balancer,$currtargets,$currrules) =
                   1380:                 &check_balancer_result($result,@hosts);
                   1381:             if ($is_balancer) {
1.1129    raeburn  1382:                 if (ref($currrules) eq 'HASH') {
                   1383:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1384:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1385:                     }
                   1386:                 }
                   1387:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1388:                                                        $uname,$udom);
                   1389:             }
                   1390:         } else {
                   1391:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1392:                 $is_balancer = 1;
                   1393:                 $offloadto = &this_host_spares($dom_in_use);
                   1394:             }
1.1172.2.75  raeburn  1395:             unless (defined($cached)) {
                   1396:                 $domneedscache = $serverhomedom;
                   1397:             }
1.1129    raeburn  1398:         }
                   1399:     } else {
                   1400:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1401:             $is_balancer = 1;
                   1402:             $offloadto = &this_host_spares($dom_in_use);
                   1403:         }
1.1172.2.75  raeburn  1404:         unless (defined($cached)) {
                   1405:             $domneedscache = $serverhomedom;
                   1406:         }
                   1407:     }
                   1408:     if ($domneedscache) {
                   1409:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1410:     }
1.1172.2.5  raeburn  1411:     if ($is_balancer) {
                   1412:         my $lowest_load = 30000;
                   1413:         if (ref($offloadto) eq 'HASH') {
                   1414:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1415:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1416:                     ($otherserver,$lowest_load) =
                   1417:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1418:                 }
1.1129    raeburn  1419:             }
1.1172.2.5  raeburn  1420:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1421: 
1.1172.2.5  raeburn  1422:             if (!$found_server) {
                   1423:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1424:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1425:                         ($otherserver,$lowest_load) =
                   1426:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1427:                     }
                   1428:                 }
                   1429:             }
                   1430:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1431:             if (@{$offloadto} == 1) {
                   1432:                 $otherserver = $offloadto->[0];
                   1433:             } elsif (@{$offloadto} > 1) {
                   1434:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1435:                     ($otherserver,$lowest_load) =
                   1436:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1437:                 }
                   1438:             }
                   1439:         }
1.1172.2.88  raeburn  1440:         unless ($caller eq 'login') {
                   1441:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1442:                 $is_balancer = 0;
                   1443:                 if ($uname ne '' && $udom ne '') {
                   1444:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1172.2.5  raeburn  1445: 
1.1172.2.88  raeburn  1446:                         &appenv({'user.loadbalexempt'     => $lonhost,
                   1447:                                  'user.loadbalcheck.time' => time});
                   1448:                     }
1.1172.2.5  raeburn  1449:                 }
1.1129    raeburn  1450:             }
                   1451:         }
                   1452:     }
                   1453:     return ($is_balancer,$otherserver);
                   1454: }
                   1455: 
1.1172.2.12  raeburn  1456: sub check_balancer_result {
                   1457:     my ($result,@hosts) = @_;
                   1458:     my ($is_balancer,$currtargets,$currrules);
                   1459:     if (ref($result) eq 'HASH') {
                   1460:         if ($result->{'lonhost'} ne '') {
                   1461:             my $currbalancer = $result->{'lonhost'};
                   1462:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1463:                 $is_balancer = 1;
                   1464:                 $currtargets = $result->{'targets'};
                   1465:                 $currrules = $result->{'rules'};
                   1466:             }
                   1467:         } else {
                   1468:             foreach my $key (keys(%{$result})) {
                   1469:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1470:                     (ref($result->{$key}) eq 'HASH')) {
                   1471:                     $is_balancer = 1;
                   1472:                     $currrules = $result->{$key}{'rules'};
                   1473:                     $currtargets = $result->{$key}{'targets'};
                   1474:                     last;
                   1475:                 }
                   1476:             }
                   1477:         }
                   1478:     }
                   1479:     return ($is_balancer,$currtargets,$currrules);
                   1480: }
                   1481: 
1.1129    raeburn  1482: sub get_loadbalancer_targets {
                   1483:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1484:     my $offloadto;
1.1172.2.4  raeburn  1485:     if ($rule_in_effect eq 'none') {
                   1486:         return [$perlvar{'lonHostID'}];
                   1487:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1488:         $offloadto = $currtargets;
                   1489:     } else {
                   1490:         if ($rule_in_effect eq 'homeserver') {
                   1491:             my $homeserver = &homeserver($uname,$udom);
                   1492:             if ($homeserver ne 'no_host') {
                   1493:                 $offloadto = [$homeserver];
                   1494:             }
                   1495:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1496:             my %domconfig =
                   1497:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1498:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1499:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1500:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1501:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1502:                     }
                   1503:                 }
                   1504:             } else {
1.1172.2.7  raeburn  1505:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1506:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1507:                 if (&hostname($remotebalancer) ne '') {
                   1508:                     $offloadto = [$remotebalancer];
                   1509:                 }
                   1510:             }
                   1511:         } elsif (&hostname($rule_in_effect) ne '') {
                   1512:             $offloadto = [$rule_in_effect];
                   1513:         }
                   1514:     }
                   1515:     return $offloadto;
                   1516: }
                   1517: 
1.1127    raeburn  1518: sub internet_dom_servers {
                   1519:     my ($dom) = @_;
                   1520:     my (%uniqservers,%servers);
                   1521:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1522:     my @machinedoms = &machine_domains($primaryserver);
                   1523:     foreach my $mdom (@machinedoms) {
                   1524:         my %currservers = %servers;
                   1525:         my %server = &get_servers($mdom);
                   1526:         %servers = (%currservers,%server);
                   1527:     }
                   1528:     my %by_hostname;
                   1529:     foreach my $id (keys(%servers)) {
                   1530:         push(@{$by_hostname{$servers{$id}}},$id);
                   1531:     }
                   1532:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1533:         if (@{$by_hostname{$hostname}} > 1) {
                   1534:             my $match = 0;
                   1535:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1536:                 if (&host_domain($id) eq $dom) {
                   1537:                     $uniqservers{$id} = $hostname;
                   1538:                     $match = 1;
                   1539:                 }
                   1540:             }
                   1541:             unless ($match) {
                   1542:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1543:             }
                   1544:         } else {
                   1545:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1546:         }
                   1547:     }
                   1548:     return %uniqservers;
                   1549: }
                   1550: 
1.1       albertel 1551: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1552: 
1.599     albertel 1553: my %homecache;
1.1       albertel 1554: sub homeserver {
1.230     stredwic 1555:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1556:     my $index="$uname:$udom";
1.426     albertel 1557: 
1.599     albertel 1558:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1559: 
                   1560:     my %servers = &get_servers($udom,'library');
                   1561:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1562:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1563: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1564: 
                   1565: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1566: 	if ($answer eq 'found') {
                   1567: 	    delete($badServerCache{$tryserver}); 
                   1568: 	    return $homecache{$index}=$tryserver;
                   1569: 	} elsif ($answer eq 'no_host') {
                   1570: 	    $badServerCache{$tryserver}=1;
                   1571: 	}
1.1       albertel 1572:     }    
                   1573:     return 'no_host';
1.70      www      1574: }
                   1575: 
                   1576: # ------------------------------------- Find the usernames behind a list of IDs
                   1577: 
                   1578: sub idget {
                   1579:     my ($udom,@ids)=@_;
                   1580:     my %returnhash=();
                   1581:     
1.841     albertel 1582:     my %servers = &get_servers($udom,'library');
                   1583:     foreach my $tryserver (keys(%servers)) {
1.1172.2.73  raeburn  1584: 	my $idlist=join('&', map { &escape($_); } @ids);
1.841     albertel 1585: 	$idlist=~tr/A-Z/a-z/; 
                   1586: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1587: 	my @answer=();
                   1588: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1589: 	    @answer=split(/\&/,$reply);
                   1590: 	}                    ;
                   1591: 	my $i;
                   1592: 	for ($i=0;$i<=$#ids;$i++) {
                   1593: 	    if ($answer[$i]) {
1.1172.2.73  raeburn  1594: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841     albertel 1595: 	    } 
                   1596: 	}
                   1597:     } 
1.70      www      1598:     return %returnhash;
                   1599: }
                   1600: 
                   1601: # ------------------------------------- Find the IDs behind a list of usernames
                   1602: 
                   1603: sub idrget {
                   1604:     my ($udom,@unames)=@_;
                   1605:     my %returnhash=();
1.800     albertel 1606:     foreach my $uname (@unames) {
                   1607:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1608:     }
1.70      www      1609:     return %returnhash;
                   1610: }
                   1611: 
                   1612: # ------------------------------- Store away a list of names and associated IDs
                   1613: 
                   1614: sub idput {
                   1615:     my ($udom,%ids)=@_;
                   1616:     my %servers=();
1.800     albertel 1617:     foreach my $uname (keys(%ids)) {
                   1618: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1619:         my $uhom=&homeserver($uname,$udom);
1.70      www      1620:         if ($uhom ne 'no_host') {
1.800     albertel 1621:             my $id=&escape($ids{$uname});
1.70      www      1622:             $id=~tr/A-Z/a-z/;
1.800     albertel 1623:             my $esc_unam=&escape($uname);
1.70      www      1624: 	    if ($servers{$uhom}) {
1.800     albertel 1625: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1626:             } else {
1.800     albertel 1627:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1628:             }
                   1629:         }
1.191     harris41 1630:     }
1.800     albertel 1631:     foreach my $server (keys(%servers)) {
                   1632:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1633:     }
1.344     www      1634: }
                   1635: 
1.1172.2.30  raeburn  1636: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1637: 
                   1638: sub iddel {
                   1639:     my ($udom,$idshashref,$uhome)=@_;
                   1640:     my %result=();
                   1641:     unless (ref($idshashref) eq 'HASH') {
                   1642:         return %result;
                   1643:     }
                   1644:     my %servers=();
                   1645:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1646:         my $uhom;
                   1647:         if ($uhome) {
                   1648:             $uhom = $uhome;
                   1649:         } else {
                   1650:             $uhom=&homeserver($uname,$udom);
                   1651:         }
                   1652:         if ($uhom ne 'no_host') {
                   1653:             if ($servers{$uhom}) {
                   1654:                 $servers{$uhom}.='&'.&escape($id);
                   1655:             } else {
                   1656:                 $servers{$uhom}=&escape($id);
                   1657:             }
                   1658:         }
                   1659:     }
                   1660:     foreach my $server (keys(%servers)) {
                   1661:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1662:     }
                   1663:     return %result;
                   1664: }
                   1665: 
1.1023    raeburn  1666: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1667: sub dump_dom {
1.1165    droeschl 1668:     my ($namespace, $udom, $regexp) = @_;
                   1669: 
                   1670:     $udom ||= $env{'user.domain'};
                   1671: 
                   1672:     return () unless $udom;
                   1673: 
                   1674:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1675: }
                   1676: 
1.1023    raeburn  1677: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1678: 
                   1679: sub get_dom {
1.860     raeburn  1680:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57  raeburn  1681:     return if ($udom eq 'public');
1.806     raeburn  1682:     my $items='';
                   1683:     foreach my $item (@$storearr) {
                   1684:         $items.=&escape($item).'&';
                   1685:     }
                   1686:     $items=~s/\&$//;
1.860     raeburn  1687:     if (!$udom) {
                   1688:         $udom=$env{'user.domain'};
1.1172.2.57  raeburn  1689:         return if ($udom eq 'public');
1.860     raeburn  1690:         if (defined(&domain($udom,'primary'))) {
                   1691:             $uhome=&domain($udom,'primary');
                   1692:         } else {
1.874     albertel 1693:             undef($uhome);
1.860     raeburn  1694:         }
                   1695:     } else {
                   1696:         if (!$uhome) {
                   1697:             if (defined(&domain($udom,'primary'))) {
                   1698:                 $uhome=&domain($udom,'primary');
                   1699:             }
                   1700:         }
                   1701:     }
                   1702:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1703:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1704:         my %returnhash;
1.875     albertel 1705:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1706:             return %returnhash;
                   1707:         }
1.806     raeburn  1708:         my @pairs=split(/\&/,$rep);
                   1709:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1710:             return @pairs;
                   1711:         }
                   1712:         my $i=0;
                   1713:         foreach my $item (@$storearr) {
                   1714:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1715:             $i++;
                   1716:         }
                   1717:         return %returnhash;
                   1718:     } else {
1.880     banghart 1719:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1720:     }
                   1721: }
                   1722: 
                   1723: # -------------------------------------------- put items in domain db files 
                   1724: 
                   1725: sub put_dom {
1.860     raeburn  1726:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1727:     if (!$udom) {
                   1728:         $udom=$env{'user.domain'};
                   1729:         if (defined(&domain($udom,'primary'))) {
                   1730:             $uhome=&domain($udom,'primary');
                   1731:         } else {
1.874     albertel 1732:             undef($uhome);
1.860     raeburn  1733:         }
                   1734:     } else {
                   1735:         if (!$uhome) {
                   1736:             if (defined(&domain($udom,'primary'))) {
                   1737:                 $uhome=&domain($udom,'primary');
                   1738:             }
                   1739:         }
                   1740:     } 
                   1741:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1742:         my $items='';
                   1743:         foreach my $item (keys(%$storehash)) {
                   1744:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1745:         }
                   1746:         $items=~s/\&$//;
                   1747:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1748:     } else {
1.860     raeburn  1749:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1750:     }
                   1751: }
                   1752: 
1.1023    raeburn  1753: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1754: sub newput_dom {
1.1023    raeburn  1755:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1756:     my $result;
                   1757:     if (!$udom) {
                   1758:         $udom=$env{'user.domain'};
                   1759:     }
1.1023    raeburn  1760:     if ($udom) {
                   1761:         my $uname = &get_domainconfiguser($udom);
                   1762:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1763:     }
                   1764:     return $result;
                   1765: }
                   1766: 
1.1023    raeburn  1767: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1768: sub del_dom {
1.1023    raeburn  1769:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1770:     if (ref($storearr) eq 'ARRAY') {
                   1771:         if (!$udom) {
                   1772:             $udom=$env{'user.domain'};
                   1773:         }
1.1023    raeburn  1774:         if ($udom) {
                   1775:             my $uname = &get_domainconfiguser($udom); 
                   1776:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1777:         }
                   1778:     }
                   1779: }
                   1780: 
1.1023    raeburn  1781: # ----------------------------------construct domainconfig user for a domain 
                   1782: sub get_domainconfiguser {
                   1783:     my ($udom) = @_;
                   1784:     return $udom.'-domainconfig';
                   1785: }
                   1786: 
1.837     raeburn  1787: sub retrieve_inst_usertypes {
                   1788:     my ($udom) = @_;
                   1789:     my (%returnhash,@order);
1.989     raeburn  1790:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1791:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1792:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  1793:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1794:     } else {
                   1795:         if (defined(&domain($udom,'primary'))) {
                   1796:             my $uhome=&domain($udom,'primary');
                   1797:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1798:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  1799:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1800:                 return (\%returnhash,\@order);
                   1801:             }
                   1802:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1803:             my @pairs=split(/\&/,$hashitems);
                   1804:             foreach my $item (@pairs) {
                   1805:                 my ($key,$value)=split(/=/,$item,2);
                   1806:                 $key = &unescape($key);
                   1807:                 next if ($key =~ /^error: 2 /);
                   1808:                 $returnhash{$key}=&thaw_unescape($value);
                   1809:             }
                   1810:             my @esc_order = split(/\&/,$orderitems);
                   1811:             foreach my $item (@esc_order) {
                   1812:                 push(@order,&unescape($item));
                   1813:             }
                   1814:         } else {
1.1172.2.44  raeburn  1815:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1816:         }
1.1172.2.44  raeburn  1817:         return (\%returnhash,\@order);
1.837     raeburn  1818:     }
                   1819: }
                   1820: 
1.868     raeburn  1821: sub is_domainimage {
                   1822:     my ($url) = @_;
1.1172.2.74  raeburn  1823:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  1824:         if (&domain($1) ne '') {
                   1825:             return '1';
                   1826:         }
                   1827:     }
                   1828:     return;
                   1829: }
                   1830: 
1.899     raeburn  1831: sub inst_directory_query {
                   1832:     my ($srch) = @_;
                   1833:     my $udom = $srch->{'srchdomain'};
                   1834:     my %results;
                   1835:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1836:     my $outcome;
1.899     raeburn  1837:     if ($homeserver ne '') {
1.904     albertel 1838: 	my $queryid=&reply("querysend:instdirsearch:".
                   1839: 			   &escape($srch->{'srchby'}).':'.
                   1840: 			   &escape($srch->{'srchterm'}).':'.
                   1841: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1842: 	my $host=&hostname($homeserver);
                   1843: 	if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96  raeburn  1844: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 1845: 	    return;
                   1846: 	}
                   1847: 	my $response = &get_query_reply($queryid);
                   1848: 	my $maxtries = 5;
                   1849: 	my $tries = 1;
                   1850: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1851: 	    $response = &get_query_reply($queryid);
                   1852: 	    $tries ++;
                   1853: 	}
                   1854: 
                   1855:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1856:             if ($response eq 'unavailable') {
                   1857:                 $outcome = $response;
                   1858:             } else {
                   1859:                 $outcome = 'ok';
                   1860:                 my @matches = split(/\n/,$response);
                   1861:                 foreach my $match (@matches) {
                   1862:                     my ($key,$value) = split(/=/,$match);
                   1863:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1864:                 }
1.899     raeburn  1865:             }
                   1866:         }
                   1867:     }
1.909     raeburn  1868:     return ($outcome,%results);
1.899     raeburn  1869: }
                   1870: 
                   1871: sub usersearch {
                   1872:     my ($srch) = @_;
                   1873:     my $dom = $srch->{'srchdomain'};
                   1874:     my %results;
                   1875:     my %libserv = &all_library();
                   1876:     my $query = 'usersearch';
                   1877:     foreach my $tryserver (keys(%libserv)) {
                   1878:         if (&host_domain($tryserver) eq $dom) {
                   1879:             my $host=&hostname($tryserver);
                   1880:             my $queryid=
1.911     raeburn  1881:                 &reply("querysend:".&escape($query).':'.
                   1882:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1883:                        &escape($srch->{'srchtype'}).':'.
                   1884:                        &escape($srch->{'srchterm'}),$tryserver);
                   1885:             if ($queryid !~/^\Q$host\E\_/) {
                   1886:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1887:                 next;
1.899     raeburn  1888:             }
                   1889:             my $reply = &get_query_reply($queryid);
                   1890:             my $maxtries = 1;
                   1891:             my $tries = 1;
                   1892:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1893:                 $reply = &get_query_reply($queryid);
                   1894:                 $tries ++;
                   1895:             }
                   1896:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1897:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1898:             } else {
1.911     raeburn  1899:                 my @matches;
                   1900:                 if ($reply =~ /\n/) {
                   1901:                     @matches = split(/\n/,$reply);
                   1902:                 } else {
                   1903:                     @matches = split(/\&/,$reply);
                   1904:                 }
1.899     raeburn  1905:                 foreach my $match (@matches) {
                   1906:                     my ($uname,$udom,%userhash);
1.911     raeburn  1907:                     foreach my $entry (split(/:/,$match)) {
                   1908:                         my ($key,$value) =
                   1909:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1910:                         $userhash{$key} = $value;
                   1911:                         if ($key eq 'username') {
                   1912:                             $uname = $value;
                   1913:                         } elsif ($key eq 'domain') {
                   1914:                             $udom = $value;
1.911     raeburn  1915:                         }
1.899     raeburn  1916:                     }
                   1917:                     $results{$uname.':'.$udom} = \%userhash;
                   1918:                 }
                   1919:             }
                   1920:         }
                   1921:     }
                   1922:     return %results;
                   1923: }
                   1924: 
1.912     raeburn  1925: sub get_instuser {
                   1926:     my ($udom,$uname,$id) = @_;
                   1927:     my $homeserver = &domain($udom,'primary');
                   1928:     my ($outcome,%results);
                   1929:     if ($homeserver ne '') {
                   1930:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1931:                            &escape($id).':'.&escape($udom),$homeserver);
                   1932:         my $host=&hostname($homeserver);
                   1933:         if ($queryid !~/^\Q$host\E\_/) {
                   1934:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1935:             return;
                   1936:         }
                   1937:         my $response = &get_query_reply($queryid);
                   1938:         my $maxtries = 5;
                   1939:         my $tries = 1;
                   1940:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1941:             $response = &get_query_reply($queryid);
                   1942:             $tries ++;
                   1943:         }
                   1944:         if (!&error($response) && $response ne 'refused') {
                   1945:             if ($response eq 'unavailable') {
                   1946:                 $outcome = $response;
                   1947:             } else {
                   1948:                 $outcome = 'ok';
                   1949:                 my @matches = split(/\n/,$response);
                   1950:                 foreach my $match (@matches) {
                   1951:                     my ($key,$value) = split(/=/,$match);
                   1952:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1953:                 }
                   1954:             }
                   1955:         }
                   1956:     }
                   1957:     my %userinfo;
                   1958:     if (ref($results{$uname}) eq 'HASH') {
                   1959:         %userinfo = %{$results{$uname}};
                   1960:     } 
                   1961:     return ($outcome,%userinfo);
                   1962: }
                   1963: 
1.1172.2.69  raeburn  1964: sub get_multiple_instusers {
                   1965:     my ($udom,$users,$caller) = @_;
                   1966:     my ($outcome,$results);
                   1967:     if (ref($users) eq 'HASH') {
                   1968:         my $count = keys(%{$users});
                   1969:         my $requested = &freeze_escape($users);
                   1970:         my $homeserver = &domain($udom,'primary');
                   1971:         if ($homeserver ne '') {
                   1972:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   1973:             my $host=&hostname($homeserver);
                   1974:             if ($queryid !~/^\Q$host\E\_/) {
                   1975:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   1976:                          ' for host: '.$homeserver.'in domain '.$udom);
                   1977:                 return ($outcome,$results);
                   1978:             }
                   1979:             my $response = &get_query_reply($queryid);
                   1980:             my $maxtries = 5;
                   1981:             if ($count > 100) {
                   1982:                 $maxtries = 1+int($count/20);
                   1983:             }
                   1984:             my $tries = 1;
                   1985:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   1986:                 $response = &get_query_reply($queryid);
                   1987:                 $tries ++;
                   1988:             }
                   1989:             if ($response eq '') {
                   1990:                 $results = {};
                   1991:                 foreach my $key (keys(%{$users})) {
                   1992:                     my ($uname,$id);
                   1993:                     if ($caller eq 'id') {
                   1994:                         $id = $key;
                   1995:                     } else {
                   1996:                         $uname = $key;
                   1997:                     }
                   1998:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
                   1999:                     $outcome = $resp;
                   2000:                     if ($resp eq 'ok') {
                   2001:                         %{$results} = (%{$results}, %info);
                   2002:                     } else {
                   2003:                         last;
                   2004:                     }
                   2005:                 }
                   2006:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2007:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2008:                     $outcome = $response;
                   2009:                 } else {
                   2010:                     ($outcome,my $userdata) = split(/=/,$response,2);
                   2011:                     if ($outcome eq 'ok') {
                   2012:                         $results = &thaw_unescape($userdata);
                   2013:                     }
                   2014:                 }
                   2015:             }
                   2016:         }
                   2017:     }
                   2018:     return ($outcome,$results);
                   2019: }
                   2020: 
1.912     raeburn  2021: sub inst_rulecheck {
1.923     raeburn  2022:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2023:     my %returnhash;
                   2024:     if ($udom ne '') {
                   2025:         if (ref($rules) eq 'ARRAY') {
                   2026:             @{$rules} = map {&escape($_);} (@{$rules});
                   2027:             my $rulestr = join(':',@{$rules});
                   2028:             my $homeserver=&domain($udom,'primary');
                   2029:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2030:                 my $response;
                   2031:                 if ($item eq 'username') {                
                   2032:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2033:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2034:                                               $homeserver));
1.923     raeburn  2035:                 } elsif ($item eq 'id') {
                   2036:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2037:                                               ':'.&escape($id).':'.$rulestr,
                   2038:                                               $homeserver));
1.945     raeburn  2039:                 } elsif ($item eq 'selfcreate') {
                   2040:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2041:                                                &escape($udom).':'.&escape($uname).
                   2042:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2043:                 }
1.912     raeburn  2044:                 if ($response ne 'refused') {
                   2045:                     my @pairs=split(/\&/,$response);
                   2046:                     foreach my $item (@pairs) {
                   2047:                         my ($key,$value)=split(/=/,$item,2);
                   2048:                         $key = &unescape($key);
                   2049:                         next if ($key =~ /^error: 2 /);
                   2050:                         $returnhash{$key}=&thaw_unescape($value);
                   2051:                     }
                   2052:                 }
                   2053:             }
                   2054:         }
                   2055:     }
                   2056:     return %returnhash;
                   2057: }
                   2058: 
                   2059: sub inst_userrules {
1.923     raeburn  2060:     my ($udom,$check) = @_;
1.912     raeburn  2061:     my (%ruleshash,@ruleorder);
                   2062:     if ($udom ne '') {
                   2063:         my $homeserver=&domain($udom,'primary');
                   2064:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2065:             my $response;
                   2066:             if ($check eq 'id') {
                   2067:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2068:                                  $homeserver);
1.943     raeburn  2069:             } elsif ($check eq 'email') {
                   2070:                 $response=&reply('instemailrules:'.&escape($udom),
                   2071:                                  $homeserver);
1.923     raeburn  2072:             } else {
                   2073:                 $response=&reply('instuserrules:'.&escape($udom),
                   2074:                                  $homeserver);
                   2075:             }
1.912     raeburn  2076:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2077:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2078:                 ($response ne 'no_such_host')) {
                   2079:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2080:                 my @pairs=split(/\&/,$hashitems);
                   2081:                 foreach my $item (@pairs) {
                   2082:                     my ($key,$value)=split(/=/,$item,2);
                   2083:                     $key = &unescape($key);
                   2084:                     next if ($key =~ /^error: 2 /);
                   2085:                     $ruleshash{$key}=&thaw_unescape($value);
                   2086:                 }
                   2087:                 my @esc_order = split(/\&/,$orderitems);
                   2088:                 foreach my $item (@esc_order) {
                   2089:                     push(@ruleorder,&unescape($item));
                   2090:                 }
                   2091:             }
                   2092:         }
                   2093:     }
                   2094:     return (\%ruleshash,\@ruleorder);
                   2095: }
                   2096: 
1.976     raeburn  2097: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2098: 
                   2099: sub get_domain_defaults {
1.1172.2.35  raeburn  2100:     my ($domain,$ignore_cache) = @_;
                   2101:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2102:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2103:     unless ($ignore_cache) {
                   2104:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2105:         if (defined($cached)) {
                   2106:             if (ref($result) eq 'HASH') {
                   2107:                 return %{$result};
                   2108:             }
1.943     raeburn  2109:         }
                   2110:     }
                   2111:     my %domdefaults;
                   2112:     my %domconfig =
1.989     raeburn  2113:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2114:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2115:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2116:                                   'requestauthor','selfenrollment',
1.1172.2.89  raeburn  2117:                                   'coursecategories','autoenroll',
                   2118:                                   'helpsettings'],$domain);
1.1172.2.41  raeburn  2119:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2120:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2121:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2122:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2123:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2124:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2125:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2126:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91  raeburn  2127:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2128:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2129:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2130:     } else {
                   2131:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2132:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2133:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2134:     }
1.976     raeburn  2135:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2136:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2137:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2138:         } else {
                   2139:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2140:         }
1.1172.2.6  raeburn  2141:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2142:         foreach my $item (@usertools) {
                   2143:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2144:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2145:             }
                   2146:         }
1.1172.2.29  raeburn  2147:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2148:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2149:         }
1.976     raeburn  2150:     }
1.985     raeburn  2151:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2152:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2153:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2154:         }
                   2155:     }
1.1172.2.9  raeburn  2156:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2157:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2158:     }
1.989     raeburn  2159:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2160:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2161:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2162:         }
                   2163:     }
1.1047    raeburn  2164:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2165:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2166:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2167:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2168:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2169:         }
1.1172.2.41  raeburn  2170:         foreach my $type (@coursetypes) {
                   2171:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2172:                 unless ($type eq 'community') {
                   2173:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2174:                 }
                   2175:             }
                   2176:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2177:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2178:             }
1.1172.2.60  raeburn  2179:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2180:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2181:                     $domdefaults{$type.'postsubtimeout'} =
                   2182:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2183:                 }
                   2184:             }
1.1172.2.30  raeburn  2185:         }
1.1172.2.67  raeburn  2186:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2187:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2188:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2189:                 if (@clonecodes) {
                   2190:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2191:                 }
                   2192:             }
                   2193:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2194:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2195:         }
1.1047    raeburn  2196:     }
1.1073    raeburn  2197:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2198:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2199:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2200:         }
                   2201:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2202:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2203:         }
1.1172.2.62  raeburn  2204:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2205:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2206:         }
1.1073    raeburn  2207:     }
1.1172.2.41  raeburn  2208:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2209:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2210:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2211:                             'approval','limit');
                   2212:             foreach my $type (@coursetypes) {
                   2213:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2214:                     my @mgrdc = ();
                   2215:                     foreach my $item (@settings) {
                   2216:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2217:                             push(@mgrdc,$item);
                   2218:                         }
                   2219:                     }
                   2220:                     if (@mgrdc) {
                   2221:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2222:                     }
                   2223:                 }
                   2224:             }
                   2225:         }
                   2226:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2227:             foreach my $type (@coursetypes) {
                   2228:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2229:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2230:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2231:                     }
                   2232:                 }
                   2233:             }
                   2234:         }
                   2235:     }
1.1172.2.46  raeburn  2236:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2237:         $domdefaults{'catauth'} = 'std';
                   2238:         $domdefaults{'catunauth'} = 'std';
                   2239:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2240:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2241:         }
                   2242:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2243:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2244:         }
                   2245:     }
1.1172.2.76  raeburn  2246:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2247:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2248:     }
1.1172.2.89  raeburn  2249:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2250:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2251:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2252:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2253:         }
                   2254:     }
1.1172.2.23  raeburn  2255:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2256:     return %domdefaults;
                   2257: }
                   2258: 
1.344     www      2259: # --------------------------------------------------- Assign a key to a student
                   2260: 
                   2261: sub assign_access_key {
1.364     www      2262: #
                   2263: # a valid key looks like uname:udom#comments
                   2264: # comments are being appended
                   2265: #
1.498     www      2266:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2267:     $kdom=
1.620     albertel 2268:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2269:     $knum=
1.620     albertel 2270:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2271:     $cdom=
1.620     albertel 2272:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2273:     $cnum=
1.620     albertel 2274:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2275:     $udom=$env{'user.name'} unless (defined($udom));
                   2276:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2277:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2278:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2279:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2280:                                                   # assigned to this person
                   2281:                                                   # - this should not happen,
1.345     www      2282:                                                   # unless something went wrong
                   2283:                                                   # the first time around
                   2284: # ready to assign
1.364     www      2285:         $logentry=$1.'; '.$logentry;
1.496     www      2286:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2287:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2288: # key now belongs to user
1.346     www      2289: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2290:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2291:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2292:                 return 'ok';
                   2293:             } else {
                   2294:                 return 
                   2295:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2296: 	    }
                   2297:         } else {
                   2298:             return 'error: Could not assign key, try again later.';
                   2299:         }
1.364     www      2300:     } elsif (!$existing{$ckey}) {
1.345     www      2301: # the key does not exist
                   2302: 	return 'error: The key does not exist';
                   2303:     } else {
                   2304: # the key is somebody else's
                   2305: 	return 'error: The key is already in use';
                   2306:     }
1.344     www      2307: }
                   2308: 
1.364     www      2309: # ------------------------------------------ put an additional comment on a key
                   2310: 
                   2311: sub comment_access_key {
                   2312: #
                   2313: # a valid key looks like uname:udom#comments
                   2314: # comments are being appended
                   2315: #
                   2316:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2317:     $cdom=
1.620     albertel 2318:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2319:     $cnum=
1.620     albertel 2320:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2321:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2322:     if ($existing{$ckey}) {
                   2323:         $existing{$ckey}.='; '.$logentry;
                   2324: # ready to assign
1.367     www      2325:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2326:                                                  $cdom,$cnum) eq 'ok') {
                   2327: 	    return 'ok';
                   2328:         } else {
                   2329: 	    return 'error: Count not store comment.';
                   2330:         }
                   2331:     } else {
                   2332: # the key does not exist
                   2333: 	return 'error: The key does not exist';
                   2334:     }
                   2335: }
                   2336: 
1.344     www      2337: # ------------------------------------------------------ Generate a set of keys
                   2338: 
                   2339: sub generate_access_keys {
1.364     www      2340:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2341:     $cdom=
1.620     albertel 2342:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2343:     $cnum=
1.620     albertel 2344:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2345:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2346:     unless (($cdom) && ($cnum)) { return 0; }
                   2347:     if ($number>10000) { return 0; }
                   2348:     sleep(2); # make sure don't get same seed twice
                   2349:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2350:     my $total=0;
                   2351:     for (my $i=1;$i<=$number;$i++) {
                   2352:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2353:                   sprintf("%lx",int(100000*rand)).'-'.
                   2354:                   sprintf("%lx",int(100000*rand));
                   2355:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2356:        $newkey=~s/0/h/g; # and also 0 and O
                   2357:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2358:        if ($existing{$newkey}) {
                   2359:            $i--;
                   2360:        } else {
1.364     www      2361: 	  if (&put('accesskeys',
                   2362:               { $newkey => '# generated '.localtime().
1.620     albertel 2363:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2364:                            '; '.$logentry },
                   2365: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2366:               $total++;
                   2367: 	  }
                   2368:        }
                   2369:     }
1.620     albertel 2370:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2371:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2372:     return $total;
                   2373: }
                   2374: 
                   2375: # ------------------------------------------------------- Validate an accesskey
                   2376: 
                   2377: sub validate_access_key {
                   2378:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2379:     $cdom=
1.620     albertel 2380:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2381:     $cnum=
1.620     albertel 2382:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2383:     $udom=$env{'user.domain'} unless (defined($udom));
                   2384:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2385:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2386:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2387: }
                   2388: 
                   2389: # ------------------------------------- Find the section of student in a course
1.652     albertel 2390: sub devalidate_getsection_cache {
                   2391:     my ($udom,$unam,$courseid)=@_;
                   2392:     my $hashid="$udom:$unam:$courseid";
                   2393:     &devalidate_cache_new('getsection',$hashid);
                   2394: }
1.298     matthew  2395: 
1.815     albertel 2396: sub courseid_to_courseurl {
                   2397:     my ($courseid) = @_;
                   2398:     #already url style courseid
                   2399:     return $courseid if ($courseid =~ m{^/});
                   2400: 
                   2401:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2402: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2403: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2404: 	return "/$cdom/$cnum";
                   2405:     }
                   2406: 
                   2407:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2408:     if (exists($courseinfo{'num'})) {
                   2409: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2410:     }
                   2411: 
                   2412:     return undef;
                   2413: }
                   2414: 
1.298     matthew  2415: sub getsection {
                   2416:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2417:     my $cachetime=1800;
1.551     albertel 2418: 
                   2419:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2420:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2421:     if (defined($cached)) { return $result; }
                   2422: 
1.298     matthew  2423:     my %Pending; 
                   2424:     my %Expired;
                   2425:     #
                   2426:     # Each role can either have not started yet (pending), be active, 
                   2427:     #    or have expired.
                   2428:     #
                   2429:     # If there is an active role, we are done.
                   2430:     #
                   2431:     # If there is more than one role which has not started yet, 
                   2432:     #     choose the one which will start sooner
                   2433:     # If there is one role which has not started yet, return it.
                   2434:     #
                   2435:     # If there is more than one expired role, choose the one which ended last.
                   2436:     # If there is a role which has expired, return it.
                   2437:     #
1.815     albertel 2438:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2439:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2440:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2441:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2442:         my $section=$1;
                   2443:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2444:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2445:         my $now=time;
1.548     albertel 2446:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2447:             $Expired{$end}=$section;
                   2448:             next;
                   2449:         }
1.548     albertel 2450:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2451:             $Pending{$start}=$section;
                   2452:             next;
                   2453:         }
1.599     albertel 2454:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2455:     }
                   2456:     #
                   2457:     # Presumedly there will be few matching roles from the above
                   2458:     # loop and the sorting time will be negligible.
                   2459:     if (scalar(keys(%Pending))) {
                   2460:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2461:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2462:     } 
                   2463:     if (scalar(keys(%Expired))) {
                   2464:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2465:         my $time = pop(@sorted);
1.599     albertel 2466:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2467:     }
1.599     albertel 2468:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2469: }
1.70      www      2470: 
1.599     albertel 2471: sub save_cache {
                   2472:     &purge_remembered();
1.722     albertel 2473:     #&Apache::loncommon::validate_page();
1.620     albertel 2474:     undef(%env);
1.780     albertel 2475:     undef($env_loaded);
1.599     albertel 2476: }
1.452     albertel 2477: 
1.599     albertel 2478: my $to_remember=-1;
                   2479: my %remembered;
                   2480: my %accessed;
                   2481: my $kicks=0;
                   2482: my $hits=0;
1.849     albertel 2483: sub make_key {
                   2484:     my ($name,$id) = @_;
1.872     albertel 2485:     if (length($id) > 65 
                   2486: 	&& length(&escape($id)) > 200) {
                   2487: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2488:     }
1.849     albertel 2489:     return &escape($name.':'.$id);
                   2490: }
                   2491: 
1.599     albertel 2492: sub devalidate_cache_new {
                   2493:     my ($name,$id,$debug) = @_;
                   2494:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  2495:     my $remembered_id=$name.':'.$id;
1.849     albertel 2496:     $id=&make_key($name,$id);
1.599     albertel 2497:     $memcache->delete($id);
1.1172.2.81  raeburn  2498:     delete($remembered{$remembered_id});
                   2499:     delete($accessed{$remembered_id});
1.599     albertel 2500: }
                   2501: 
                   2502: sub is_cached_new {
                   2503:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  2504:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   2505:                                      # keys in %remembered hash, which persists for
                   2506:                                      # duration of request (no restriction on key length).
                   2507:     if (exists($remembered{$remembered_id})) {
                   2508: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2509: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2510: 	$hits++;
1.1172.2.81  raeburn  2511: 	return ($remembered{$remembered_id},1);
1.599     albertel 2512:     }
1.1172.2.81  raeburn  2513:     $id=&make_key($name,$id);
1.599     albertel 2514:     my $value = $memcache->get($id);
                   2515:     if (!(defined($value))) {
                   2516: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2517: 	return (undef,undef);
1.416     albertel 2518:     }
1.599     albertel 2519:     if ($value eq '__undef__') {
                   2520: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2521: 	$value=undef;
                   2522:     }
1.1172.2.81  raeburn  2523:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2524:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2525:     return ($value,1);
                   2526: }
                   2527: 
                   2528: sub do_cache_new {
                   2529:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  2530:     my $remembered_id=$name.':'.$id;
1.849     albertel 2531:     $id=&make_key($name,$id);
1.599     albertel 2532:     my $setvalue=$value;
                   2533:     if (!defined($setvalue)) {
                   2534: 	$setvalue='__undef__';
                   2535:     }
1.623     albertel 2536:     if (!defined($time) ) {
                   2537: 	$time=600;
                   2538:     }
1.599     albertel 2539:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2540:     my $result = $memcache->set($id,$setvalue,$time);
                   2541:     if (! $result) {
1.872     albertel 2542: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2543: 	$memcache->disconnect_all();
1.872     albertel 2544:     }
1.600     albertel 2545:     # need to make a copy of $value
1.1172.2.81  raeburn  2546:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2547:     return $value;
                   2548: }
                   2549: 
                   2550: sub make_room {
1.1172.2.81  raeburn  2551:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2552: 
1.1172.2.81  raeburn  2553:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2554:                                     : $value;
1.599     albertel 2555:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  2556:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2557:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2558:     my $to_kick;
                   2559:     my $max_time=0;
                   2560:     foreach my $other (keys(%accessed)) {
                   2561: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2562: 	    $to_kick=$other;
                   2563: 	    $max_time=&tv_interval($accessed{$other});
                   2564: 	}
                   2565:     }
                   2566:     delete($remembered{$to_kick});
                   2567:     delete($accessed{$to_kick});
                   2568:     $kicks++;
                   2569:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2570:     return;
                   2571: }
                   2572: 
1.599     albertel 2573: sub purge_remembered {
1.604     albertel 2574:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2575:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2576:     undef(%remembered);
                   2577:     undef(%accessed);
1.428     albertel 2578: }
1.70      www      2579: # ------------------------------------- Read an entry from a user's environment
                   2580: 
                   2581: sub userenvironment {
                   2582:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2583:     my $items;
                   2584:     foreach my $item (@what) {
                   2585:         $items.=&escape($item).'&';
                   2586:     }
                   2587:     $items=~s/\&$//;
1.70      www      2588:     my %returnhash=();
1.1009    raeburn  2589:     my $uhome = &homeserver($unam,$udom);
                   2590:     unless ($uhome eq 'no_host') {
                   2591:         my @answer=split(/\&/, 
                   2592:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2593:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2594:             return %returnhash;
                   2595:         }
1.1009    raeburn  2596:         my $i;
                   2597:         for ($i=0;$i<=$#what;$i++) {
                   2598: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2599:         }
1.70      www      2600:     }
                   2601:     return %returnhash;
1.1       albertel 2602: }
                   2603: 
1.617     albertel 2604: # ---------------------------------------------------------- Get a studentphoto
                   2605: sub studentphoto {
                   2606:     my ($udom,$unam,$ext) = @_;
                   2607:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2608:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2609:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2610:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2611:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2612:             } else {
                   2613:                 my ($result,$perm_reqd)=
1.707     albertel 2614: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2615:                 if ($result eq 'ok') {
                   2616:                     if (!($perm_reqd eq 'yes')) {
                   2617:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2618:                     }
                   2619:                 }
                   2620:             }
                   2621:         }
                   2622:     } else {
                   2623:         my ($result,$perm_reqd) = 
1.707     albertel 2624: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2625:         if ($result eq 'ok') {
                   2626:             if (!($perm_reqd eq 'yes')) {
                   2627:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2628:             }
                   2629:         }
                   2630:     }
                   2631:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2632: }
                   2633: 
                   2634: sub retrievestudentphoto {
                   2635:     my ($udom,$unam,$ext,$type) = @_;
                   2636:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2637:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2638:     if ($ret eq 'ok') {
                   2639:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2640:         if ($type eq 'thumbnail') {
                   2641:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2642:         }
                   2643:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2644:         return $tokenurl;
                   2645:     } else {
                   2646:         if ($type eq 'thumbnail') {
                   2647:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2648:         } else { 
                   2649:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2650:         }
1.617     albertel 2651:     }
                   2652: }
                   2653: 
1.263     www      2654: # -------------------------------------------------------------------- New chat
                   2655: 
                   2656: sub chatsend {
1.724     raeburn  2657:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2658:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2659:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2660:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2661:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2662: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2663: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2664: }
                   2665: 
                   2666: # ------------------------------------------ Find current version of a resource
                   2667: 
                   2668: sub getversion {
                   2669:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2670:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2671:     return &currentversion(&filelocation('',$fname));
                   2672: }
                   2673: 
                   2674: sub currentversion {
                   2675:     my $fname=shift;
                   2676:     my $author=$fname;
                   2677:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2678:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2679:     my $home=&homeserver($uname,$udom);
1.292     www      2680:     if ($home eq 'no_host') { 
                   2681:         return -1; 
                   2682:     }
1.1112    www      2683:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2684:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2685: 	return -1;
                   2686:     }
1.1112    www      2687:     return $answer;
1.263     www      2688: }
                   2689: 
1.1111    www      2690: #
                   2691: # Return special version number of resource if set by override, empty otherwise
                   2692: #
                   2693: sub usedversion {
                   2694:     my $fname=shift;
                   2695:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2696:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2697:     if ($urlversion) { return $urlversion; }
                   2698:     return '';
                   2699: }
                   2700: 
1.1       albertel 2701: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2702: 
1.1       albertel 2703: sub subscribe {
                   2704:     my $fname=shift;
1.761     raeburn  2705:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2706:     $fname=~s/[\n\r]//g;
1.1       albertel 2707:     my $author=$fname;
                   2708:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2709:     my ($udom,$uname)=split(/\//,$author);
                   2710:     my $home=homeserver($uname,$udom);
1.335     albertel 2711:     if ($home eq 'no_host') {
                   2712:         return 'not_found';
1.1       albertel 2713:     }
                   2714:     my $answer=reply("sub:$fname",$home);
1.64      www      2715:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2716: 	$answer.=' by '.$home;
                   2717:     }
1.1       albertel 2718:     return $answer;
                   2719: }
                   2720:     
1.8       www      2721: # -------------------------------------------------------------- Replicate file
                   2722: 
                   2723: sub repcopy {
                   2724:     my $filename=shift;
1.23      www      2725:     $filename=~s/\/+/\//g;
1.1142    raeburn  2726:     my $londocroot = $perlvar{'lonDocRoot'};
                   2727:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2728:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2729:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2730: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2731: 	return &repcopy_userfile($filename);
                   2732:     }
1.532     albertel 2733:     $filename=~s/[\n\r]//g;
1.8       www      2734:     my $transname="$filename.in.transfer";
1.828     www      2735: # FIXME: this should flock
1.607     raeburn  2736:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2737:     my $remoteurl=subscribe($filename);
1.64      www      2738:     if ($remoteurl =~ /^con_lost by/) {
                   2739: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2740:            return 'unavailable';
1.8       www      2741:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2742: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2743: 	   return 'not_found';
1.64      www      2744:     } elsif ($remoteurl =~ /^rejected by/) {
                   2745: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2746:            return 'forbidden';
1.20      www      2747:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2748:            return 'ok';
1.8       www      2749:     } else {
1.290     www      2750:         my $author=$filename;
                   2751:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2752:         my ($udom,$uname)=split(/\//,$author);
                   2753:         my $home=homeserver($uname,$udom);
                   2754:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2755:            my @parts=split(/\//,$filename);
                   2756:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2757:            if ($path ne "$londocroot/res") {
1.8       www      2758:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2759: 	       return 'bad_request';
1.8       www      2760:            }
                   2761:            my $count;
                   2762:            for ($count=5;$count<$#parts;$count++) {
                   2763:                $path.="/$parts[$count]";
                   2764:                if ((-e $path)!=1) {
                   2765: 		   mkdir($path,0777);
                   2766:                }
                   2767:            }
                   2768:            my $ua=new LWP::UserAgent;
                   2769:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2770:            my $response=$ua->request($request,$transname);
                   2771:            if ($response->is_error()) {
                   2772: 	       unlink($transname);
                   2773:                my $message=$response->status_line;
1.672     albertel 2774:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2775:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2776:                return 'unavailable';
1.8       www      2777:            } else {
1.16      www      2778: 	       if ($remoteurl!~/\.meta$/) {
                   2779:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2780:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2781:                   if ($mresponse->is_error()) {
                   2782: 		      unlink($filename.'.meta');
                   2783:                       &logthis(
1.672     albertel 2784:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2785:                   }
                   2786: 	       }
1.8       www      2787:                rename($transname,$filename);
1.607     raeburn  2788:                return 'ok';
1.8       www      2789:            }
1.290     www      2790:        }
1.8       www      2791:     }
1.330     www      2792: }
                   2793: 
                   2794: # ------------------------------------------------ Get server side include body
                   2795: sub ssi_body {
1.381     albertel 2796:     my ($filelink,%form)=@_;
1.606     matthew  2797:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2798:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2799:     }
1.953     www      2800:     my $output='';
                   2801:     my $response;
1.980     raeburn  2802:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2803:        ($output,$response)=&externalssi($filelink);
1.953     www      2804:     } else {
1.1004    droeschl 2805:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2806:        $filelink .= 'inhibitmenu=yes';
1.953     www      2807:        ($output,$response)=&ssi($filelink,%form);
                   2808:     }
1.778     albertel 2809:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2810:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2811:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2812:     if (wantarray) {
                   2813:         return ($output, $response);
                   2814:     } else {
                   2815:         return $output;
                   2816:     }
1.8       www      2817: }
                   2818: 
1.15      www      2819: # --------------------------------------------------------- Server Side Include
                   2820: 
1.782     albertel 2821: sub absolute_url {
                   2822:     my ($host_name) = @_;
                   2823:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2824:     if ($host_name eq '') {
                   2825: 	$host_name = $ENV{'SERVER_NAME'};
                   2826:     }
                   2827:     return $protocol.$host_name;
                   2828: }
                   2829: 
1.942     foxr     2830: #
                   2831: #   Server side include.
                   2832: # Parameters:
                   2833: #  fn     Possibly encrypted resource name/id.
                   2834: #  form   Hash that describes how the rendering should be done
                   2835: #         and other things.
1.944     foxr     2836: # Returns:
1.950     raeburn  2837: #   Scalar context: The content of the response.
                   2838: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2839: #     
1.15      www      2840: sub ssi {
                   2841: 
1.944     foxr     2842:     my ($fn,%form)=@_;
1.1172.2.100  raeburn  2843:     my ($request,$response);
1.711     albertel 2844: 
                   2845:     $form{'no_update_last_known'}=1;
1.895     albertel 2846:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2847:     if (%form) {
1.782     albertel 2848:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58  raeburn  2849:       $request->content(join('&',map {
                   2850:             my $name = escape($_);
                   2851:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   2852:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   2853:             : &escape($form{$_}) );
                   2854:         } keys(%form)));
1.23      www      2855:     } else {
1.782     albertel 2856:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2857:     }
                   2858: 
1.15      www      2859:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100  raeburn  2860: 
1.1172.2.101! raeburn  2861:     if (($env{'request.course.id'}) &&
        !          2862:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
        !          2863:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
        !          2864:         ($form{'grade_symb'} ne '') &&
        !          2865:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
        !          2866:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100  raeburn  2867:         if (LWP::UserAgent->VERSION >= 5.834) {
                   2868:             my $ua=new LWP::UserAgent;
                   2869:             $ua->local_address('127.0.0.1');
                   2870:             $response = $ua->request($request);
                   2871:         } else {
                   2872:             {
                   2873:                 require LWP::Protocol::http;
                   2874:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
                   2875:                 my $ua=new LWP::UserAgent;
                   2876:                 $response = $ua->request($request);
                   2877:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
                   2878:             }
                   2879:         }
                   2880:     } else {
                   2881:         my $ua=new LWP::UserAgent;
                   2882:         $response = $ua->request($request);
                   2883:     }
1.944     foxr     2884:     if (wantarray) {
1.1172.2.3  raeburn  2885: 	return ($response->content, $response);
1.944     foxr     2886:     } else {
1.1172.2.3  raeburn  2887: 	return $response->content;
1.942     foxr     2888:     }
1.324     www      2889: }
                   2890: 
                   2891: sub externalssi {
                   2892:     my ($url)=@_;
                   2893:     my $ua=new LWP::UserAgent;
                   2894:     my $request=new HTTP::Request('GET',$url);
                   2895:     my $response=$ua->request($request);
1.954     raeburn  2896:     if (wantarray) {
                   2897:         return ($response->content, $response);
                   2898:     } else {
                   2899:         return $response->content;
                   2900:     }
1.15      www      2901: }
1.254     www      2902: 
1.1172.2.98  raeburn  2903: # If the local copy of a replicated resource is outdated, trigger a
                   2904: # connection from the homeserver to flush the delayed queue. If no update
                   2905: # happens, remove local copies of outdated resource (and corresponding
                   2906: # metadata file).
                   2907: 
                   2908: sub remove_stale_resfile {
                   2909:     my ($url) = @_;
                   2910:     my $removed;
                   2911:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   2912:         my $audom = $1;
                   2913:         my $auname = $2;
                   2914:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
                   2915:             my $homeserver = &homeserver($auname,$audom);
                   2916:             unless (($homeserver eq 'no_host') ||
                   2917:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   2918:                 my $fname = &filelocation('',$url);
                   2919:                 if (-e $fname) {
                   2920:                     my $ua=new LWP::UserAgent;
                   2921:                     $ua->timeout(5);
                   2922:                     my $protocol = $protocol{$homeserver};
                   2923:                     $protocol = 'http' if ($protocol ne 'https');
                   2924:                     my $hostname = &hostname($homeserver);
                   2925:                     if ($hostname) {
                   2926:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
                   2927:                         my $request=new HTTP::Request('HEAD',$uri);
                   2928:                         my $response=$ua->request($request);
                   2929:                         if ($response->is_success()) {
                   2930:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   2931:                             my $locmodtime = (stat($fname))[9];
                   2932:                             if ($locmodtime < $remmodtime) {
                   2933:                                 my $stale;
                   2934:                                 my $answer = &reply('pong',$homeserver);
                   2935:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   2936:                                     sleep(0.2);
                   2937:                                     $locmodtime = (stat($fname))[9];
                   2938:                                     if ($locmodtime < $remmodtime) {
                   2939:                                         my $posstransfer = $fname.'.in.transfer';
                   2940:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   2941:                                             $removed = 1;
                   2942:                                         } else {
                   2943:                                             $stale = 1;
                   2944:                                         }
                   2945:                                     } else {
                   2946:                                         $removed = 1;
                   2947:                                     }
                   2948:                                 } else {
                   2949:                                     $stale = 1;
                   2950:                                 }
                   2951:                                 if ($stale) {
                   2952:                                     unlink($fname);
                   2953:                                     if ($uri!~/\.meta$/) {
                   2954:                                         unlink($fname.'.meta');
                   2955:                                     }
                   2956:                                     &reply("unsub:$fname",$homeserver);
                   2957:                                     $removed = 1;
                   2958:                                 }
                   2959:                             }
                   2960:                         }
                   2961:                     }
                   2962:                 }
                   2963:             }
                   2964:         }
                   2965:     }
                   2966:     return $removed;
                   2967: }
                   2968: 
1.492     albertel 2969: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2970: 
                   2971: sub allowuploaded {
                   2972:     my ($srcurl,$url)=@_;
                   2973:     $url=&clutter(&declutter($url));
                   2974:     my $dir=$url;
                   2975:     $dir=~s/\/[^\/]+$//;
                   2976:     my %httpref=();
                   2977:     my $httpurl=&hreflocation('',$url);
                   2978:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2979:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2980: }
1.477     raeburn  2981: 
1.1172.2.13  raeburn  2982: #
                   2983: # Determine if the current user should be able to edit a particular resource,
                   2984: # when viewing in course context.
                   2985: # (a) When viewing resource used to determine if "Edit" item is included in
                   2986: #     Functions.
                   2987: # (b) When displaying folder contents in course editor, used to determine if
                   2988: #     "Edit" link will be displayed alongside resource.
                   2989: #
                   2990: #  input: six args -- filename (decluttered), course number, course domain,
                   2991: #                   url, symb (if registered) and group (if this is a group
                   2992: #                   item -- e.g., bulletin board, group page etc.).
                   2993: #  output: array of five scalars --
                   2994: #          $cfile -- url for file editing if editable on current server
                   2995: #          $home -- homeserver of resource (i.e., for author if published,
                   2996: #                                           or course if uploaded.).
                   2997: #          $switchserver --  1 if server switch will be needed.
                   2998: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   2999: #          $forceview -- 1 if icon/link should be to go to view mode
                   3000: #
                   3001: 
                   3002: sub can_edit_resource {
                   3003:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3004:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3005: #
                   3006: # For aboutme pages user can only edit his/her own.
                   3007: #
                   3008:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   3009:         my ($sdom,$sname) = ($1,$2);
                   3010:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3011:             $home = $env{'user.home'};
                   3012:             $cfile = $resurl;
                   3013:             if ($env{'form.forceedit'}) {
                   3014:                 $forceview = 1;
                   3015:             } else {
                   3016:                 $forceedit = 1;
                   3017:             }
                   3018:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3019:         } else {
                   3020:             return;
                   3021:         }
                   3022:     }
                   3023: 
                   3024:     if ($env{'request.course.id'}) {
                   3025:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3026:         if ($group ne '') {
                   3027: # if this is a group homepage or group bulletin board, check group privs
                   3028:             my $allowed = 0;
                   3029:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3030:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   3031:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3032:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3033:                     $allowed = 1;
                   3034:                 }
                   3035:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3036:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3037:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3038:                     $allowed = 1;
                   3039:                 }
                   3040:             }
                   3041:             if ($allowed) {
                   3042:                 $home=&homeserver($cnum,$cdom);
                   3043:                 if ($env{'form.forceedit'}) {
                   3044:                     $forceview = 1;
                   3045:                 } else {
                   3046:                     $forceedit = 1;
                   3047:                 }
                   3048:                 $cfile = $resurl;
                   3049:             } else {
                   3050:                 return;
                   3051:             }
                   3052:         } else {
1.1172.2.15  raeburn  3053:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3054:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3055:                     return;
                   3056:                 }
                   3057:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  3058: #
                   3059: # No edit allowed where CC has switched to student role.
                   3060: #
                   3061:                 return;
                   3062:             }
                   3063:         }
                   3064:     }
                   3065: 
                   3066:     if ($file ne '') {
                   3067:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   3068:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3069:                 $uploaded = 1;
                   3070:                 $incourse = 1;
                   3071:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3072:                     $cfile = &hreflocation('',$file);
                   3073:                     if ($env{'form.forceedit'}) {
                   3074:                         $forceview = 1;
                   3075:                     } else {
                   3076:                         $forceedit = 1;
                   3077:                     }
                   3078:                 }
                   3079:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3080:                 $incourse = 1;
                   3081:                 if ($env{'form.forceedit'}) {
                   3082:                     $forceview = 1;
                   3083:                 } else {
                   3084:                     $forceedit = 1;
                   3085:                 }
                   3086:                 $cfile = $resurl;
                   3087:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3088:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3089:                     $incourse = 1;
                   3090:                     if ($env{'form.forceedit'}) {
                   3091:                         $forceview = 1;
                   3092:                     } else {
                   3093:                         $forceedit = 1;
                   3094:                     }
                   3095:                     $cfile = $resurl;
                   3096:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3097:                     $incourse = 1;
                   3098:                     $cfile = $resurl.'/smpedit';
                   3099:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3100:                     $incourse = 1;
                   3101:                     if ($env{'form.forceedit'}) {
                   3102:                         $forceview = 1;
                   3103:                     } else {
                   3104:                         $forceedit = 1;
                   3105:                     }
                   3106:                     $cfile = $resurl;
1.1172.2.15  raeburn  3107:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3108:                     $incourse = 1;
                   3109:                     if ($env{'form.forceedit'}) {
                   3110:                         $forceview = 1;
                   3111:                     } else {
                   3112:                         $forceedit = 1;
                   3113:                     }
                   3114:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3115:                 }
                   3116:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3117:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3118:                 if (&is_on_map($template)) {
                   3119:                     $incourse = 1;
                   3120:                     $forceview = 1;
                   3121:                     $cfile = $template;
                   3122:                 }
                   3123:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3124:                     $incourse = 1;
                   3125:                     if ($env{'form.forceedit'}) {
                   3126:                         $forceview = 1;
                   3127:                     } else {
                   3128:                         $forceedit = 1;
                   3129:                     }
                   3130:                     $cfile = $resurl;
                   3131:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3132:                 $incourse = 1;
                   3133:                 $forceview = 1;
                   3134:                 if ($symb) {
                   3135:                     my ($map,$id,$res)=&decode_symb($symb);
                   3136:                     $env{'request.symb'} = $symb;
                   3137:                     $cfile = &clutter($res);
                   3138:                 } else {
                   3139:                     $cfile = $env{'form.suppurl'};
                   3140:                     $cfile =~ s{^http://}{};
                   3141:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   3142:                 }
1.1172.2.31  raeburn  3143:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3144:                 if ($env{'form.forceedit'}) {
                   3145:                     $forceview = 1;
                   3146:                 } else {
                   3147:                     $forceedit = 1;
                   3148:                 }
                   3149:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3150:             }
                   3151:         }
                   3152:         if ($uploaded || $incourse) {
                   3153:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3154:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3155:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3156:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3157:             # Check that the user has permission to edit this resource
                   3158:             my $setpriv = 1;
                   3159:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3160:             if (defined($cfudom)) {
                   3161:                 $home=&homeserver($cfuname,$cfudom);
                   3162:                 $cfile=$file;
                   3163:             }
                   3164:         }
                   3165:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3166:             (($home ne '') && ($home ne 'no_host'))) {
                   3167:             my @ids=&current_machine_ids();
                   3168:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3169:                 $switchserver=1;
                   3170:             }
                   3171:         }
                   3172:     }
                   3173:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3174: }
                   3175: 
                   3176: sub is_course_upload {
                   3177:     my ($file,$cnum,$cdom) = @_;
                   3178:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3179:     $uploadpath =~ s{^\/}{};
                   3180:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3181:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3182:         return 1;
                   3183:     }
                   3184:     return;
                   3185: }
                   3186: 
                   3187: sub in_course {
                   3188:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3189:     if ($hideprivileged) {
                   3190:         my $skipuser;
1.1172.2.23  raeburn  3191:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3192:         my @possdoms = ($cdom);
                   3193:         if ($coursehash{'checkforpriv'}) {
                   3194:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3195:         }
                   3196:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3197:             $skipuser = 1;
                   3198:             if ($coursehash{'nothideprivileged'}) {
                   3199:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3200:                     my $user;
                   3201:                     if ($item =~ /:/) {
                   3202:                         $user = $item;
                   3203:                     } else {
                   3204:                         $user = join(':',split(/[\@]/,$item));
                   3205:                     }
                   3206:                     if ($user eq $uname.':'.$udom) {
                   3207:                         undef($skipuser);
                   3208:                         last;
                   3209:                     }
                   3210:                 }
                   3211:             }
                   3212:             if ($skipuser) {
                   3213:                 return 0;
                   3214:             }
                   3215:         }
                   3216:     }
                   3217:     $type ||= 'any';
                   3218:     if (!defined($cdom) || !defined($cnum)) {
                   3219:         my $cid  = $env{'request.course.id'};
                   3220:         $cdom = $env{'course.'.$cid.'.domain'};
                   3221:         $cnum = $env{'course.'.$cid.'.num'};
                   3222:     }
                   3223:     my $typesref;
                   3224:     if (($type eq 'any') || ($type eq 'all')) {
                   3225:         $typesref = ['active','previous','future'];
                   3226:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3227:         $typesref = [$type];
                   3228:     }
                   3229:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3230:                               $typesref,undef,[$cdom]);
                   3231:     my ($tmp) = keys(%roles);
                   3232:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3233:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3234:     if (@course_roles > 0) {
                   3235:         return 1;
                   3236:     }
                   3237:     return 0;
                   3238: }
                   3239: 
1.478     albertel 3240: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3241: # input: action, courseID, current domain, intended
1.637     raeburn  3242: #        path to file, source of file, instruction to parse file for objects,
                   3243: #        ref to hash for embedded objects,
                   3244: #        ref to hash for codebase of java objects.
1.1095    raeburn  3245: #        reference to scalar to accommodate mime type determined
                   3246: #          from File::MMagic if $parser = parse.
1.637     raeburn  3247: #
1.485     raeburn  3248: # output: url to file (if action was uploaddoc), 
                   3249: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3250: #
1.478     albertel 3251: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3252: # course.
1.477     raeburn  3253: #
1.478     albertel 3254: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3255: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3256: #          course's home server.
1.477     raeburn  3257: #
1.478     albertel 3258: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3259: #          be copied from $source (current location) to 
                   3260: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3261: #         and will then be copied to
                   3262: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3263: #         course's home server.
1.485     raeburn  3264: #
1.481     raeburn  3265: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3266: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3267: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3268: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3269: #         in course's home server.
1.637     raeburn  3270: #
1.477     raeburn  3271: 
                   3272: sub process_coursefile {
1.1095    raeburn  3273:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3274:         $mimetype)=@_;
1.477     raeburn  3275:     my $fetchresult;
1.638     albertel 3276:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3277:     if ($action eq 'propagate') {
1.638     albertel 3278:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3279: 			     $home);
1.481     raeburn  3280:     } else {
1.477     raeburn  3281:         my $fpath = '';
                   3282:         my $fname = $file;
1.478     albertel 3283:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3284:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3285:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3286:         if ($action eq 'copy') {
                   3287:             if ($source eq '') {
                   3288:                 $fetchresult = 'no source file';
                   3289:                 return $fetchresult;
                   3290:             } else {
                   3291:                 my $destination = $filepath.'/'.$fname;
                   3292:                 rename($source,$destination);
                   3293:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3294:                                  $home);
1.481     raeburn  3295:             }
                   3296:         } elsif ($action eq 'uploaddoc') {
1.1172.2.96  raeburn  3297:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3298:             print $fh $env{'form.'.$source};
1.481     raeburn  3299:             close($fh);
1.637     raeburn  3300:             if ($parser eq 'parse') {
1.1024    raeburn  3301:                 my $mm = new File::MMagic;
1.1095    raeburn  3302:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3303:                 if ($type eq 'text/html') {
1.1024    raeburn  3304:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3305:                     unless ($parse_result eq 'ok') {
                   3306:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3307:                     }
1.637     raeburn  3308:                 }
1.1095    raeburn  3309:                 if (ref($mimetype)) {
                   3310:                     $$mimetype = $type;
                   3311:                 } 
1.637     raeburn  3312:             }
1.477     raeburn  3313:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3314:                                  $home);
1.481     raeburn  3315:             if ($fetchresult eq 'ok') {
                   3316:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3317:             } else {
                   3318:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3319:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3320:                 return '/adm/notfound.html';
                   3321:             }
1.477     raeburn  3322:         }
                   3323:     }
1.485     raeburn  3324:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3325:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3326:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3327:     }
                   3328:     return $fetchresult;
                   3329: }
                   3330: 
1.637     raeburn  3331: sub build_filepath {
                   3332:     my ($fpath) = @_;
                   3333:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3334:     unless ($fpath eq '') {
                   3335:         my @parts=split('/',$fpath);
                   3336:         foreach my $part (@parts) {
                   3337:             $filepath.= '/'.$part;
                   3338:             if ((-e $filepath)!=1) {
                   3339:                 mkdir($filepath,0777);
                   3340:             }
                   3341:         }
                   3342:     }
                   3343:     return $filepath;
                   3344: }
                   3345: 
                   3346: sub store_edited_file {
1.638     albertel 3347:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3348:     my $file = $primary_url;
                   3349:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3350:     my $fpath = '';
                   3351:     my $fname = $file;
                   3352:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3353:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3354:     my $filepath = &build_filepath($fpath);
1.1172.2.96  raeburn  3355:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3356:     print $fh $content;
                   3357:     close($fh);
1.638     albertel 3358:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3359:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3360: 			  $home);
1.637     raeburn  3361:     if ($$fetchresult eq 'ok') {
                   3362:         return '/uploaded/'.$fpath.'/'.$fname;
                   3363:     } else {
1.638     albertel 3364:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3365: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3366:         return '/adm/notfound.html';
                   3367:     }
                   3368: }
                   3369: 
1.531     albertel 3370: sub clean_filename {
1.831     albertel 3371:     my ($fname,$args)=@_;
1.315     www      3372: # Replace Windows backslashes by forward slashes
1.257     www      3373:     $fname=~s/\\/\//g;
1.831     albertel 3374:     if (!$args->{'keep_path'}) {
                   3375:         # Get rid of everything but the actual filename
                   3376: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3377:     }
1.315     www      3378: # Replace spaces by underscores
                   3379:     $fname=~s/\s+/\_/g;
                   3380: # Replace all other weird characters by nothing
1.831     albertel 3381:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3382: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3383: # numbers
                   3384:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3385:     return $fname;
                   3386: }
1.1051    raeburn  3387: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3388: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3389: # image with the same aspect ratio as the original, but with dimensions which do 
                   3390: # not exceed $resizewidth and $resizeheight.
                   3391:  
1.984     neumanie 3392: sub resizeImage {
1.1051    raeburn  3393:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3394:     my $ima = Image::Magick->new;
                   3395:     my $resized;
                   3396:     if (-e $img_path) {
                   3397:         $ima->Read($img_path);
                   3398:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3399:             my $width = $ima->Get('width');
                   3400:             my $height = $ima->Get('height');
                   3401:             if ($width > $resizewidth) {
                   3402: 	        my $factor = $width/$resizewidth;
                   3403:                 my $newheight = $height/$factor;
                   3404:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3405:                 $resized = 1;
                   3406:             }
                   3407:         }
                   3408:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3409:             my $width = $ima->Get('width');
                   3410:             my $height = $ima->Get('height');
                   3411:             if ($height > $resizeheight) {
                   3412:                 my $factor = $height/$resizeheight;
                   3413:                 my $newwidth = $width/$factor;
                   3414:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3415:                 $resized = 1;
                   3416:             }
                   3417:         }
                   3418:         if ($resized) {
                   3419:             $ima->Write($img_path);
                   3420:         }
                   3421:     }
                   3422:     return;
1.977     amueller 3423: }
                   3424: 
1.608     albertel 3425: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3426: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3427: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3428: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3429: #                                    canceloverwrite, or ''. 
                   3430: #                   if 'coursedoc': upload to the current course
                   3431: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3432: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3433: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3434: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3435: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3436: #        $allfiles - reference to hash for embedded objects
                   3437: #        $codebase - reference to hash for codebase of java objects
                   3438: #        $desuname - username for permanent storage of uploaded file
                   3439: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3440: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3441: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3442: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3443: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3444: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3445: #                    from File::MMagic.
1.858     raeburn  3446: # 
1.686     albertel 3447: # output: url of file in userspace, or error: <message> 
                   3448: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3449: 
1.531     albertel 3450: sub userfileupload {
1.1090    raeburn  3451:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3452:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3453:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3454:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3455:     $fname=&clean_filename($fname);
1.1090    raeburn  3456:     # See if there is anything left
1.257     www      3457:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3458:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3459:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3460:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3461:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3462:         my $now = time;
1.1090    raeburn  3463:         my $filepath;
1.1095    raeburn  3464:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3465:              $filepath = 'tmp/helprequests/'.$now;
                   3466:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3467:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3468:                          '_'.$env{'user.domain'}.'/pending';
                   3469:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3470:             my ($docuname,$docudom);
1.1172.2.96  raeburn  3471:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3472:                 $docudom = $destudom;
                   3473:             } else {
                   3474:                 $docudom = $env{'user.domain'};
                   3475:             }
1.1172.2.96  raeburn  3476:             if ($destuname =~ /^$match_username$/) { 
1.1090    raeburn  3477:                 $docuname = $destuname;
                   3478:             } else {
                   3479:                 $docuname = $env{'user.name'};
                   3480:             }
                   3481:             if (exists($env{'form.group'})) {
                   3482:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3483:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3484:             }
                   3485:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3486:             if ($context eq 'canceloverwrite') {
                   3487:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3488:                 if (-e  $tempfile) {
                   3489:                     my @info = stat($tempfile);
                   3490:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3491:                         unlink($tempfile);
                   3492:                     }
                   3493:                 }
                   3494:                 return;
1.523     raeburn  3495:             }
                   3496:         }
1.1090    raeburn  3497:         # Create the directory if not present
1.741     raeburn  3498:         my @parts=split(/\//,$filepath);
                   3499:         my $fullpath = $perlvar{'lonDaemons'};
                   3500:         for (my $i=0;$i<@parts;$i++) {
                   3501:             $fullpath .= '/'.$parts[$i];
                   3502:             if ((-e $fullpath)!=1) {
                   3503:                 mkdir($fullpath,0777);
                   3504:             }
                   3505:         }
1.1172.2.96  raeburn  3506:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3507:         print $fh $env{'form.'.$formname};
                   3508:         close($fh);
1.1090    raeburn  3509:         if ($context eq 'existingfile') {
                   3510:             my @info = stat($fullpath.'/'.$fname);
                   3511:             return ($fullpath.'/'.$fname,$info[9]);
                   3512:         } else {
                   3513:             return $fullpath.'/'.$fname;
                   3514:         }
1.523     raeburn  3515:     }
1.995     raeburn  3516:     if ($subdir eq 'scantron') {
                   3517:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3518:     } else {
1.995     raeburn  3519:         $fname="$subdir/$fname";
                   3520:     }
1.1090    raeburn  3521:     if ($context eq 'coursedoc') {
1.638     albertel 3522: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3523: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3524:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3525:             return &finishuserfileupload($docuname,$docudom,
                   3526: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3527: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3528:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3529:         } else {
1.1172.2.21  raeburn  3530:             if ($env{'form.folder'}) {
                   3531:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3532:             }
1.638     albertel 3533:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3534: 				       $fname,$formname,$parser,
1.1095    raeburn  3535: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3536:         }
1.719     banghart 3537:     } elsif (defined($destuname)) {
                   3538:         my $docuname=$destuname;
                   3539:         my $docudom=$destudom;
1.860     raeburn  3540: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3541: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3542:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3543:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3544:     } else {
1.638     albertel 3545:         my $docuname=$env{'user.name'};
                   3546:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3547:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3548:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3549:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3550:         }
1.860     raeburn  3551: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3552: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3553:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3554:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3555:     }
1.271     www      3556: }
                   3557: 
                   3558: sub finishuserfileupload {
1.860     raeburn  3559:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3560:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3561:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3562:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3563:   
1.860     raeburn  3564:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3565:     $file=$fname;
                   3566:     if ($fname=~m|/|) {
                   3567:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3568: 	$path.=$fnamepath.'/';
                   3569:     }
1.259     www      3570:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3571:     my $count;
                   3572:     for ($count=4;$count<=$#parts;$count++) {
                   3573:         $filepath.="/$parts[$count]";
                   3574:         if ((-e $filepath)!=1) {
                   3575: 	    mkdir($filepath,0777);
                   3576:         }
                   3577:     }
1.984     neumanie 3578: 
1.258     www      3579: # Save the file
                   3580:     {
1.1172.2.96  raeburn  3581: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 3582: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3583: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3584: 	    return '/adm/notfound.html';
                   3585: 	}
1.1090    raeburn  3586:         if ($context eq 'overwrite') {
1.1117    foxr     3587:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3588:             my $target = $filepath.'/'.$file;
                   3589:             if (-e $source) {
                   3590:                 my @info = stat($source);
                   3591:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3592:                     unless (&File::Copy::move($source,$target)) {
                   3593:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3594:                         return "Moving from $source failed";
                   3595:                     }
                   3596:                 } else {
                   3597:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3598:                 }
                   3599:             } else {
                   3600:                 return "Temporary file: $source missing";
                   3601:             }
                   3602:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3603: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3604: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3605: 	    return '/adm/notfound.html';
                   3606: 	}
1.570     albertel 3607: 	close(FH);
1.1051    raeburn  3608:         if ($resizewidth && $resizeheight) {
                   3609:             my $mm = new File::MMagic;
                   3610:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3611:             if ($mime_type =~ m{^image/}) {
                   3612: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3613:             }  
1.977     amueller 3614: 	}
1.258     www      3615:     }
1.1152    raeburn  3616:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3617:         if (ref($mimetype)) {
                   3618:             if ($$mimetype eq '') {
                   3619:                 my $mm = new File::MMagic;
                   3620:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3621:                 $$mimetype = $type;
                   3622:             }
                   3623:         }
                   3624:     }
1.637     raeburn  3625:     if ($parser eq 'parse') {
1.1152    raeburn  3626:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3627:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3628:                                                        $allfiles,$codebase);
                   3629:             unless ($parse_result eq 'ok') {
                   3630:                 &logthis('Failed to parse '.$filepath.$file.
                   3631: 	   	         ' for embedded media: '.$parse_result); 
                   3632:             }
1.637     raeburn  3633:         }
                   3634:     }
1.860     raeburn  3635:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3636:         my $input = $filepath.'/'.$file;
                   3637:         my $output = $filepath.'/'.'tn-'.$file;
                   3638:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96  raeburn  3639:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   3640:         system({$args[0]} @args);
1.860     raeburn  3641:         if (-e $filepath.'/'.'tn-'.$file) {
                   3642:             $fetchthumb  = 1; 
                   3643:         }
                   3644:     }
1.858     raeburn  3645:  
1.259     www      3646: # Notify homeserver to grep it
                   3647: #
1.984     neumanie 3648:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3649:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3650:     if ($fetchresult eq 'ok') {
1.860     raeburn  3651:         if ($fetchthumb) {
                   3652:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3653:             if ($thumbresult ne 'ok') {
                   3654:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3655:                          $docuhome.': '.$thumbresult);
                   3656:             }
                   3657:         }
1.259     www      3658: #
1.258     www      3659: # Return the URL to it
1.494     albertel 3660:         return '/uploaded/'.$path.$file;
1.263     www      3661:     } else {
1.494     albertel 3662:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3663: 		 ': '.$fetchresult);
1.263     www      3664:         return '/adm/notfound.html';
1.858     raeburn  3665:     }
1.493     albertel 3666: }
                   3667: 
1.637     raeburn  3668: sub extract_embedded_items {
1.961     raeburn  3669:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3670:     my @state = ();
1.1164    raeburn  3671:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3672:     my %javafiles = (
                   3673:                       codebase => '',
                   3674:                       code => '',
                   3675:                       archive => ''
                   3676:                     );
                   3677:     my %mediafiles = (
                   3678:                       src => '',
                   3679:                       movie => '',
                   3680:                      );
1.648     raeburn  3681:     my $p;
                   3682:     if ($content) {
                   3683:         $p = HTML::LCParser->new($content);
                   3684:     } else {
1.961     raeburn  3685:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3686:     }
1.641     albertel 3687:     while (my $t=$p->get_token()) {
1.640     albertel 3688: 	if ($t->[0] eq 'S') {
                   3689: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3690: 	    push(@state, $tagname);
1.648     raeburn  3691:             if (lc($tagname) eq 'allow') {
                   3692:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3693:             }
1.640     albertel 3694: 	    if (lc($tagname) eq 'img') {
                   3695: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3696: 	    }
1.886     albertel 3697: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  3698:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   3699: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   3700:                 }
1.886     albertel 3701: 	    }
1.645     raeburn  3702:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3703:                 my $src;
1.645     raeburn  3704:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3705:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3706:                 } else {
1.1164    raeburn  3707:                     if ($attr->{'src'} ne '') {
                   3708:                         $src = $attr->{'src'};
                   3709:                         &add_filetype($allfiles,$src,'src');
                   3710:                     }
                   3711:                 }
                   3712:                 my $text = $p->get_trimmed_text();
                   3713:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3714:                     my @swfargs = split(/,/,$1);
                   3715:                     foreach my $item (@swfargs) {
                   3716:                         $item =~ s/["']//g;
                   3717:                         $item =~ s/^\s+//;
                   3718:                         $item =~ s/\s+$//;
                   3719:                     }
                   3720:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3721:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3722:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3723:                         } else {
                   3724:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3725:                         }
                   3726:                     }
1.645     raeburn  3727:                 }
                   3728:             }
                   3729:             if (lc($tagname) eq 'link') {
                   3730:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3731:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3732:                 }
                   3733:             }
1.640     albertel 3734: 	    if (lc($tagname) eq 'object' ||
                   3735: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3736: 		foreach my $item (keys(%javafiles)) {
                   3737: 		    $javafiles{$item} = '';
                   3738: 		}
1.1164    raeburn  3739:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3740:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3741:                 }
1.640     albertel 3742: 	    }
                   3743: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3744: 		my $name = lc($attr->{'name'});
                   3745: 		foreach my $item (keys(%javafiles)) {
                   3746: 		    if ($name eq $item) {
                   3747: 			$javafiles{$item} = $attr->{'value'};
                   3748: 			last;
                   3749: 		    }
                   3750: 		}
1.1164    raeburn  3751:                 my $pathfrom;
1.640     albertel 3752: 		foreach my $item (keys(%mediafiles)) {
                   3753: 		    if ($name eq $item) {
1.1164    raeburn  3754:                         $pathfrom = $attr->{'value'};
                   3755:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3756: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3757: 			last;
                   3758: 		    }
                   3759: 		}
1.1164    raeburn  3760:                 if ($name eq 'flashvars') {
                   3761:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3762:                 }
                   3763:                 if ($pathfrom ne '') {
                   3764:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3765:                                          $pathfrom);
                   3766:                 }
1.640     albertel 3767: 	    }
                   3768: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3769: 		foreach my $item (keys(%javafiles)) {
                   3770: 		    if ($attr->{$item}) {
                   3771: 			$javafiles{$item} = $attr->{$item};
                   3772: 			last;
                   3773: 		    }
                   3774: 		}
                   3775: 		foreach my $item (keys(%mediafiles)) {
                   3776: 		    if ($attr->{$item}) {
                   3777: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3778: 			last;
                   3779: 		    }
                   3780: 		}
1.1164    raeburn  3781:                 if (lc($tagname) eq 'embed') {
                   3782:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3783:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3784:                                              $attr->{'src'});
                   3785:                     }
                   3786:                 }
1.640     albertel 3787: 	    }
1.1172.2.35  raeburn  3788:             if (lc($tagname) eq 'iframe') {
                   3789:                 my $src = $attr->{'src'} ;
                   3790:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   3791:                     &add_filetype($allfiles,$src,'src');
                   3792:                 } elsif ($src =~ m{^/}) {
                   3793:                     if ($env{'request.course.id'}) {
                   3794:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3795:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3796:                         my $url = &hreflocation('',$fullpath);
                   3797:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   3798:                             my $relpath = $1;
                   3799:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   3800:                                 &add_filetype($allfiles,$1,'src');
                   3801:                             }
                   3802:                         }
                   3803:                     }
                   3804:                 }
                   3805:             }
1.1164    raeburn  3806:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  3807:                 pop(@state);
1.1164    raeburn  3808:             }
1.640     albertel 3809: 	} elsif ($t->[0] eq 'E') {
                   3810: 	    my ($tagname) = ($t->[1]);
                   3811: 	    if ($javafiles{'codebase'} ne '') {
                   3812: 		$javafiles{'codebase'} .= '/';
                   3813: 	    }  
                   3814: 	    if (lc($tagname) eq 'applet' ||
                   3815: 		lc($tagname) eq 'object' ||
                   3816: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3817: 		) {
                   3818: 		foreach my $item (keys(%javafiles)) {
                   3819: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3820: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3821: 			&add_filetype($allfiles,$file,$item);
                   3822: 		    }
                   3823: 		}
                   3824: 	    } 
                   3825: 	    pop @state;
                   3826: 	}
                   3827:     }
1.1164    raeburn  3828:     foreach my $id (sort(keys(%flashvars))) {
                   3829:         if ($shockwave{$id} ne '') {
                   3830:             my @pairs = split(/\&/,$flashvars{$id});
                   3831:             foreach my $pair (@pairs) {
                   3832:                 my ($key,$value) = split(/\=/,$pair);
                   3833:                 if ($key eq 'thumb') {
                   3834:                     &add_filetype($allfiles,$value,$key);
                   3835:                 } elsif ($key eq 'content') {
                   3836:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3837:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3838:                     if ($ext ne '') {
                   3839:                         &add_filetype($allfiles,$path.$value,$ext);
                   3840:                     }
                   3841:                 }
                   3842:             }
                   3843:         }
                   3844:     }
1.637     raeburn  3845:     return 'ok';
                   3846: }
                   3847: 
1.639     albertel 3848: sub add_filetype {
                   3849:     my ($allfiles,$file,$type)=@_;
                   3850:     if (exists($allfiles->{$file})) {
                   3851: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3852: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3853: 	}
                   3854:     } else {
                   3855: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3856:     }
                   3857: }
                   3858: 
1.1164    raeburn  3859: sub embedded_dependency {
                   3860:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3861:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3862:         if (($identifier ne '') &&
                   3863:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3864:             ($pathfrom ne '')) {
                   3865:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3866:             foreach my $dep (@{$related->{$identifier}}) {
                   3867:                 &add_filetype($allfiles,$path.$dep,'object');
                   3868:             }
                   3869:         }
                   3870:     }
                   3871:     return;
                   3872: }
                   3873: 
1.493     albertel 3874: sub removeuploadedurl {
1.984     neumanie 3875:     my ($url)=@_;	
                   3876:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3877:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3878: }
                   3879: 
                   3880: sub removeuserfile {
                   3881:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3882:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3883:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3884:     if ($result eq 'ok') {	
1.798     raeburn  3885:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3886:             my $metafile = $fname.'.meta';
                   3887:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3888: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3889:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3890:             my $sqlresult = 
1.823     albertel 3891:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3892:                                         'portfolio_metadata',$group,
                   3893:                                         'delete');
1.798     raeburn  3894:         }
                   3895:     }
                   3896:     return $result;
1.257     www      3897: }
1.15      www      3898: 
1.530     albertel 3899: sub mkdiruserfile {
                   3900:     my ($docuname,$docudom,$dir)=@_;
                   3901:     my $home=&homeserver($docuname,$docudom);
                   3902:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3903: }
                   3904: 
1.531     albertel 3905: sub renameuserfile {
                   3906:     my ($docuname,$docudom,$old,$new)=@_;
                   3907:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3908:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3909:                         &escape("$old").':'.&escape("$new"),$home);
                   3910:     if ($result eq 'ok') {
                   3911:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3912:             my $oldmeta = $old.'.meta';
                   3913:             my $newmeta = $new.'.meta';
                   3914:             my $metaresult = 
                   3915:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3916: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3917:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3918:             my $sqlresult = 
1.823     albertel 3919:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3920:                                         'portfolio_metadata',$group,
                   3921:                                         'delete');
1.798     raeburn  3922:         }
                   3923:     }
                   3924:     return $result;
1.531     albertel 3925: }
                   3926: 
1.14      www      3927: # ------------------------------------------------------------------------- Log
                   3928: 
                   3929: sub log {
                   3930:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3931:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3932: }
                   3933: 
                   3934: # ------------------------------------------------------------------ Course Log
1.352     www      3935: #
                   3936: # This routine flushes several buffers of non-mission-critical nature
                   3937: #
1.157     www      3938: 
                   3939: sub flushcourselogs {
1.352     www      3940:     &logthis('Flushing log buffers');
                   3941: #
                   3942: # course logs
                   3943: # This is a log of all transactions in a course, which can be used
                   3944: # for data mining purposes
                   3945: #
                   3946: # It also collects the courseid database, which lists last transaction
                   3947: # times and course titles for all courseids
                   3948: #
                   3949:     my %courseidbuffer=();
1.921     raeburn  3950:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3951:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3952: 		          &escape($courselogs{$crsid}),
                   3953: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3954: 	    delete $courselogs{$crsid};
                   3955:         } else {
                   3956:             &logthis('Failed to flush log buffer for '.$crsid);
                   3957:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3958:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3959:                         " exceeded maximum size, deleting.</font>");
                   3960:                delete $courselogs{$crsid};
                   3961:             }
1.352     www      3962:         }
1.920     raeburn  3963:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3964:             'description' => $coursedescrbuf{$crsid},
                   3965:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3966:             'type'        => $coursetypebuf{$crsid},
                   3967:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3968:         };
1.191     harris41 3969:     }
1.352     www      3970: #
                   3971: # Write course id database (reverse lookup) to homeserver of courses 
                   3972: # Is used in pickcourse
                   3973: #
1.840     albertel 3974:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3975:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3976:                                     $courseidbuffer{$crs_home},
                   3977:                                     $crs_home,'timeonly');
1.352     www      3978:     }
                   3979: #
                   3980: # File accesses
                   3981: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3982: #
1.449     matthew  3983:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3984:         if ($entry =~ /___count$/) {
                   3985:             my ($dom,$name);
1.807     albertel 3986:             ($dom,$name,undef)=
1.811     albertel 3987: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3988:             if (! defined($dom) || $dom eq '' || 
                   3989:                 ! defined($name) || $name eq '') {
1.620     albertel 3990:                 my $cid = $env{'request.course.id'};
                   3991:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3992:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3993:             }
1.450     matthew  3994:             my $value = $accesshash{$entry};
                   3995:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3996:             my %temphash=($url => $value);
1.449     matthew  3997:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3998:             if ($result eq 'ok') {
                   3999:                 delete $accesshash{$entry};
                   4000:             }
                   4001:         } else {
1.811     albertel 4002:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4003:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4004:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4005:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4006:                 delete $accesshash{$entry};
                   4007:             }
1.185     www      4008:         }
1.191     harris41 4009:     }
1.352     www      4010: #
                   4011: # Roles
                   4012: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4013: #
1.800     albertel 4014:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4015:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4016: 	    split(/\:/,$entry);
                   4017:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4018:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4019:                 $rudom,$runame) eq 'ok') {
                   4020: 	    delete $userrolehash{$entry};
                   4021:         }
                   4022:     }
1.662     raeburn  4023: #
1.1172.2.90  raeburn  4024: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4025: #
                   4026:     my %domrolebuffer = ();
1.1000    raeburn  4027:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4028:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4029:         if ($domrolebuffer{$rudom}) {
                   4030:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4031:                       '='.&escape($domainrolehash{$entry});
                   4032:         } else {
                   4033:             $domrolebuffer{$rudom}.=&escape($entry).
                   4034:                       '='.&escape($domainrolehash{$entry});
                   4035:         }
                   4036:         delete $domainrolehash{$entry};
                   4037:     }
                   4038:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  4039:         my %servers;
                   4040:         if (defined(&domain($dom,'primary'))) {
                   4041:             my $primary=&domain($dom,'primary');
                   4042:             my $hostname=&hostname($primary);
                   4043:             $servers{$primary} = $hostname;
                   4044:         } else {
                   4045:             %servers = &get_servers($dom,'library');
                   4046:         }
1.841     albertel 4047: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  4048: 	    if (&reply('domroleput:'.$dom.':'.
                   4049: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4050: 	        last;
                   4051: 	    } else {
1.841     albertel 4052: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4053: 	    }
1.662     raeburn  4054:         }
                   4055:     }
1.186     www      4056:     $dumpcount++;
1.157     www      4057: }
                   4058: 
                   4059: sub courselog {
                   4060:     my $what=shift;
1.158     www      4061:     $what=time.':'.$what;
1.620     albertel 4062:     unless ($env{'request.course.id'}) { return ''; }
                   4063:     $coursedombuf{$env{'request.course.id'}}=
                   4064:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4065:     $coursenumbuf{$env{'request.course.id'}}=
                   4066:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4067:     $coursehombuf{$env{'request.course.id'}}=
                   4068:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4069:     $coursedescrbuf{$env{'request.course.id'}}=
                   4070:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4071:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4072:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4073:     $courseownerbuf{$env{'request.course.id'}}=
                   4074:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4075:     $coursetypebuf{$env{'request.course.id'}}=
                   4076:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4077:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4078: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4079:     } else {
1.620     albertel 4080: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4081:     }
1.620     albertel 4082:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4083: 	&flushcourselogs();
                   4084:     }
1.158     www      4085: }
                   4086: 
                   4087: sub courseacclog {
                   4088:     my $fnsymb=shift;
1.620     albertel 4089:     unless ($env{'request.course.id'}) { return ''; }
                   4090:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4091:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4092:         $what.=':POST';
1.583     matthew  4093:         # FIXME: Probably ought to escape things....
1.800     albertel 4094: 	foreach my $key (keys(%env)) {
                   4095:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4096:                 my $formitem = $1;
                   4097:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4098:                     $what.=':'.$formitem.'='.$env{$key};
                   4099:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4100:                     $what.=':'.$formitem.'='.$env{$key};
                   4101:                 }
1.158     www      4102:             }
1.191     harris41 4103:         }
1.583     matthew  4104:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4105:         # FIXME: We should not be depending on a form parameter that someone
                   4106:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4107:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4108:             $what.= ':POST';
                   4109:             # FIXME: Probably ought to escape things....
                   4110:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4111:                                  'crsdiscuss') {
1.620     albertel 4112:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4113:             }
                   4114:         }
1.158     www      4115:     }
                   4116:     &courselog($what);
1.149     www      4117: }
                   4118: 
1.185     www      4119: sub countacc {
                   4120:     my $url=&declutter(shift);
1.458     matthew  4121:     return if (! defined($url) || $url eq '');
1.620     albertel 4122:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4123: #
                   4124: # Mark that this url was used in this course
                   4125: #
1.620     albertel 4126:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4127: #
                   4128: # Increase the access count for this resource in this child process
                   4129: #
1.281     www      4130:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4131:     $accesshash{$key}++;
1.185     www      4132: }
1.349     www      4133: 
1.361     www      4134: sub linklog {
                   4135:     my ($from,$to)=@_;
                   4136:     $from=&declutter($from);
                   4137:     $to=&declutter($to);
                   4138:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4139:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4140: }
1.1160    www      4141: 
                   4142: sub statslog {
                   4143:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4144:     if ($users<2) { return; }
                   4145:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4146:             'course'       => $env{'request.course.id'},
                   4147:             'sections'     => '"all"',
                   4148:             'num_students' => $users,
                   4149:             'part'         => $part,
                   4150:             'symb'         => $symb,
                   4151:             'mean_tries'   => $av_attempts,
                   4152:             'deg_of_diff'  => $degdiff});
                   4153:     foreach my $key (keys(%dynstore)) {
                   4154:         $accesshash{$key}=$dynstore{$key};
                   4155:     }
                   4156: }
1.361     www      4157:   
1.349     www      4158: sub userrolelog {
                   4159:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4160:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4161:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4162:        $userrolehash
                   4163:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4164:                     =$tend.':'.$tstart;
1.662     raeburn  4165:     }
1.1169    droeschl 4166:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4167:        $userrolehash
                   4168:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4169:                     =$tend.':'.$tstart;
                   4170:     }
1.1172.2.90  raeburn  4171:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4172:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4173:        $domainrolehash
                   4174:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4175:                     = $tend.':'.$tstart;
                   4176:     }
1.351     www      4177: }
                   4178: 
1.957     raeburn  4179: sub courserolelog {
                   4180:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4181:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4182:         my $cdom = $1;
                   4183:         my $cnum = $2;
                   4184:         my $sec = $3;
                   4185:         my $namespace = 'rolelog';
                   4186:         my %storehash = (
                   4187:                            role    => $trole,
                   4188:                            start   => $tstart,
                   4189:                            end     => $tend,
                   4190:                            selfenroll => $selfenroll,
                   4191:                            context    => $context,
                   4192:                         );
                   4193:         if ($trole eq 'gr') {
                   4194:             $namespace = 'groupslog';
                   4195:             $storehash{'group'} = $sec;
                   4196:         } else {
                   4197:             $storehash{'section'} = $sec;
                   4198:         }
                   4199:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4200:                    $domain,$cnum,$cdom);
                   4201:         if (($trole ne 'st') || ($sec ne '')) {
                   4202:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4203:         }
                   4204:     }
                   4205:     return;
                   4206: }
                   4207: 
1.1172.2.9  raeburn  4208: sub domainrolelog {
                   4209:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4210:     if ($area =~ m{^/($match_domain)/$}) {
                   4211:         my $cdom = $1;
                   4212:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4213:         my $namespace = 'rolelog';
                   4214:         my %storehash = (
                   4215:                            role    => $trole,
                   4216:                            start   => $tstart,
                   4217:                            end     => $tend,
                   4218:                            context => $context,
                   4219:                         );
                   4220:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4221:                    $domain,$domconfiguser,$cdom);
                   4222:     }
                   4223:     return;
                   4224: 
                   4225: }
                   4226: 
                   4227: sub coauthorrolelog {
                   4228:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4229:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4230:         my $audom = $1;
                   4231:         my $auname = $2;
                   4232:         my $namespace = 'rolelog';
                   4233:         my %storehash = (
                   4234:                            role    => $trole,
                   4235:                            start   => $tstart,
                   4236:                            end     => $tend,
                   4237:                            context => $context,
                   4238:                         );
                   4239:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4240:                    $domain,$auname,$audom);
                   4241:     }
                   4242:     return;
                   4243: }
                   4244: 
1.351     www      4245: sub get_course_adv_roles {
1.948     raeburn  4246:     my ($cid,$codes) = @_;
1.620     albertel 4247:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4248:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4249:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4250:     my %nothide=();
1.800     albertel 4251:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4252:         if ($user !~ /:/) {
                   4253: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4254:         } else {
                   4255:             $nothide{$user}=1;
                   4256:         }
1.470     www      4257:     }
1.1172.2.23  raeburn  4258:     my @possdoms = ($coursehash{'domain'});
                   4259:     if ($coursehash{'checkforpriv'}) {
                   4260:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4261:     }
1.351     www      4262:     my %returnhash=();
                   4263:     my %dumphash=
                   4264:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4265:     my $now=time;
1.997     raeburn  4266:     my %privileged;
1.1000    raeburn  4267:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4268: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4269:         if (($tstart) && ($tstart<0)) { next; }
                   4270:         if (($tend) && ($tend<$now)) { next; }
                   4271:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4272:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4273: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4274:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4275:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4276: 	if ($role eq 'cr') { next; }
1.948     raeburn  4277:         if ($codes) {
                   4278:             if ($section) { $role .= ':'.$section; }
                   4279:             if ($returnhash{$role}) {
                   4280:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4281:             } else {
                   4282:                 $returnhash{$role}=$username.':'.$domain;
                   4283:             }
1.351     www      4284:         } else {
1.988     raeburn  4285:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4286:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4287:             if ($returnhash{$key}) {
                   4288: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4289:             } else {
                   4290:                 $returnhash{$key}=$username.':'.$domain;
                   4291:             }
1.351     www      4292:         }
1.948     raeburn  4293:     }
1.400     www      4294:     return %returnhash;
                   4295: }
                   4296: 
                   4297: sub get_my_roles {
1.937     raeburn  4298:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4299:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4300:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4301:     my (%dumphash,%nothide);
1.1086    raeburn  4302:     if ($context eq 'userroles') {
1.1166    raeburn  4303:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4304:     } else {
1.1172.2.23  raeburn  4305:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4306:         if ($hidepriv) {
                   4307:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4308:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4309:                 if ($user !~ /:/) {
                   4310:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4311:                 } else {
                   4312:                     $nothide{$user} = 1;
                   4313:                 }
                   4314:             }
                   4315:         }
1.858     raeburn  4316:     }
1.400     www      4317:     my %returnhash=();
                   4318:     my $now=time;
1.999     raeburn  4319:     my %privileged;
1.800     albertel 4320:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4321:         my ($role,$tend,$tstart);
                   4322:         if ($context eq 'userroles') {
1.1149    raeburn  4323:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4324: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4325:         } else {
                   4326:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4327:         }
1.400     www      4328:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4329:         my $status = 'active';
1.939     raeburn  4330:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4331:             $status = 'previous';
                   4332:         } 
                   4333:         if (($tstart) && ($now<$tstart)) {
                   4334:             $status = 'future';
                   4335:         }
                   4336:         if (ref($types) eq 'ARRAY') {
                   4337:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4338:                 next;
                   4339:             } 
                   4340:         } else {
                   4341:             if ($status ne 'active') {
                   4342:                 next;
                   4343:             }
                   4344:         }
1.867     raeburn  4345:         my ($rolecode,$username,$domain,$section,$area);
                   4346:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  4347:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4348:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4349:         } else {
                   4350:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4351:         }
1.832     raeburn  4352:         if (ref($roledoms) eq 'ARRAY') {
                   4353:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4354:                 next;
                   4355:             }
                   4356:         }
                   4357:         if (ref($roles) eq 'ARRAY') {
                   4358:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4359:                 if ($role =~ /^cr\//) {
                   4360:                     if (!grep(/^cr$/,@{$roles})) {
                   4361:                         next;
                   4362:                     }
1.1104    raeburn  4363:                 } elsif ($role =~ /^gr\//) {
                   4364:                     if (!grep(/^gr$/,@{$roles})) {
                   4365:                         next;
                   4366:                     }
1.922     raeburn  4367:                 } else {
                   4368:                     next;
                   4369:                 }
1.832     raeburn  4370:             }
1.867     raeburn  4371:         }
1.937     raeburn  4372:         if ($hidepriv) {
1.1172.2.23  raeburn  4373:             my @privroles = ('dc','su');
1.999     raeburn  4374:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  4375:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4376:             } else {
1.1172.2.23  raeburn  4377:                 my $possdoms = [$domain];
                   4378:                 if (ref($roledoms) eq 'ARRAY') {
                   4379:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  4380:                 }
1.1172.2.23  raeburn  4381:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4382:                     if (!$nothide{$username.':'.$domain}) {
                   4383:                         next;
                   4384:                     }
                   4385:                 }
1.937     raeburn  4386:             }
                   4387:         }
1.933     raeburn  4388:         if ($withsec) {
                   4389:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4390:                 $tstart.':'.$tend;
                   4391:         } else {
                   4392:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4393:         }
1.832     raeburn  4394:     }
1.373     www      4395:     return %returnhash;
1.399     www      4396: }
                   4397: 
1.1172.2.89  raeburn  4398: sub get_all_adhocroles {
                   4399:     my ($dom) = @_;
                   4400:     my @roles_by_num = ();
                   4401:     my %domdefaults = &get_domain_defaults($dom);
                   4402:     my (%description,%access_in_dom,%access_info);
                   4403:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   4404:         my $count = 0;
                   4405:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   4406:         my %ordered;
                   4407:         foreach my $role (sort(keys(%domcurrent))) {
                   4408:             my ($order,$desc,$access_in_dom);
                   4409:             if (ref($domcurrent{$role}) eq 'HASH') {
                   4410:                 $order = $domcurrent{$role}{'order'};
                   4411:                 $desc = $domcurrent{$role}{'desc'};
                   4412:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   4413:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   4414:             }
                   4415:             if ($order eq '') {
                   4416:                 $order = $count;
                   4417:             }
                   4418:             $ordered{$order} = $role;
                   4419:             if ($desc ne '') {
                   4420:                 $description{$role} = $desc;
                   4421:             } else {
                   4422:                 $description{$role}= $role;
                   4423:             }
                   4424:             $count++;
                   4425:         }
                   4426:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   4427:             push(@roles_by_num,$ordered{$item});
                   4428:         }
                   4429:     }
                   4430:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   4431: }
                   4432: 
                   4433: sub get_my_adhocroles {
                   4434:     my ($cid,$checkreg) = @_;
                   4435:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   4436:     if ($env{'request.course.id'} eq $cid) {
                   4437:         $cdom = $env{'course.'.$cid.'.domain'};
                   4438:         $cnum = $env{'course.'.$cid.'.num'};
                   4439:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   4440:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   4441:         $cdom = $1;
                   4442:         $cnum = $2;
                   4443:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   4444:                                      $cdom,$cnum);
                   4445:     }
                   4446:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   4447:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4448:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   4449:         if ($rosterhash{$user} ne '') {
                   4450:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   4451:             return ([],{}) if ($type eq 'auto');
                   4452:         }
                   4453:     }
                   4454:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  4455:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  4456:             my $then=$env{'user.login.time'};
                   4457:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  4458:             if (!$update) {
                   4459:                 $update = $then;
                   4460:             }
                   4461:             my @liveroles;
                   4462:             foreach my $role ('dh','da') {
                   4463:                 if ($env{"user.role.$role./$cdom/"}) {
                   4464:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   4465:                     my $limit = $update;
                   4466:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   4467:                         $limit = $then;
                   4468:                     }
                   4469:                     my $activerole = 1;
                   4470:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   4471:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   4472:                     if ($activerole) {
                   4473:                         push(@liveroles,$role);
                   4474:                     }
                   4475:                 }
                   4476:             }
                   4477:             if (@liveroles) {
1.1172.2.89  raeburn  4478:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   4479:                     my ($accessref,$accessinfo,%access_in_dom);
                   4480:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   4481:                     if (ref($roles_by_num) eq 'ARRAY') {
                   4482:                         if (@{$roles_by_num}) {
                   4483:                             my %settings;
                   4484:                             if ($env{'request.course.id'} eq $cid) {
                   4485:                                 foreach my $envkey (keys(%env)) {
                   4486:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   4487:                                         $settings{$1} = $env{$envkey};
                   4488:                                     }
                   4489:                                 }
                   4490:                             } else {
                   4491:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   4492:                             }
                   4493:                             my %setincrs;
                   4494:                             if ($settings{'internal.adhocaccess'}) {
                   4495:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   4496:                             }
                   4497:                             my @statuses;
                   4498:                             if ($env{'environment.inststatus'}) {
                   4499:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   4500:                             }
                   4501:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4502:                             if (ref($accessref) eq 'HASH') {
                   4503:                                 %access_in_dom = %{$accessref};
                   4504:                             }
                   4505:                             foreach my $role (@{$roles_by_num}) {
                   4506:                                 my ($curraccess,@okstatus,@personnel);
                   4507:                                 if ($setincrs{$role}) {
                   4508:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   4509:                                     if ($curraccess eq 'status') {
                   4510:                                         @okstatus = split(/\&/,$rest);
                   4511:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4512:                                         @personnel = split(/\&/,$rest);
                   4513:                                     }
                   4514:                                 } else {
                   4515:                                     $curraccess = $access_in_dom{$role};
                   4516:                                     if (ref($accessinfo) eq 'HASH') {
                   4517:                                         if ($curraccess eq 'status') {
                   4518:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4519:                                                 @okstatus = @{$accessinfo->{$role}};
                   4520:                                             }
                   4521:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4522:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4523:                                                 @personnel = @{$accessinfo->{$role}};
                   4524:                                             }
                   4525:                                         }
                   4526:                                     }
                   4527:                                 }
                   4528:                                 if ($curraccess eq 'none') {
                   4529:                                     next;
                   4530:                                 } elsif ($curraccess eq 'all') {
                   4531:                                     push(@possroles,$role);
1.1172.2.90  raeburn  4532:                                 } elsif ($curraccess eq 'dh') {
                   4533:                                     if (grep(/^dh$/,@liveroles)) {
                   4534:                                         push(@possroles,$role);
                   4535:                                     } else {
                   4536:                                         next;
                   4537:                                     }
                   4538:                                 } elsif ($curraccess eq 'da') {
                   4539:                                     if (grep(/^da$/,@liveroles)) {
                   4540:                                         push(@possroles,$role);
                   4541:                                     } else {
                   4542:                                         next;
                   4543:                                     }
1.1172.2.89  raeburn  4544:                                 } elsif ($curraccess eq 'status') {
                   4545:                                     if (@okstatus) {
                   4546:                                         if (!@statuses) {
                   4547:                                             if (grep(/^default$/,@okstatus)) {
                   4548:                                                 push(@possroles,$role);
                   4549:                                             }
                   4550:                                         } else {
                   4551:                                             foreach my $status (@okstatus) {
                   4552:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   4553:                                                     push(@possroles,$role);
                   4554:                                                     last;
                   4555:                                                 }
                   4556:                                             }
                   4557:                                         }
                   4558:                                     }
                   4559:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4560:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   4561:                                         if ($curraccess eq 'exc') {
                   4562:                                             push(@possroles,$role);
                   4563:                                         }
                   4564:                                     } elsif ($curraccess eq 'inc') {
                   4565:                                         push(@possroles,$role);
                   4566:                                     }
                   4567:                                 }
                   4568:                             }
                   4569:                         }
                   4570:                     }
                   4571:                 }
                   4572:             }
                   4573:         }
                   4574:     }
                   4575:     unless (ref($description) eq 'HASH') {
                   4576:         if (ref($roles_by_num) eq 'ARRAY') {
                   4577:             my %desc;
                   4578:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   4579:             $description = \%desc;
                   4580:         } else {
                   4581:             $description = {};
                   4582:         }
                   4583:     }
                   4584:     return (\@possroles,$description);
                   4585: }
                   4586: 
1.399     www      4587: # ----------------------------------------------------- Frontpage Announcements
                   4588: #
                   4589: #
                   4590: 
                   4591: sub postannounce {
                   4592:     my ($server,$text)=@_;
1.844     albertel 4593:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4594:     unless ($text=~/\w/) { $text=''; }
                   4595:     return &reply('setannounce:'.&escape($text),$server);
                   4596: }
                   4597: 
                   4598: sub getannounce {
1.448     albertel 4599: 
1.1172.2.96  raeburn  4600:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4601: 	my $announcement='';
1.800     albertel 4602: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4603: 	close($fh);
1.399     www      4604: 	if ($announcement=~/\w/) { 
                   4605: 	    return 
                   4606:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4607:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4608: 	} else {
                   4609: 	    return '';
                   4610: 	}
                   4611:     } else {
                   4612: 	return '';
                   4613:     }
1.351     www      4614: }
1.353     www      4615: 
                   4616: # ---------------------------------------------------------- Course ID routines
                   4617: # Deal with domain's nohist_courseid.db files
                   4618: #
                   4619: 
                   4620: sub courseidput {
1.921     raeburn  4621:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4622:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4623:     my $outcome;
                   4624:     if ($caller eq 'timeonly') {
                   4625:         my $cids = '';
                   4626:         foreach my $item (keys(%$storehash)) {
                   4627:             $cids.=&escape($item).'&';
                   4628:         }
                   4629:         $cids=~s/\&$//;
                   4630:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4631:                           $coursehome);       
                   4632:     } else {
                   4633:         my $items = '';
                   4634:         foreach my $item (keys(%$storehash)) {
                   4635:             $items.= &escape($item).'='.
                   4636:                      &freeze_escape($$storehash{$item}).'&';
                   4637:         }
                   4638:         $items=~s/\&$//;
                   4639:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4640:                           $coursehome);
1.918     raeburn  4641:     }
                   4642:     if ($outcome eq 'unknown_cmd') {
                   4643:         my $what;
                   4644:         foreach my $cid (keys(%$storehash)) {
                   4645:             $what .= &escape($cid).'=';
1.921     raeburn  4646:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4647:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4648:             }
                   4649:             $what =~ s/\:$/&/;
                   4650:         }
                   4651:         $what =~ s/\&$//;  
                   4652:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4653:     } else {
                   4654:         return $outcome;
                   4655:     }
1.353     www      4656: }
                   4657: 
                   4658: sub courseiddump {
1.921     raeburn  4659:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4660:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4661:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  4662:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  4663:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  4664:     my $as_hash = 1;
                   4665:     my %returnhash;
                   4666:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4667:     my %libserv = &all_library();
                   4668:     foreach my $tryserver (keys(%libserv)) {
                   4669:         if ( (  $hostidflag == 1 
                   4670: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4671: 	     || (!defined($hostidflag)) ) {
                   4672: 
1.918     raeburn  4673: 	    if (($domfilter eq '') ||
                   4674: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  4675:                 my $rep;
                   4676:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   4677:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   4678:                         join(":", (&host_domain($tryserver), $sincefilter,
                   4679:                                 &escape($descfilter), &escape($instcodefilter),
                   4680:                                 &escape($ownerfilter), &escape($coursefilter),
                   4681:                                 &escape($typefilter), &escape($regexp_ok),
                   4682:                                 $as_hash, &escape($selfenrollonly),
                   4683:                                 &escape($catfilter), $showhidden, $caller,
                   4684:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   4685:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  4686:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   4687:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  4688:                 } else {
                   4689:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4690:                              $sincefilter.':'.&escape($descfilter).':'.
                   4691:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4692:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4693:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4694:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4695:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4696:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4697:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  4698:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   4699:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  4700:                 }
                   4701: 
1.918     raeburn  4702:                 my @pairs=split(/\&/,$rep);
                   4703:                 foreach my $item (@pairs) {
                   4704:                     my ($key,$value)=split(/\=/,$item,2);
                   4705:                     $key = &unescape($key);
                   4706:                     next if ($key =~ /^error: 2 /);
                   4707:                     my $result = &thaw_unescape($value);
                   4708:                     if (ref($result) eq 'HASH') {
                   4709:                         $returnhash{$key}=$result;
                   4710:                     } else {
1.921     raeburn  4711:                         my @responses = split(/:/,$value);
                   4712:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4713:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4714:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4715:                         }
1.1008    raeburn  4716:                     }
1.353     www      4717:                 }
                   4718:             }
                   4719:         }
                   4720:     }
                   4721:     return %returnhash;
                   4722: }
                   4723: 
1.1055    raeburn  4724: sub courselastaccess {
                   4725:     my ($cdom,$cnum,$hostidref) = @_;
                   4726:     my %returnhash;
                   4727:     if ($cdom && $cnum) {
                   4728:         my $chome = &homeserver($cnum,$cdom);
                   4729:         if ($chome ne 'no_host') {
                   4730:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4731:             &extract_lastaccess(\%returnhash,$rep);
                   4732:         }
                   4733:     } else {
                   4734:         if (!$cdom) { $cdom=''; }
                   4735:         my %libserv = &all_library();
                   4736:         foreach my $tryserver (keys(%libserv)) {
                   4737:             if (ref($hostidref) eq 'ARRAY') {
                   4738:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4739:             } 
                   4740:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4741:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4742:                 &extract_lastaccess(\%returnhash,$rep);
                   4743:             }
                   4744:         }
                   4745:     }
                   4746:     return %returnhash;
                   4747: }
                   4748: 
                   4749: sub extract_lastaccess {
                   4750:     my ($returnhash,$rep) = @_;
                   4751:     if (ref($returnhash) eq 'HASH') {
                   4752:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4753:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4754:                  $rep eq '') {
                   4755:             my @pairs=split(/\&/,$rep);
                   4756:             foreach my $item (@pairs) {
                   4757:                 my ($key,$value)=split(/\=/,$item,2);
                   4758:                 $key = &unescape($key);
                   4759:                 next if ($key =~ /^error: 2 /);
                   4760:                 $returnhash->{$key} = &thaw_unescape($value);
                   4761:             }
                   4762:         }
                   4763:     }
                   4764:     return;
                   4765: }
                   4766: 
1.658     raeburn  4767: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4768: 
                   4769: sub dcmailput {
1.685     raeburn  4770:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4771:     my $status = &Apache::lonnet::critical(
1.740     www      4772:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4773:        &escape($message),$server);
1.662     raeburn  4774:     return $status;
                   4775: }
                   4776: 
1.658     raeburn  4777: sub dcmaildump {
                   4778:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4779:     my %returnhash=();
1.846     albertel 4780: 
                   4781:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4782:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4783:                                                          &escape($enddate).':';
                   4784: 	my @esc_senders=map { &escape($_)} @$senders;
                   4785: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4786: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4787:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4788:             if (($key) && ($value)) {
                   4789:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4790:             }
                   4791:         }
                   4792:     }
                   4793:     return %returnhash;
                   4794: }
1.662     raeburn  4795: # ---------------------------------------------------------- Domain roles
                   4796: 
                   4797: sub get_domain_roles {
                   4798:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4799:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4800:         $startdate = '.';
                   4801:     }
1.1018    raeburn  4802:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4803:         $enddate = '.';
                   4804:     }
1.922     raeburn  4805:     my $rolelist;
                   4806:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  4807:         $rolelist = join('&',@{$roles});
1.922     raeburn  4808:     }
1.662     raeburn  4809:     my %personnel = ();
1.841     albertel 4810: 
                   4811:     my %servers = &get_servers($dom,'library');
                   4812:     foreach my $tryserver (keys(%servers)) {
                   4813: 	%{$personnel{$tryserver}}=();
                   4814: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4815: 					    &escape($startdate).':'.
                   4816: 					    &escape($enddate).':'.
                   4817: 					    &escape($rolelist), $tryserver))) {
                   4818: 	    my ($key,$value) = split(/\=/,$line,2);
                   4819: 	    if (($key) && ($value)) {
                   4820: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4821: 	    }
                   4822: 	}
1.662     raeburn  4823:     }
                   4824:     return %personnel;
                   4825: }
1.658     raeburn  4826: 
1.1172.2.89  raeburn  4827: sub get_active_domroles {
                   4828:     my ($dom,$roles) = @_;
                   4829:     return () unless (ref($roles) eq 'ARRAY');
                   4830:     my $now = time;
                   4831:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   4832:     my %domroles;
                   4833:     foreach my $server (keys(%dompersonnel)) {
                   4834:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   4835:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   4836:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   4837:         }
                   4838:     }
                   4839:     return %domroles;
                   4840: }
                   4841: 
1.1057    www      4842: # ----------------------------------------------------------- Interval timing 
1.149     www      4843: 
1.1153    www      4844: {
                   4845: # Caches needed for speedup of navmaps
                   4846: # We don't want to cache this for very long at all (5 seconds at most)
                   4847: # 
                   4848: # The user for whom we cache
                   4849: my $cachedkey='';
                   4850: # The cached times for this user
                   4851: my %cachedtimes=();
                   4852: # When this was last done
1.1172.2.66  raeburn  4853: my $cachedtime='';
1.1153    www      4854: 
                   4855: sub load_all_first_access {
1.1154    raeburn  4856:     my ($uname,$udom)=@_;
1.1156    www      4857:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  4858:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4859:         return;
                   4860:     }
                   4861:     $cachedtime=time;
                   4862:     $cachedkey=$uname.':'.$udom;
                   4863:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4864: }
                   4865: 
1.504     albertel 4866: sub get_first_access {
1.1162    raeburn  4867:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4868:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4869:     if ($argsymb) { $symb=$argsymb; }
                   4870:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4871:     if ($argmap) { $map = $argmap; }
1.926     albertel 4872:     if ($type eq 'course') {
                   4873: 	$res='course';
                   4874:     } elsif ($type eq 'map') {
1.588     albertel 4875: 	$res=&symbread($map);
                   4876:     } else {
                   4877: 	$res=$symb;
                   4878:     }
1.1153    www      4879:     &load_all_first_access($uname,$udom);
                   4880:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4881: }
                   4882: 
                   4883: sub set_first_access {
1.1162    raeburn  4884:     my ($type,$interval)=@_;
1.790     albertel 4885:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4886:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4887:     if ($type eq 'course') {
                   4888: 	$res='course';
                   4889:     } elsif ($type eq 'map') {
1.588     albertel 4890: 	$res=&symbread($map);
                   4891:     } else {
                   4892: 	$res=$symb;
                   4893:     }
1.1153    www      4894:     $cachedkey='';
1.1162    raeburn  4895:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4896:     if (!$firstaccess) {
1.1162    raeburn  4897:         my $start = time;
                   4898: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4899:                           $udom,$uname);
                   4900:         if ($putres eq 'ok') {
                   4901:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4902:                  $udom,$uname); 
                   4903:             &appenv(
                   4904:                      {
                   4905:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4906:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4907:                      }
                   4908:                   );
1.1172.2.97  raeburn  4909:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   4910:                 $cachedtimes{"$courseid\0$res"} = $start;
                   4911:             }
1.1162    raeburn  4912:         }
                   4913:         return $putres;
1.505     albertel 4914:     }
                   4915:     return 'already_set';
1.504     albertel 4916: }
1.1153    www      4917: }
1.1172.2.32  raeburn  4918: 
                   4919: sub checkout {
                   4920:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   4921:     my $now=time;
                   4922:     my $lonhost=$perlvar{'lonHostID'};
                   4923:     my $infostr=&escape(
                   4924:                  'CHECKOUTTOKEN&'.
                   4925:                  $tuname.'&'.
                   4926:                  $tudom.'&'.
                   4927:                  $tcrsid.'&'.
                   4928:                  $symb.'&'.
                   4929:                  $now.'&'.$ENV{'REMOTE_ADDR'});
                   4930:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   4931:     if ($token=~/^error\:/) {
                   4932:         &logthis("<font color=\"blue\">WARNING: ".
                   4933:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4934:                  "</font>");
                   4935:         return '';
                   4936:     }
                   4937: 
                   4938:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   4939:     $token=~tr/a-z/A-Z/;
                   4940: 
                   4941:     my %infohash=('resource.0.outtoken' => $token,
                   4942:                   'resource.0.checkouttime' => $now,
                   4943:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
                   4944: 
                   4945:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   4946:        return '';
                   4947:     } else {
                   4948:         &logthis("<font color=\"blue\">WARNING: ".
                   4949:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4950:                  "</font>");
                   4951:     }
                   4952: 
                   4953:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   4954:                          &escape('Checkout '.$infostr.' - '.
                   4955:                                                  $token)) ne 'ok') {
                   4956:         return '';
                   4957:     } else {
                   4958:         &logthis("<font color=\"blue\">WARNING: ".
                   4959:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4960:                  "</font>");
                   4961:     }
                   4962:     return $token;
                   4963: }
                   4964: 
                   4965: # ------------------------------------------------------------ Check in an item
                   4966: 
                   4967: sub checkin {
                   4968:     my $token=shift;
                   4969:     my $now=time;
                   4970:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   4971:     $lonhost=~tr/A-Z/a-z/;
                   4972:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   4973:     $dtoken=~s/\W/\_/g;
                   4974:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   4975:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   4976: 
                   4977:     unless (($tuname) && ($tudom)) {
                   4978:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   4979:         return '';
                   4980:     }
                   4981: 
                   4982:     unless (&allowed('mgr',$tcrsid)) {
                   4983:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   4984:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   4985:         return '';
                   4986:     }
                   4987: 
                   4988:     my %infohash=('resource.0.intoken' => $token,
                   4989:                   'resource.0.checkintime' => $now,
                   4990:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
                   4991: 
                   4992:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   4993:        return '';
                   4994:     }
                   4995: 
                   4996:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   4997:                          &escape('Checkin - '.$token)) ne 'ok') {
                   4998:         return '';
                   4999:     }
                   5000: 
                   5001:     return ($symb,$tuname,$tudom,$tcrsid);
                   5002: }
                   5003: 
1.110     www      5004: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5005: 
                   5006: sub expirespread {
                   5007:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5008:     my $cid=$env{'request.course.id'}; 
1.110     www      5009:     if ($cid) {
                   5010:        my $now=time;
                   5011:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5012:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5013:                             $env{'course.'.$cid.'.num'}.
1.110     www      5014: 	        	    ':nohist_expirationdates:'.
                   5015:                             &escape($key).'='.$now,
1.620     albertel 5016:                             $env{'course.'.$cid.'.home'})
1.110     www      5017:     }
                   5018:     return 'ok';
1.14      www      5019: }
                   5020: 
1.109     www      5021: # ----------------------------------------------------- Devalidate Spreadsheets
                   5022: 
                   5023: sub devalidate {
1.325     www      5024:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5025:     my $cid=$env{'request.course.id'}; 
1.109     www      5026:     if ($cid) {
1.391     matthew  5027:         # delete the stored spreadsheets for
                   5028:         # - the student level sheet of this user in course's homespace
                   5029:         # - the assessment level sheet for this resource 
                   5030:         #   for this user in user's homespace
1.553     albertel 5031: 	# - current conditional state info
1.325     www      5032: 	my $key=$uname.':'.$udom.':';
1.109     www      5033:         my $status=
1.299     matthew  5034: 	    &del('nohist_calculatedsheets',
1.391     matthew  5035: 		 [$key.'studentcalc:'],
1.620     albertel 5036: 		 $env{'course.'.$cid.'.domain'},
                   5037: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5038: 		.' '.
                   5039: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5040: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5041:         unless ($status eq 'ok ok') {
                   5042:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5043:                     $uname.' at '.$udom.' for '.
1.109     www      5044: 		    $symb.': '.$status);
1.133     albertel 5045:         }
1.553     albertel 5046: 	&delenv('user.state.'.$cid);
1.109     www      5047:     }
                   5048: }
                   5049: 
1.265     albertel 5050: sub get_scalar {
                   5051:     my ($string,$end) = @_;
                   5052:     my $value;
                   5053:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5054: 	$value = $1;
                   5055:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5056: 	$value = $1;
                   5057:     }
                   5058:     return &unescape($value);
                   5059: }
                   5060: 
                   5061: sub array2str {
                   5062:   my (@array) = @_;
                   5063:   my $result=&arrayref2str(\@array);
                   5064:   $result=~s/^__ARRAY_REF__//;
                   5065:   $result=~s/__END_ARRAY_REF__$//;
                   5066:   return $result;
                   5067: }
                   5068: 
1.204     albertel 5069: sub arrayref2str {
                   5070:   my ($arrayref) = @_;
1.265     albertel 5071:   my $result='__ARRAY_REF__';
1.204     albertel 5072:   foreach my $elem (@$arrayref) {
1.265     albertel 5073:     if(ref($elem) eq 'ARRAY') {
                   5074:       $result.=&arrayref2str($elem).'&';
                   5075:     } elsif(ref($elem) eq 'HASH') {
                   5076:       $result.=&hashref2str($elem).'&';
                   5077:     } elsif(ref($elem)) {
                   5078:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5079:     } else {
                   5080:       $result.=&escape($elem).'&';
                   5081:     }
                   5082:   }
                   5083:   $result=~s/\&$//;
1.265     albertel 5084:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5085:   return $result;
                   5086: }
                   5087: 
1.168     albertel 5088: sub hash2str {
1.204     albertel 5089:   my (%hash) = @_;
                   5090:   my $result=&hashref2str(\%hash);
1.265     albertel 5091:   $result=~s/^__HASH_REF__//;
                   5092:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5093:   return $result;
                   5094: }
                   5095: 
                   5096: sub hashref2str {
                   5097:   my ($hashref)=@_;
1.265     albertel 5098:   my $result='__HASH_REF__';
1.800     albertel 5099:   foreach my $key (sort(keys(%$hashref))) {
                   5100:     if (ref($key) eq 'ARRAY') {
                   5101:       $result.=&arrayref2str($key).'=';
                   5102:     } elsif (ref($key) eq 'HASH') {
                   5103:       $result.=&hashref2str($key).'=';
                   5104:     } elsif (ref($key)) {
1.265     albertel 5105:       $result.='=';
1.800     albertel 5106:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5107:     } else {
1.1132    raeburn  5108: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5109:     }
                   5110: 
1.800     albertel 5111:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5112:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5113:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5114:       $result.=&hashref2str($hashref->{$key}).'&';
                   5115:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5116:        $result.='&';
1.800     albertel 5117:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5118:     } else {
1.800     albertel 5119:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5120:     }
                   5121:   }
1.168     albertel 5122:   $result=~s/\&$//;
1.265     albertel 5123:   $result .= '__END_HASH_REF__';
1.168     albertel 5124:   return $result;
                   5125: }
                   5126: 
                   5127: sub str2hash {
1.265     albertel 5128:     my ($string)=@_;
                   5129:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5130:     return %$hash;
                   5131: }
                   5132: 
                   5133: sub str2hashref {
1.168     albertel 5134:   my ($string) = @_;
1.265     albertel 5135: 
                   5136:   my %hash;
                   5137: 
                   5138:   if($string !~ /^__HASH_REF__/) {
                   5139:       if (! ($string eq '' || !defined($string))) {
                   5140: 	  $hash{'error'}='Not hash reference';
                   5141:       }
                   5142:       return (\%hash, $string);
                   5143:   }
                   5144: 
                   5145:   $string =~ s/^__HASH_REF__//;
                   5146: 
                   5147:   while($string !~ /^__END_HASH_REF__/) {
                   5148:       #key
                   5149:       my $key='';
                   5150:       if($string =~ /^__HASH_REF__/) {
                   5151:           ($key, $string)=&str2hashref($string);
                   5152:           if(defined($key->{'error'})) {
                   5153:               $hash{'error'}='Bad data';
                   5154:               return (\%hash, $string);
                   5155:           }
                   5156:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5157:           ($key, $string)=&str2arrayref($string);
                   5158:           if($key->[0] eq 'Array reference error') {
                   5159:               $hash{'error'}='Bad data';
                   5160:               return (\%hash, $string);
                   5161:           }
                   5162:       } else {
                   5163:           $string =~ s/^(.*?)=//;
1.267     albertel 5164: 	  $key=&unescape($1);
1.265     albertel 5165:       }
                   5166:       $string =~ s/^=//;
                   5167: 
                   5168:       #value
                   5169:       my $value='';
                   5170:       if($string =~ /^__HASH_REF__/) {
                   5171:           ($value, $string)=&str2hashref($string);
                   5172:           if(defined($value->{'error'})) {
                   5173:               $hash{'error'}='Bad data';
                   5174:               return (\%hash, $string);
                   5175:           }
                   5176:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5177:           ($value, $string)=&str2arrayref($string);
                   5178:           if($value->[0] eq 'Array reference error') {
                   5179:               $hash{'error'}='Bad data';
                   5180:               return (\%hash, $string);
                   5181:           }
                   5182:       } else {
                   5183: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5184:       }
                   5185:       $string =~ s/^&//;
                   5186: 
                   5187:       $hash{$key}=$value;
1.204     albertel 5188:   }
1.265     albertel 5189: 
                   5190:   $string =~ s/^__END_HASH_REF__//;
                   5191: 
                   5192:   return (\%hash, $string);
1.204     albertel 5193: }
                   5194: 
                   5195: sub str2array {
1.265     albertel 5196:     my ($string)=@_;
                   5197:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5198:     return @$array;
                   5199: }
                   5200: 
                   5201: sub str2arrayref {
1.204     albertel 5202:   my ($string) = @_;
1.265     albertel 5203:   my @array;
                   5204: 
                   5205:   if($string !~ /^__ARRAY_REF__/) {
                   5206:       if (! ($string eq '' || !defined($string))) {
                   5207: 	  $array[0]='Array reference error';
                   5208:       }
                   5209:       return (\@array, $string);
                   5210:   }
                   5211: 
                   5212:   $string =~ s/^__ARRAY_REF__//;
                   5213: 
                   5214:   while($string !~ /^__END_ARRAY_REF__/) {
                   5215:       my $value='';
                   5216:       if($string =~ /^__HASH_REF__/) {
                   5217:           ($value, $string)=&str2hashref($string);
                   5218:           if(defined($value->{'error'})) {
                   5219:               $array[0] ='Array reference error';
                   5220:               return (\@array, $string);
                   5221:           }
                   5222:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5223:           ($value, $string)=&str2arrayref($string);
                   5224:           if($value->[0] eq 'Array reference error') {
                   5225:               $array[0] ='Array reference error';
                   5226:               return (\@array, $string);
                   5227:           }
                   5228:       } else {
                   5229: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5230:       }
                   5231:       $string =~ s/^&//;
                   5232: 
                   5233:       push(@array, $value);
1.191     harris41 5234:   }
1.265     albertel 5235: 
                   5236:   $string =~ s/^__END_ARRAY_REF__//;
                   5237: 
                   5238:   return (\@array, $string);
1.168     albertel 5239: }
                   5240: 
1.167     albertel 5241: # -------------------------------------------------------------------Temp Store
                   5242: 
1.168     albertel 5243: sub tmpreset {
                   5244:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5245:   if (!$symb) {
                   5246:     $symb=&symbread();
1.620     albertel 5247:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5248:   }
                   5249:   $symb=escape($symb);
                   5250: 
1.620     albertel 5251:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5252:   $namespace=~s/\//\_/g;
                   5253:   $namespace=~s/\W//g;
                   5254: 
1.620     albertel 5255:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5256:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5257:   if ($domain eq 'public' && $stuname eq 'public') {
                   5258:       $stuname=$ENV{'REMOTE_ADDR'};
                   5259:   }
1.1117    foxr     5260:   my $path=LONCAPA::tempdir();
1.168     albertel 5261:   my %hash;
                   5262:   if (tie(%hash,'GDBM_File',
                   5263: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5264: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5265:     foreach my $key (keys(%hash)) {
1.180     albertel 5266:       if ($key=~ /:$symb/) {
1.168     albertel 5267: 	delete($hash{$key});
                   5268:       }
                   5269:     }
                   5270:   }
                   5271: }
                   5272: 
1.167     albertel 5273: sub tmpstore {
1.168     albertel 5274:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5275: 
                   5276:   if (!$symb) {
                   5277:     $symb=&symbread();
1.620     albertel 5278:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5279:   }
                   5280:   $symb=escape($symb);
                   5281: 
                   5282:   if (!$namespace) {
                   5283:     # I don't think we would ever want to store this for a course.
                   5284:     # it seems this will only be used if we don't have a course.
1.620     albertel 5285:     #$namespace=$env{'request.course.id'};
1.168     albertel 5286:     #if (!$namespace) {
1.620     albertel 5287:       $namespace=$env{'request.state'};
1.168     albertel 5288:     #}
                   5289:   }
                   5290:   $namespace=~s/\//\_/g;
                   5291:   $namespace=~s/\W//g;
1.620     albertel 5292:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5293:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5294:   if ($domain eq 'public' && $stuname eq 'public') {
                   5295:       $stuname=$ENV{'REMOTE_ADDR'};
                   5296:   }
1.168     albertel 5297:   my $now=time;
                   5298:   my %hash;
1.1117    foxr     5299:   my $path=LONCAPA::tempdir();
1.168     albertel 5300:   if (tie(%hash,'GDBM_File',
                   5301: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5302: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5303:     $hash{"version:$symb"}++;
                   5304:     my $version=$hash{"version:$symb"};
                   5305:     my $allkeys=''; 
                   5306:     foreach my $key (keys(%$storehash)) {
                   5307:       $allkeys.=$key.':';
1.591     albertel 5308:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5309:     }
                   5310:     $hash{"$version:$symb:timestamp"}=$now;
                   5311:     $allkeys.='timestamp';
                   5312:     $hash{"$version:keys:$symb"}=$allkeys;
                   5313:     if (untie(%hash)) {
                   5314:       return 'ok';
                   5315:     } else {
                   5316:       return "error:$!";
                   5317:     }
                   5318:   } else {
                   5319:     return "error:$!";
                   5320:   }
                   5321: }
1.167     albertel 5322: 
1.168     albertel 5323: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5324: 
1.168     albertel 5325: sub tmprestore {
                   5326:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5327: 
1.168     albertel 5328:   if (!$symb) {
                   5329:     $symb=&symbread();
1.620     albertel 5330:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5331:   }
                   5332:   $symb=escape($symb);
                   5333: 
1.620     albertel 5334:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5335: 
1.620     albertel 5336:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5337:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5338:   if ($domain eq 'public' && $stuname eq 'public') {
                   5339:       $stuname=$ENV{'REMOTE_ADDR'};
                   5340:   }
1.168     albertel 5341:   my %returnhash;
                   5342:   $namespace=~s/\//\_/g;
                   5343:   $namespace=~s/\W//g;
                   5344:   my %hash;
1.1117    foxr     5345:   my $path=LONCAPA::tempdir();
1.168     albertel 5346:   if (tie(%hash,'GDBM_File',
                   5347: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5348: 	  &GDBM_READER(),0640)) {
1.168     albertel 5349:     my $version=$hash{"version:$symb"};
                   5350:     $returnhash{'version'}=$version;
                   5351:     my $scope;
                   5352:     for ($scope=1;$scope<=$version;$scope++) {
                   5353:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5354:       my @keys=split(/:/,$vkeys);
                   5355:       my $key;
                   5356:       $returnhash{"$scope:keys"}=$vkeys;
                   5357:       foreach $key (@keys) {
1.591     albertel 5358: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5359: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5360:       }
                   5361:     }
1.168     albertel 5362:     if (!(untie(%hash))) {
                   5363:       return "error:$!";
                   5364:     }
                   5365:   } else {
                   5366:     return "error:$!";
                   5367:   }
                   5368:   return %returnhash;
1.167     albertel 5369: }
                   5370: 
1.9       www      5371: # ----------------------------------------------------------------------- Store
                   5372: 
                   5373: sub store {
1.1172.2.64  raeburn  5374:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5375:     my $home='';
                   5376: 
1.168     albertel 5377:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5378: 
1.213     www      5379:     $symb=&symbclean($symb);
1.122     albertel 5380:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5381: 
1.620     albertel 5382:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5383:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5384: 
                   5385:     &devalidate($symb,$stuname,$domain);
1.109     www      5386: 
                   5387:     $symb=escape($symb);
1.187     www      5388:     if (!$namespace) { 
1.620     albertel 5389:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5390:           return ''; 
                   5391:        } 
                   5392:     }
1.620     albertel 5393:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5394: 
                   5395:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5396:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5397: 
1.12      www      5398:     my $namevalue='';
1.800     albertel 5399:     foreach my $key (keys(%$storehash)) {
                   5400:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5401:     }
1.12      www      5402:     $namevalue=~s/\&$//;
1.187     www      5403:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  5404:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5405: }
                   5406: 
1.47      www      5407: # -------------------------------------------------------------- Critical Store
                   5408: 
                   5409: sub cstore {
1.1172.2.64  raeburn  5410:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5411:     my $home='';
                   5412: 
1.168     albertel 5413:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5414: 
1.213     www      5415:     $symb=&symbclean($symb);
1.122     albertel 5416:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5417: 
1.620     albertel 5418:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5419:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5420: 
                   5421:     &devalidate($symb,$stuname,$domain);
1.109     www      5422: 
                   5423:     $symb=escape($symb);
1.187     www      5424:     if (!$namespace) { 
1.620     albertel 5425:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5426:           return ''; 
                   5427:        } 
                   5428:     }
1.620     albertel 5429:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5430: 
                   5431:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5432:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5433: 
1.47      www      5434:     my $namevalue='';
1.800     albertel 5435:     foreach my $key (keys(%$storehash)) {
                   5436:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5437:     }
1.47      www      5438:     $namevalue=~s/\&$//;
1.187     www      5439:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5440:     return critical
1.1172.2.64  raeburn  5441:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5442: }
                   5443: 
1.9       www      5444: # --------------------------------------------------------------------- Restore
                   5445: 
                   5446: sub restore {
1.124     www      5447:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5448:     my $home='';
                   5449: 
1.168     albertel 5450:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5451: 
1.122     albertel 5452:     if (!$symb) {
1.1172.2.26  raeburn  5453:         return if ($namespace eq 'courserequests');
                   5454:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5455:     } else {
1.1172.2.26  raeburn  5456:         unless ($namespace eq 'courserequests') {
                   5457:             $symb=&escape(&symbclean($symb));
                   5458:         }
1.122     albertel 5459:     }
1.188     www      5460:     if (!$namespace) { 
1.620     albertel 5461:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5462:           return ''; 
                   5463:        } 
                   5464:     }
1.620     albertel 5465:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5466:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5467:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5468:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5469: 
1.12      www      5470:     my %returnhash=();
1.800     albertel 5471:     foreach my $line (split(/\&/,$answer)) {
                   5472: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5473:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5474:     }
1.75      www      5475:     my $version;
                   5476:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5477:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5478:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5479:        }
1.75      www      5480:     }
1.13      www      5481:     return %returnhash;
1.34      www      5482: }
                   5483: 
                   5484: # ---------------------------------------------------------- Course Description
1.1118    foxr     5485: #
                   5486: #  
1.34      www      5487: 
                   5488: sub coursedescription {
1.731     albertel 5489:     my ($courseid,$args)=@_;
1.34      www      5490:     $courseid=~s/^\///;
1.49      www      5491:     $courseid=~s/\_/\//g;
1.34      www      5492:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5493:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5494:     my $normalid=$cdomain.'_'.$cnum;
                   5495:     # need to always cache even if we get errors otherwise we keep 
                   5496:     # trying and trying and trying to get the course description.
                   5497:     my %envhash=();
                   5498:     my %returnhash=();
1.731     albertel 5499:     
                   5500:     my $expiretime=600;
                   5501:     if ($env{'request.course.id'} eq $normalid) {
                   5502: 	$expiretime=120;
                   5503:     }
                   5504: 
                   5505:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5506:     if (!$args->{'freshen_cache'}
                   5507: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5508: 	foreach my $key (keys(%env)) {
                   5509: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5510: 	    my ($setting) = $1;
                   5511: 	    $returnhash{$setting} = $env{$key};
                   5512: 	}
                   5513: 	return %returnhash;
                   5514:     }
                   5515: 
1.1118    foxr     5516:     # get the data again
                   5517: 
1.731     albertel 5518:     if (!$args->{'one_time'}) {
                   5519: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5520:     }
1.811     albertel 5521: 
1.34      www      5522:     if ($chome ne 'no_host') {
1.302     albertel 5523:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5524:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5525: 	   my $username = $env{'user.name'}; # Defult username
                   5526: 	   if(defined $args->{'user'}) {
                   5527: 	       $username = $args->{'user'};
                   5528: 	   }
1.129     albertel 5529:            $returnhash{'home'}= $chome;
                   5530: 	   $returnhash{'domain'} = $cdomain;
                   5531: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5532:            if (!defined($returnhash{'type'})) {
                   5533:                $returnhash{'type'} = 'Course';
                   5534:            }
1.130     albertel 5535:            while (my ($name,$value) = each %returnhash) {
1.53      www      5536:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5537:            }
1.270     www      5538:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5539:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5540: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5541:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5542:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5543:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5544:        }
                   5545:     }
1.731     albertel 5546:     if (!$args->{'one_time'}) {
1.949     raeburn  5547: 	&appenv(\%envhash);
1.731     albertel 5548:     }
1.302     albertel 5549:     return %returnhash;
1.461     www      5550: }
                   5551: 
1.1080    raeburn  5552: sub update_released_required {
                   5553:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5554:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5555:         $cid = $env{'request.course.id'};
                   5556:         $cdom = $env{'course.'.$cid.'.domain'};
                   5557:         $cnum = $env{'course.'.$cid.'.num'};
                   5558:         $chome = $env{'course.'.$cid.'.home'};
                   5559:     }
                   5560:     if ($needsrelease) {
                   5561:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5562:         my $needsupdate;
                   5563:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5564:             $needsupdate = 1;
                   5565:         } else {
                   5566:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5567:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5568:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5569:                 $needsupdate = 1;
                   5570:             }
                   5571:         }
                   5572:         if ($needsupdate) {
                   5573:             my %needshash = (
                   5574:                              'internal.releaserequired' => $needsrelease,
                   5575:                             );
                   5576:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5577:             if ($putresult eq 'ok') {
                   5578:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5579:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5580:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5581:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5582:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5583:                 }
                   5584:             }
                   5585:         }
                   5586:     }
                   5587:     return;
                   5588: }
                   5589: 
1.461     www      5590: # -------------------------------------------------See if a user is privileged
                   5591: 
                   5592: sub privileged {
1.1172.2.23  raeburn  5593:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5594:     my $now = time;
1.1172.2.23  raeburn  5595:     my $roles;
                   5596:     if (ref($possroles) eq 'ARRAY') {
                   5597:         $roles = $possroles;
                   5598:     } else {
                   5599:         $roles = ['dc','su'];
                   5600:     }
                   5601:     if (ref($possdomains) eq 'ARRAY') {
                   5602:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5603:         foreach my $dom (@{$possdomains}) {
                   5604:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5605:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5606:                 foreach my $role (@{$roles}) {
                   5607:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5608:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5609:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5610:                             return 1 unless (($end && $end < $now) ||
                   5611:                                              ($start && $start > $now));
                   5612:                         }
                   5613:                     }
                   5614:                 }
                   5615:             }
                   5616:         }
                   5617:     } else {
                   5618:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5619:         my $now = time;
1.1170    droeschl 5620: 
1.1172.2.58  raeburn  5621:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5622:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  5623:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   5624:                 return 1 unless ($tend && $tend < $now)
                   5625:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5626:             }
1.1172.2.23  raeburn  5627:         }
                   5628:     }
1.461     www      5629:     return 0;
1.9       www      5630: }
1.1       albertel 5631: 
1.1172.2.23  raeburn  5632: sub privileged_by_domain {
                   5633:     my ($domains,$roles) = @_;
                   5634:     my %privileged = ();
                   5635:     my $cachetime = 60*60*24;
                   5636:     my $now = time;
                   5637:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5638:         return %privileged;
                   5639:     }
                   5640:     foreach my $dom (@{$domains}) {
                   5641:         next if (ref($privileged{$dom}) eq 'HASH');
                   5642:         my $needroles;
                   5643:         foreach my $role (@{$roles}) {
                   5644:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5645:             if (defined($cached)) {
                   5646:                 if (ref($result) eq 'HASH') {
                   5647:                     $privileged{$dom}{$role} = $result;
                   5648:                 }
                   5649:             } else {
                   5650:                 $needroles = 1;
                   5651:             }
                   5652:         }
                   5653:         if ($needroles) {
                   5654:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5655:             $privileged{$dom} = {};
                   5656:             foreach my $server (keys(%dompersonnel)) {
                   5657:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5658:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5659:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5660:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5661:                         next if ($end && $end < $now);
                   5662:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   5663:                             $dompersonnel{$server}{$item};
                   5664:                     }
                   5665:                 }
                   5666:             }
                   5667:             if (ref($privileged{$dom}) eq 'HASH') {
                   5668:                 foreach my $role (@{$roles}) {
                   5669:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5670:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5671:                     } else {
                   5672:                         my %hash = ();
                   5673:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5674:                     }
                   5675:                 }
                   5676:             }
                   5677:         }
                   5678:     }
                   5679:     return %privileged;
                   5680: }
                   5681: 
1.103     harris41 5682: # -------------------------------------------------------- Get user privileges
1.11      www      5683: 
                   5684: sub rolesinit {
1.1169    droeschl 5685:     my ($domain, $username) = @_;
                   5686:     my %userroles = ('user.login.time' => time);
                   5687:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5688: 
                   5689:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5690:     # also, blocking can be triggered by an activating timer
                   5691:     # it's saved in the user's %env.
                   5692:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5693:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5694:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5695:         %timerintchk, %timerintenv);
                   5696: 
1.1162    raeburn  5697:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5698:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5699:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5700:     }
1.1169    droeschl 5701: 
1.1162    raeburn  5702:     foreach my $key (keys(%timerinterval)) {
                   5703:         my ($cid,$rest) = split(/\0/,$key);
                   5704:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5705:     }
1.1169    droeschl 5706: 
1.11      www      5707:     my %allroles=();
1.1162    raeburn  5708:     my %allgroups=();
1.11      www      5709: 
1.1172.2.58  raeburn  5710:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5711:         my $role = $rolesdump{$area};
                   5712:         $area =~ s/\_\w\w$//;
                   5713: 
                   5714:         my ($trole, $tend, $tstart, $group_privs);
                   5715: 
                   5716:         if ($role =~ /^cr/) {
                   5717:         # Custom role, defined by a user 
                   5718:         # e.g., user.role.cr/msu/smith/mynewrole
                   5719:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5720:                 $trole = $1;
                   5721:                 ($tend, $tstart) = split('_', $2);
                   5722:             } else {
                   5723:                 $trole = $role;
                   5724:             }
                   5725:         } elsif ($role =~ m|^gr/|) {
                   5726:         # Role of member in a group, defined within a course/community
                   5727:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5728:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5729:             next if $tstart eq '-1';
                   5730:             ($trole, $group_privs) = split(/\//, $trole);
                   5731:             $group_privs = &unescape($group_privs);
                   5732:         } else {
                   5733:         # Just a normal role, defined in roles.tab
                   5734:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5735:         }
                   5736: 
                   5737:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5738:                  $username);
                   5739:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5740: 
                   5741:         # role expired or not available yet?
                   5742:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5743:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5744: 
                   5745:         next if $area eq '' or $trole eq '';
                   5746: 
                   5747:         my $spec = "$trole.$area";
                   5748:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5749: 
                   5750:         if ($trole =~ /^cr\//) {
                   5751:         # Custom role, defined by a user
                   5752:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5753:         } elsif ($trole eq 'gr') {
                   5754:         # Role of a member in a group, defined within a course/community
                   5755:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5756:             next;
                   5757:         } else {
                   5758:         # Normal role, defined in roles.tab
                   5759:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5760:         }
                   5761: 
                   5762:         my $cid = $tdomain.'_'.$trest;
                   5763:         unless ($firstaccchk{$cid}) {
                   5764:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5765:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5766:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5767:                         $coursetimerstarts{$cid}{$item}; 
                   5768:                 }
                   5769:             }
                   5770:             $firstaccchk{$cid} = 1;
                   5771:         }
                   5772:         unless ($timerintchk{$cid}) {
                   5773:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5774:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5775:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5776:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5777:                 }
1.12      www      5778:             }
1.1169    droeschl 5779:             $timerintchk{$cid} = 1;
1.191     harris41 5780:         }
1.11      www      5781:     }
1.1169    droeschl 5782: 
1.1172.2.91  raeburn  5783:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   5784:                                                           \%allroles, \%allgroups);
1.1169    droeschl 5785:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  5786:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 5787: 
1.1162    raeburn  5788:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5789: }
                   5790: 
1.567     raeburn  5791: sub set_arearole {
1.1172.2.19  raeburn  5792:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5793:     unless ($nolog) {
1.567     raeburn  5794: # log the associated role with the area
1.1172.2.19  raeburn  5795:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5796:     }
1.743     albertel 5797:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5798: }
                   5799: 
                   5800: sub custom_roleprivs {
                   5801:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5802:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  5803:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5804:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5805:         my ($rdummy,$roledef)=
                   5806:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5807:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5808:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5809:             if (defined($syspriv)) {
1.1043    raeburn  5810:                 if ($trest =~ /^$match_community$/) {
                   5811:                     $syspriv =~ s/bre\&S//; 
                   5812:                 }
1.567     raeburn  5813:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5814:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5815:             }
                   5816:             if ($tdomain ne '') {
                   5817:                 if (defined($dompriv)) {
                   5818:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5819:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5820:                 }
                   5821:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  5822:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   5823:                         my $rolename = $1;
                   5824:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   5825:                     }
1.567     raeburn  5826:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5827:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5828:                 }
                   5829:             }
                   5830:         }
                   5831:     }
                   5832: }
                   5833: 
1.1172.2.89  raeburn  5834: sub course_adhocrole_privs {
                   5835:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   5836:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   5837:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   5838:         my (%currprivs,%storeprivs);
                   5839:         foreach my $item (split(/:/,$coursepriv)) {
                   5840:             my ($priv,$restrict) = split(/\&/,$item);
                   5841:             $currprivs{$priv} = $restrict;
                   5842:         }
                   5843:         my (%possadd,%possremove,%full);
                   5844:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   5845:             my ($priv,$restrict)=split(/\&/,$item);
                   5846:             $full{$priv} = $restrict;
                   5847:         }
                   5848:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   5849:              next if ($item eq '');
                   5850:              my ($rule,$rest) = split(/=/,$item);
                   5851:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   5852:              foreach my $priv (split(/:/,$rest)) {
                   5853:                  if ($priv ne '') {
                   5854:                      if ($rule eq 'off') {
                   5855:                          $possremove{$priv} = 1;
                   5856:                      } else {
                   5857:                          $possadd{$priv} = 1;
                   5858:                      }
                   5859:                  }
                   5860:              }
                   5861:          }
                   5862:          foreach my $priv (sort(keys(%full))) {
                   5863:              if (exists($currprivs{$priv})) {
                   5864:                  unless (exists($possremove{$priv})) {
                   5865:                      $storeprivs{$priv} = $currprivs{$priv};
                   5866:                  }
                   5867:              } elsif (exists($possadd{$priv})) {
                   5868:                  $storeprivs{$priv} = $full{$priv};
                   5869:              }
                   5870:          }
                   5871:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   5872:      }
                   5873:      return $coursepriv;
                   5874: }
                   5875: 
1.678     raeburn  5876: sub group_roleprivs {
                   5877:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5878:     my $access = 1;
                   5879:     my $now = time;
                   5880:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5881:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5882:     if ($access) {
1.811     albertel 5883:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5884:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5885:     }
                   5886: }
1.567     raeburn  5887: 
                   5888: sub standard_roleprivs {
                   5889:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5890:     if (defined($pr{$trole.':s'})) {
                   5891:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5892:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5893:     }
                   5894:     if ($tdomain ne '') {
                   5895:         if (defined($pr{$trole.':d'})) {
                   5896:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5897:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5898:         }
                   5899:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5900:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5901:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5902:         }
                   5903:     }
                   5904: }
                   5905: 
                   5906: sub set_userprivs {
1.1064    raeburn  5907:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5908:     my $author=0;
                   5909:     my $adv=0;
1.1172.2.91  raeburn  5910:     my $rar=0;
1.678     raeburn  5911:     my %grouproles = ();
                   5912:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5913:         my @groupkeys; 
1.1000    raeburn  5914:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5915:             push(@groupkeys,$role);
                   5916:         }
                   5917:         if (ref($groups_roles) eq 'HASH') {
                   5918:             foreach my $key (keys(%{$groups_roles})) {
                   5919:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5920:                     push(@groupkeys,$key);
                   5921:                 }
                   5922:             }
                   5923:         }
                   5924:         if (@groupkeys > 0) {
                   5925:             foreach my $role (@groupkeys) {
                   5926:                 my ($trole,$area,$sec,$extendedarea);
                   5927:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5928:                     $trole = $1;
                   5929:                     $area = $2;
                   5930:                     $sec = $3;
                   5931:                     $extendedarea = $area.$sec;
                   5932:                     if (exists($$allgroups{$area})) {
                   5933:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5934:                             my $spec = $trole.'.'.$extendedarea;
                   5935:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5936:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5937:                         }
1.678     raeburn  5938:                     }
                   5939:                 }
                   5940:             }
                   5941:         }
                   5942:     }
1.800     albertel 5943:     foreach my $group (keys(%grouproles)) {
                   5944:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5945:     }
1.800     albertel 5946:     foreach my $role (keys(%{$allroles})) {
                   5947:         my %thesepriv;
1.941     raeburn  5948:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5949:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5950:             if ($item ne '') {
                   5951:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5952:                 if ($restrictions eq '') {
                   5953:                     $thesepriv{$privilege}='F';
                   5954:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5955:                     $thesepriv{$privilege}.=$restrictions;
                   5956:                 }
                   5957:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  5958:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  5959:             }
                   5960:         }
                   5961:         my $thesestr='';
1.1104    raeburn  5962:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5963: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5964: 	}
                   5965:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5966:     }
1.1172.2.91  raeburn  5967:     return ($author,$adv,$rar);
1.567     raeburn  5968: }
                   5969: 
1.994     raeburn  5970: sub role_status {
1.1104    raeburn  5971:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5972:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  5973:         my ($one,$two) = split(m{\./},$rolekey,2);
                   5974:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  5975:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  5976:             $$where = '/'.$two;
1.994     raeburn  5977:             $$trolecode=$$role.'.'.$$where;
                   5978:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5979:             $$tstatus='is';
1.1104    raeburn  5980:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5981:                 $$tstatus='future';
1.1034    raeburn  5982:                 if ($$tstart<$now) {
                   5983:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5984:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5985:                             my (%allroles,%allgroups,$group_privs,
                   5986:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5987:                             my %userroles = (
                   5988:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5989:                             );
1.1064    raeburn  5990:                             @rolecodes = ('cm'); 
1.1002    raeburn  5991:                             my $spec=$$role.'.'.$$where;
                   5992:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5993:                             if ($$role =~ /^cr\//) {
                   5994:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5995:                                 push(@rolecodes,'cr');
1.1002    raeburn  5996:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5997:                                 push(@rolecodes,$$role);
1.1002    raeburn  5998:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5999:                                                     $env{'user.name'});
1.1064    raeburn  6000:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6001:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6002:                                 $group_privs = &unescape($group_privs);
                   6003:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6004:                                 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  6005:                                 &get_groups_roles($tdomain,$trest,
                   6006:                                                   \%course_roles,\@rolecodes,
                   6007:                                                   \%groups_roles);
1.1002    raeburn  6008:                             } else {
1.1064    raeburn  6009:                                 push(@rolecodes,$$role);
1.1002    raeburn  6010:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6011:                             }
1.1172.2.91  raeburn  6012:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6013:                                                                    \%groups_roles);
1.1064    raeburn  6014:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  6015:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6016:                         }
                   6017:                     }
1.1034    raeburn  6018:                     $$tstatus = 'is';
1.1002    raeburn  6019:                 }
1.994     raeburn  6020:             }
                   6021:             if ($$tend) {
1.1104    raeburn  6022:                 if ($$tend<$update) {
1.994     raeburn  6023:                     $$tstatus='expired';
                   6024:                 } elsif ($$tend<$now) {
                   6025:                     $$tstatus='will_not';
                   6026:                 }
                   6027:             }
                   6028:         }
                   6029:     }
                   6030: }
                   6031: 
1.1104    raeburn  6032: sub get_groups_roles {
                   6033:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6034:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6035:                   (ref($rolecodes) eq 'ARRAY') && 
                   6036:                   (ref($groups_roles) eq 'HASH')); 
                   6037:     if (keys(%{$cdom_courseroles}) > 0) {
                   6038:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6039:         if ($cdom ne '' && $cnum ne '') {
                   6040:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6041:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6042:                     my $crsrole = $1;
                   6043:                     my $crssec = $2;
                   6044:                     if ($crsrole =~ /^cr/) {
                   6045:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6046:                             push(@{$rolecodes},'cr');
                   6047:                         }
                   6048:                     } else {
                   6049:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6050:                             push(@{$rolecodes},$crsrole);
                   6051:                         }
                   6052:                     }
                   6053:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6054:                     if ($crssec ne '') {
                   6055:                         $rolekey .= "/$crssec";
                   6056:                     }
                   6057:                     $rolekey .= './';
                   6058:                     $groups_roles->{$rolekey} = $rolecodes;
                   6059:                 }
                   6060:             }
                   6061:         }
                   6062:     }
                   6063:     return;
                   6064: }
                   6065: 
                   6066: sub delete_env_groupprivs {
                   6067:     my ($where,$courseroles,$possroles) = @_;
                   6068:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6069:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6070:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6071:         %{$courseroles->{$udom}} =
                   6072:             &get_my_roles('','','userroles',['active'],
                   6073:                           $possroles,[$udom],1);
                   6074:     }
                   6075:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6076:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6077:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6078:             my $area = '/'.$cdom.'/'.$cnum;
                   6079:             my $privkey = "user.priv.$crsrole.$area";
                   6080:             if ($crssec ne '') {
                   6081:                 $privkey .= '/'.$crssec;
                   6082:             }
                   6083:             $privkey .= ".$area/$group";
                   6084:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6085:         }
                   6086:     }
                   6087:     return;
                   6088: }
                   6089: 
1.994     raeburn  6090: sub check_adhoc_privs {
1.1172.2.86  raeburn  6091:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6092:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6093:     if ($sec) {
                   6094:         $cckey .= '/'.$sec;
                   6095:     }
1.1172.2.9  raeburn  6096:     my $setprivs;
1.994     raeburn  6097:     if ($env{$cckey}) {
                   6098:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6099:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6100:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6101:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6102:             $setprivs = 1;
1.994     raeburn  6103:         }
                   6104:     } else {
1.1172.2.87  raeburn  6105:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6106:         $setprivs = 1;
1.994     raeburn  6107:     }
1.1172.2.9  raeburn  6108:     return $setprivs;
1.994     raeburn  6109: }
                   6110: 
                   6111: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6112: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6113:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6114:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6115:     if ($sec ne '') {
                   6116:         $area .= '/'.$sec;
                   6117:     }
1.994     raeburn  6118:     my $spec = $role.'.'.$area;
                   6119:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6120:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6121:     my %rolehash = ();
1.1172.2.89  raeburn  6122:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6123:         my $rolename = $1;
1.1172.2.84  raeburn  6124:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6125:         my %domdef = &get_domain_defaults($dcdom);
                   6126:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6127:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6128:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6129:             }
                   6130:         }
1.1172.2.84  raeburn  6131:     } else {
                   6132:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6133:     }
1.1172.2.91  raeburn  6134:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6135:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6136:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6137:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6138:         &appenv( {'request.role'        => $spec,
                   6139:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6140:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6141:                  }
                   6142:                );
                   6143:         my $tadv=0;
                   6144:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6145:         &appenv({'request.role.adv'    => $tadv});
                   6146:     }
1.994     raeburn  6147: }
                   6148: 
1.12      www      6149: # --------------------------------------------------------------- get interface
                   6150: 
                   6151: sub get {
1.131     albertel 6152:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6153:    my $items='';
1.800     albertel 6154:    foreach my $item (@$storearr) {
                   6155:        $items.=&escape($item).'&';
1.191     harris41 6156:    }
1.12      www      6157:    $items=~s/\&$//;
1.620     albertel 6158:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6159:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6160:    my $uhome=&homeserver($uname,$udomain);
                   6161: 
1.133     albertel 6162:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6163:    my @pairs=split(/\&/,$rep);
1.273     albertel 6164:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6165:      return @pairs;
                   6166:    }
1.15      www      6167:    my %returnhash=();
1.42      www      6168:    my $i=0;
1.800     albertel 6169:    foreach my $item (@$storearr) {
                   6170:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6171:       $i++;
1.191     harris41 6172:    }
1.15      www      6173:    return %returnhash;
1.27      www      6174: }
                   6175: 
                   6176: # --------------------------------------------------------------- del interface
                   6177: 
                   6178: sub del {
1.133     albertel 6179:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6180:    my $items='';
1.800     albertel 6181:    foreach my $item (@$storearr) {
                   6182:        $items.=&escape($item).'&';
1.191     harris41 6183:    }
1.984     neumanie 6184: 
1.27      www      6185:    $items=~s/\&$//;
1.620     albertel 6186:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6187:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6188:    my $uhome=&homeserver($uname,$udomain);
                   6189:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6190: }
                   6191: 
                   6192: # -------------------------------------------------------------- dump interface
                   6193: 
1.1172.2.22  raeburn  6194: sub unserialize {
                   6195:     my ($rep, $escapedkeys) = @_;
                   6196: 
                   6197:     return {} if $rep =~ /^error/;
                   6198: 
                   6199:     my %returnhash=();
                   6200:     foreach my $item (split(/\&/,$rep)) {
                   6201:         my ($key, $value) = split(/=/, $item, 2);
                   6202:         $key = unescape($key) unless $escapedkeys;
                   6203:         next if $key =~ /^error: 2 /;
                   6204:         $returnhash{$key} = &thaw_unescape($value);
                   6205:     }
                   6206:     return \%returnhash;
                   6207: }
                   6208: 
                   6209: # see Lond::dump_with_regexp
                   6210: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6211: sub dump {
1.1172.2.22  raeburn  6212:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6213:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6214:     if (!$uname) { $uname=$env{'user.name'}; }
                   6215:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6216: 
1.1172.2.55  raeburn  6217:     if ($regexp) {
                   6218:         $regexp=&escape($regexp);
                   6219:     } else {
                   6220:         $regexp='.';
                   6221:     }
1.1172.2.22  raeburn  6222:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   6223:         # user is hosted on this machine
1.1172.2.55  raeburn  6224:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  6225:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  6226:         return %{&unserialize($reply, $escapedkeys)};
                   6227:     }
1.1166    raeburn  6228:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6229:     my @pairs=split(/\&/,$rep);
                   6230:     my %returnhash=();
1.1098    foxr     6231:     if (!($rep =~ /^error/ )) {
                   6232: 	foreach my $item (@pairs) {
                   6233: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  6234:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     6235: 	    next if ($key =~ /^error: 2 /);
                   6236: 	    $returnhash{$key}=&thaw_unescape($value);
                   6237: 	}
1.755     albertel 6238:     }
                   6239:     return %returnhash;
1.407     www      6240: }
                   6241: 
1.1098    foxr     6242: 
1.717     albertel 6243: # --------------------------------------------------------- dumpstore interface
                   6244: 
                   6245: sub dumpstore {
                   6246:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  6247:    # same as dump but keys must be escaped. They may contain colon separated
                   6248:    # lists of values that may themself contain colons (e.g. symbs).
                   6249:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6250: }
                   6251: 
1.407     www      6252: # -------------------------------------------------------------- keys interface
                   6253: 
                   6254: sub getkeys {
                   6255:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6256:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6257:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6258:    my $uhome=&homeserver($uname,$udomain);
                   6259:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6260:    my @keyarray=();
1.800     albertel 6261:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6262:       next if ($key =~ /^error: 2 /);
1.800     albertel 6263:       push(@keyarray,&unescape($key));
1.407     www      6264:    }
                   6265:    return @keyarray;
1.318     matthew  6266: }
                   6267: 
1.319     matthew  6268: # --------------------------------------------------------------- currentdump
                   6269: sub currentdump {
1.328     matthew  6270:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6271:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6272:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6273:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6274:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  6275:    my $rep;
                   6276: 
                   6277:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6278:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   6279:                    $courseid)));
                   6280:    } else {
                   6281:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6282:    }
                   6283: 
1.318     matthew  6284:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6285:    #
1.318     matthew  6286:    my %returnhash=();
1.319     matthew  6287:    #
                   6288:    if ($rep eq "unknown_cmd") { 
                   6289:        # an old lond will not know currentdump
                   6290:        # Do a dump and make it look like a currentdump
1.822     albertel 6291:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6292:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6293:        my %hash = @tmp;
                   6294:        @tmp=();
1.424     matthew  6295:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6296:    } else {
                   6297:        my @pairs=split(/\&/,$rep);
1.800     albertel 6298:        foreach my $pair (@pairs) {
                   6299:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6300:            my ($symb,$param) = split(/:/,$key);
                   6301:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6302:                                                         &thaw_unescape($value);
1.319     matthew  6303:        }
1.191     harris41 6304:    }
1.12      www      6305:    return %returnhash;
1.424     matthew  6306: }
                   6307: 
                   6308: sub convert_dump_to_currentdump{
                   6309:     my %hash = %{shift()};
                   6310:     my %returnhash;
                   6311:     # Code ripped from lond, essentially.  The only difference
                   6312:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6313:     # we might run in to problems with parameter names =~ /^v\./
                   6314:     while (my ($key,$value) = each(%hash)) {
                   6315:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6316: 	$symb  = &unescape($symb);
                   6317: 	$param = &unescape($param);
1.424     matthew  6318:         next if ($v eq 'version' || $symb eq 'keys');
                   6319:         next if (exists($returnhash{$symb}) &&
                   6320:                  exists($returnhash{$symb}->{$param}) &&
                   6321:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6322:         $returnhash{$symb}->{$param}=$value;
                   6323:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6324:     }
                   6325:     #
                   6326:     # Remove all of the keys in the hashes which keep track of
                   6327:     # the version of the parameter.
                   6328:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6329:         # use a foreach because we are going to delete from the hash.
                   6330:         foreach my $key (keys(%$param_hash)) {
                   6331:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6332:         }
                   6333:     }
                   6334:     return \%returnhash;
1.12      www      6335: }
                   6336: 
1.627     albertel 6337: # ------------------------------------------------------ critical inc interface
                   6338: 
                   6339: sub cinc {
                   6340:     return &inc(@_,'critical');
                   6341: }
                   6342: 
1.449     matthew  6343: # --------------------------------------------------------------- inc interface
                   6344: 
                   6345: sub inc {
1.627     albertel 6346:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6347:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6348:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6349:     my $uhome=&homeserver($uname,$udomain);
                   6350:     my $items='';
                   6351:     if (! ref($store)) {
                   6352:         # got a single value, so use that instead
                   6353:         $items = &escape($store).'=&';
                   6354:     } elsif (ref($store) eq 'SCALAR') {
                   6355:         $items = &escape($$store).'=&';        
                   6356:     } elsif (ref($store) eq 'ARRAY') {
                   6357:         $items = join('=&',map {&escape($_);} @{$store});
                   6358:     } elsif (ref($store) eq 'HASH') {
                   6359:         while (my($key,$value) = each(%{$store})) {
                   6360:             $items.= &escape($key).'='.&escape($value).'&';
                   6361:         }
                   6362:     }
                   6363:     $items=~s/\&$//;
1.627     albertel 6364:     if ($critical) {
                   6365: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6366:     } else {
                   6367: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6368:     }
1.449     matthew  6369: }
                   6370: 
1.12      www      6371: # --------------------------------------------------------------- put interface
                   6372: 
                   6373: sub put {
1.134     albertel 6374:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6375:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6376:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6377:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6378:    my $items='';
1.800     albertel 6379:    foreach my $item (keys(%$storehash)) {
                   6380:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6381:    }
1.12      www      6382:    $items=~s/\&$//;
1.134     albertel 6383:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6384: }
                   6385: 
1.631     albertel 6386: # ------------------------------------------------------------ newput interface
                   6387: 
                   6388: sub newput {
                   6389:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6390:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6391:    if (!$uname) { $uname=$env{'user.name'}; }
                   6392:    my $uhome=&homeserver($uname,$udomain);
                   6393:    my $items='';
                   6394:    foreach my $key (keys(%$storehash)) {
                   6395:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6396:    }
                   6397:    $items=~s/\&$//;
                   6398:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6399: }
                   6400: 
                   6401: # ---------------------------------------------------------  putstore interface
                   6402: 
1.524     raeburn  6403: sub putstore {
1.1172.2.59  raeburn  6404:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6405:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6406:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6407:    my $uhome=&homeserver($uname,$udomain);
                   6408:    my $items='';
1.715     albertel 6409:    foreach my $key (keys(%$storehash)) {
                   6410:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6411:    }
1.715     albertel 6412:    $items=~s/\&$//;
1.716     albertel 6413:    my $esc_symb=&escape($symb);
                   6414:    my $esc_v=&escape($version);
1.715     albertel 6415:    my $reply =
1.716     albertel 6416:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6417: 	      $uhome);
1.1172.2.59  raeburn  6418:    if (($tolog) && ($reply eq 'ok')) {
                   6419:        my $namevalue='';
                   6420:        foreach my $key (keys(%{$storehash})) {
                   6421:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6422:        }
                   6423:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6424:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6425:                      '&version='.$esc_v.
                   6426:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6427:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6428:    }
1.715     albertel 6429:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6430:        # gfall back to way things use to be done
1.715     albertel 6431:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6432: 			    $uname);
1.524     raeburn  6433:    }
1.715     albertel 6434:    return $reply;
                   6435: }
                   6436: 
                   6437: sub old_putstore {
1.716     albertel 6438:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6439:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6440:     if (!$uname) { $uname=$env{'user.name'}; }
                   6441:     my $uhome=&homeserver($uname,$udomain);
                   6442:     my %newstorehash;
1.800     albertel 6443:     foreach my $item (keys(%$storehash)) {
                   6444: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6445: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6446:     }
                   6447:     my $items='';
                   6448:     my %allitems = ();
1.800     albertel 6449:     foreach my $item (keys(%newstorehash)) {
                   6450: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6451: 	    my $key = $1.':keys:'.$2;
                   6452: 	    $allitems{$key} .= $3.':';
                   6453: 	}
1.800     albertel 6454: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6455:     }
1.800     albertel 6456:     foreach my $item (keys(%allitems)) {
                   6457: 	$allitems{$item} =~ s/\:$//;
                   6458: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6459:     }
                   6460:     $items=~s/\&$//;
                   6461:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6462: }
                   6463: 
1.47      www      6464: # ------------------------------------------------------ critical put interface
                   6465: 
                   6466: sub cput {
1.134     albertel 6467:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6468:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6469:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6470:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6471:    my $items='';
1.800     albertel 6472:    foreach my $item (keys(%$storehash)) {
                   6473:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6474:    }
1.47      www      6475:    $items=~s/\&$//;
1.134     albertel 6476:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6477: }
                   6478: 
                   6479: # -------------------------------------------------------------- eget interface
                   6480: 
                   6481: sub eget {
1.133     albertel 6482:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6483:    my $items='';
1.800     albertel 6484:    foreach my $item (@$storearr) {
                   6485:        $items.=&escape($item).'&';
1.191     harris41 6486:    }
1.12      www      6487:    $items=~s/\&$//;
1.620     albertel 6488:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6489:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6490:    my $uhome=&homeserver($uname,$udomain);
                   6491:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6492:    my @pairs=split(/\&/,$rep);
                   6493:    my %returnhash=();
1.42      www      6494:    my $i=0;
1.800     albertel 6495:    foreach my $item (@$storearr) {
                   6496:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6497:       $i++;
1.191     harris41 6498:    }
1.12      www      6499:    return %returnhash;
                   6500: }
                   6501: 
1.667     albertel 6502: # ------------------------------------------------------------ tmpput interface
                   6503: sub tmpput {
1.802     raeburn  6504:     my ($storehash,$server,$context)=@_;
1.667     albertel 6505:     my $items='';
1.800     albertel 6506:     foreach my $item (keys(%$storehash)) {
                   6507: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6508:     }
                   6509:     $items=~s/\&$//;
1.802     raeburn  6510:     if (defined($context)) {
                   6511:         $items .= ':'.&escape($context);
                   6512:     }
1.667     albertel 6513:     return &reply("tmpput:$items",$server);
                   6514: }
                   6515: 
                   6516: # ------------------------------------------------------------ tmpget interface
                   6517: sub tmpget {
1.688     albertel 6518:     my ($token,$server)=@_;
                   6519:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6520:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6521:     my %returnhash;
1.1172.2.85  raeburn  6522:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   6523:         return %returnhash;
                   6524:     }
1.667     albertel 6525:     foreach my $item (split(/\&/,$rep)) {
                   6526: 	my ($key,$value)=split(/=/,$item);
                   6527: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6528:     }
                   6529:     return %returnhash;
                   6530: }
                   6531: 
1.1113    raeburn  6532: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6533: sub tmpdel {
                   6534:     my ($token,$server)=@_;
                   6535:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6536:     return &reply("tmpdel:$token",$server);
                   6537: }
                   6538: 
1.1172.2.13  raeburn  6539: # ------------------------------------------------------------ get_timebased_id
                   6540: 
                   6541: sub get_timebased_id {
                   6542:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6543:         $maxtries) = @_;
                   6544:     my ($newid,$error,$dellock);
                   6545:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   6546:         return ('','ok','invalid call to get suffix');
                   6547:     }
                   6548: 
                   6549: # set defaults for any optional args for which values were not supplied
                   6550:     if ($who eq '') {
                   6551:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6552:     }
                   6553:     if (!$locktries) {
                   6554:         $locktries = 3;
                   6555:     }
                   6556:     if (!$maxtries) {
                   6557:         $maxtries = 10;
                   6558:     }
                   6559: 
                   6560:     if (($cdom eq '') || ($cnum eq '')) {
                   6561:         if ($env{'request.course.id'}) {
                   6562:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6563:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6564:         }
                   6565:         if (($cdom eq '') || ($cnum eq '')) {
                   6566:             return ('','ok','call to get suffix not in course context');
                   6567:         }
                   6568:     }
                   6569: 
                   6570: # construct locking item
                   6571:     my $lockhash = {
                   6572:                       $prefix."\0".'locked_'.$keyid => $who,
                   6573:                    };
                   6574:     my $tries = 0;
                   6575: 
                   6576: # attempt to get lock on nohist_$namespace file
                   6577:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6578:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6579:         $tries ++;
                   6580:         sleep 1;
                   6581:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6582:     }
                   6583: 
                   6584: # attempt to get unique identifier, based on current timestamp
                   6585:     if ($gotlock eq 'ok') {
                   6586:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6587:         my $id = time;
                   6588:         $newid = $id;
1.1172.2.56  raeburn  6589:         if ($idtype eq 'addcode') {
                   6590:             $newid .= &sixnum_code();
                   6591:         }
1.1172.2.13  raeburn  6592:         my $idtries = 0;
                   6593:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6594:             if ($idtype eq 'concat') {
                   6595:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  6596:             } elsif ($idtype eq 'addcode') {
                   6597:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  6598:             } else {
                   6599:                 $newid ++;
                   6600:             }
                   6601:             $idtries ++;
                   6602:         }
                   6603:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6604:             my %new_item =  (
                   6605:                               $prefix."\0".$newid => $who,
                   6606:                             );
                   6607:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6608:                                                  $cdom,$cnum);
                   6609:             if ($putresult ne 'ok') {
                   6610:                 undef($newid);
                   6611:                 $error = 'error saving new item: '.$putresult;
                   6612:             }
                   6613:         } else {
1.1172.2.56  raeburn  6614:              undef($newid);
1.1172.2.13  raeburn  6615:              $error = ('error: no unique suffix available for the new item ');
                   6616:         }
                   6617: #  remove lock
                   6618:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6619:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6620:     } else {
                   6621:         $error = "error: could not obtain lockfile\n";
                   6622:         $dellock = 'ok';
1.1172.2.58  raeburn  6623:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6624:             $dellock = 'nolock';
                   6625:         }
1.1172.2.13  raeburn  6626:     }
                   6627:     return ($newid,$dellock,$error);
                   6628: }
                   6629: 
1.1172.2.56  raeburn  6630: sub sixnum_code {
                   6631:     my $code;
                   6632:     for (0..6) {
                   6633:         $code .= int( rand(9) );
                   6634:     }
                   6635:     return $code;
                   6636: }
                   6637: 
1.765     albertel 6638: # -------------------------------------------------- portfolio access checking
                   6639: 
                   6640: sub portfolio_access {
1.1172.2.77  raeburn  6641:     my ($requrl,$clientip) = @_;
1.765     albertel 6642:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  6643:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6644:     if ($result) {
                   6645:         my %setters;
                   6646:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6647:             my ($startblock,$endblock) =
                   6648:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6649:             if ($startblock && $endblock) {
                   6650:                 return 'B';
                   6651:             }
                   6652:         } else {
                   6653:             my ($startblock,$endblock) =
                   6654:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6655:             if ($startblock && $endblock) {
                   6656:                 return 'B';
                   6657:             }
                   6658:         }
                   6659:     }
1.765     albertel 6660:     if ($result eq 'ok') {
1.766     albertel 6661:        return 'F';
1.765     albertel 6662:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6663:        return 'A';
1.765     albertel 6664:     }
1.766     albertel 6665:     return '';
1.765     albertel 6666: }
                   6667: 
                   6668: sub get_portfolio_access {
1.1172.2.77  raeburn  6669:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 6670: 
                   6671:     if (!ref($access_hash)) {
                   6672: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6673: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6674: 						   $file_name);
                   6675: 	$access_hash = $access_controls{$file_name};
                   6676:     }
                   6677: 
1.1172.2.77  raeburn  6678:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 6679:     my $now = time;
                   6680:     if (ref($access_hash) eq 'HASH') {
                   6681:         foreach my $key (keys(%{$access_hash})) {
                   6682:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6683:             if ($start > $now) {
                   6684:                 next;
                   6685:             }
                   6686:             if ($end && $end<$now) {
                   6687:                 next;
                   6688:             }
                   6689:             if ($scope eq 'public') {
                   6690:                 $public = $key;
                   6691:                 last;
                   6692:             } elsif ($scope eq 'guest') {
                   6693:                 $guest = $key;
                   6694:             } elsif ($scope eq 'domains') {
                   6695:                 push(@domains,$key);
                   6696:             } elsif ($scope eq 'users') {
                   6697:                 push(@users,$key);
                   6698:             } elsif ($scope eq 'course') {
                   6699:                 push(@courses,$key);
                   6700:             } elsif ($scope eq 'group') {
                   6701:                 push(@groups,$key);
1.1172.2.77  raeburn  6702:             } elsif ($scope eq 'ip') {
                   6703:                 push(@ips,$key);
1.765     albertel 6704:             }
                   6705:         }
                   6706:         if ($public) {
                   6707:             return 'ok';
1.1172.2.77  raeburn  6708:         } elsif (@ips > 0) {
                   6709:             my $allowed;
                   6710:             foreach my $ipkey (@ips) {
                   6711:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   6712:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   6713:                         $allowed = 1;
                   6714:                         last;
                   6715:                     }
                   6716:                 }
                   6717:             }
                   6718:             if ($allowed) {
                   6719:                 return 'ok';
                   6720:             }
1.765     albertel 6721:         }
                   6722:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6723:             if ($guest) {
                   6724:                 return $guest;
                   6725:             }
                   6726:         } else {
                   6727:             if (@domains > 0) {
                   6728:                 foreach my $domkey (@domains) {
                   6729:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6730:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6731:                             return 'ok';
                   6732:                         }
                   6733:                     }
                   6734:                 }
                   6735:             }
                   6736:             if (@users > 0) {
                   6737:                 foreach my $userkey (@users) {
1.865     raeburn  6738:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6739:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6740:                             if (ref($item) eq 'HASH') {
                   6741:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6742:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6743:                                     return 'ok';
                   6744:                                 }
                   6745:                             }
                   6746:                         }
                   6747:                     } 
1.765     albertel 6748:                 }
                   6749:             }
                   6750:             my %roleshash;
                   6751:             my @courses_and_groups = @courses;
                   6752:             push(@courses_and_groups,@groups); 
                   6753:             if (@courses_and_groups > 0) {
                   6754:                 my (%allgroups,%allroles); 
                   6755:                 my ($start,$end,$role,$sec,$group);
                   6756:                 foreach my $envkey (%env) {
1.1060    raeburn  6757:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6758:                         my $cid = $2.'_'.$3; 
                   6759:                         if ($1 eq 'gr') {
                   6760:                             $group = $4;
                   6761:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6762:                         } else {
                   6763:                             if ($4 eq '') {
                   6764:                                 $sec = 'none';
                   6765:                             } else {
                   6766:                                 $sec = $4;
                   6767:                             }
                   6768:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6769:                         }
1.811     albertel 6770:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6771:                         my $cid = $2.'_'.$3;
                   6772:                         if ($4 eq '') {
                   6773:                             $sec = 'none';
                   6774:                         } else {
                   6775:                             $sec = $4;
                   6776:                         }
                   6777:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6778:                     }
                   6779:                 }
                   6780:                 if (keys(%allroles) == 0) {
                   6781:                     return;
                   6782:                 }
                   6783:                 foreach my $key (@courses_and_groups) {
                   6784:                     my %content = %{$$access_hash{$key}};
                   6785:                     my $cnum = $content{'number'};
                   6786:                     my $cdom = $content{'domain'};
                   6787:                     my $cid = $cdom.'_'.$cnum;
                   6788:                     if (!exists($allroles{$cid})) {
                   6789:                         next;
                   6790:                     }    
                   6791:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6792:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6793:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6794:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6795:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6796:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6797:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6798:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6799:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6800:                                         if (grep/^all$/,@sections) {
                   6801:                                             return 'ok';
                   6802:                                         } else {
                   6803:                                             if (grep/^$sec$/,@sections) {
                   6804:                                                 return 'ok';
                   6805:                                             }
                   6806:                                         }
                   6807:                                     }
                   6808:                                 }
                   6809:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6810:                                     if (grep/^none$/,@groups) {
                   6811:                                         return 'ok';
                   6812:                                     }
                   6813:                                 } else {
                   6814:                                     if (grep/^all$/,@groups) {
                   6815:                                         return 'ok';
                   6816:                                     } 
                   6817:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6818:                                         if (grep/^$group$/,@groups) {
                   6819:                                             return 'ok';
                   6820:                                         }
                   6821:                                     }
                   6822:                                 } 
                   6823:                             }
                   6824:                         }
                   6825:                     }
                   6826:                 }
                   6827:             }
                   6828:             if ($guest) {
                   6829:                 return $guest;
                   6830:             }
                   6831:         }
                   6832:     }
                   6833:     return;
                   6834: }
                   6835: 
                   6836: sub course_group_datechecker {
                   6837:     my ($dates,$now,$status) = @_;
                   6838:     my ($start,$end) = split(/\./,$dates);
                   6839:     if (!$start && !$end) {
                   6840:         return 'ok';
                   6841:     }
                   6842:     if (grep/^active$/,@{$status}) {
                   6843:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6844:             return 'ok';
                   6845:         }
                   6846:     }
                   6847:     if (grep/^previous$/,@{$status}) {
                   6848:         if ($end > $now ) {
                   6849:             return 'ok';
                   6850:         }
                   6851:     }
                   6852:     if (grep/^future$/,@{$status}) {
                   6853:         if ($start > $now) {
                   6854:             return 'ok';
                   6855:         }
                   6856:     }
                   6857:     return; 
                   6858: }
                   6859: 
                   6860: sub parse_portfolio_url {
                   6861:     my ($url) = @_;
                   6862: 
                   6863:     my ($type,$udom,$unum,$group,$file_name);
                   6864:     
1.823     albertel 6865:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6866: 	$type = 1;
                   6867:         $udom = $1;
                   6868:         $unum = $2;
                   6869:         $file_name = $3;
1.823     albertel 6870:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6871: 	$type = 2;
                   6872:         $udom = $1;
                   6873:         $unum = $2;
                   6874:         $group = $3;
                   6875:         $file_name = $3.'/'.$4;
                   6876:     }
                   6877:     if (wantarray) {
                   6878: 	return ($type,$udom,$unum,$file_name,$group);
                   6879:     }
                   6880:     return $type;
                   6881: }
                   6882: 
                   6883: sub is_portfolio_url {
                   6884:     my ($url) = @_;
                   6885:     return scalar(&parse_portfolio_url($url));
                   6886: }
                   6887: 
1.798     raeburn  6888: sub is_portfolio_file {
                   6889:     my ($file) = @_;
1.820     raeburn  6890:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6891:         return 1;
                   6892:     }
                   6893:     return;
                   6894: }
                   6895: 
1.976     raeburn  6896: sub usertools_access {
1.1084    raeburn  6897:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6898:     my ($access,%tools);
                   6899:     if ($context eq '') {
                   6900:         $context = 'tools';
                   6901:     }
                   6902:     if ($context eq 'requestcourses') {
                   6903:         %tools = (
                   6904:                       official   => 1,
                   6905:                       unofficial => 1,
1.1006    raeburn  6906:                       community  => 1,
1.1172.2.37  raeburn  6907:                       textbook   => 1,
1.985     raeburn  6908:                  );
1.1172.2.9  raeburn  6909:     } elsif ($context eq 'requestauthor') {
                   6910:         %tools = (
                   6911:                       requestauthor => 1,
                   6912:                  );
1.985     raeburn  6913:     } else {
                   6914:         %tools = (
                   6915:                       aboutme   => 1,
                   6916:                       blog      => 1,
1.1172.2.6  raeburn  6917:                       webdav    => 1,
1.985     raeburn  6918:                       portfolio => 1,
                   6919:                  );
                   6920:     }
1.976     raeburn  6921:     return if (!defined($tools{$tool}));
                   6922: 
1.1172.2.35  raeburn  6923:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6924:         $udom = $env{'user.domain'};
                   6925:         $uname = $env{'user.name'};
                   6926:     }
                   6927: 
1.978     raeburn  6928:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6929:         if ($action ne 'reload') {
1.985     raeburn  6930:             if ($context eq 'requestcourses') {
                   6931:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  6932:             } elsif ($context eq 'requestauthor') {
                   6933:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6934:             } else {
                   6935:                 return $env{'environment.availabletools.'.$tool};
                   6936:             }
                   6937:         }
1.976     raeburn  6938:     }
                   6939: 
1.1172.2.9  raeburn  6940:     my ($toolstatus,$inststatus,$envkey);
                   6941:     if ($context eq 'requestauthor') {
                   6942:         $envkey = $context;
                   6943:     } else {
                   6944:         $envkey = $context.'.'.$tool;
                   6945:     }
1.976     raeburn  6946: 
1.985     raeburn  6947:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6948:          ($action ne 'reload')) {
1.1172.2.9  raeburn  6949:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6950:         $inststatus = $env{'environment.inststatus'};
                   6951:     } else {
1.1084    raeburn  6952:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  6953:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6954:             $inststatus = $userenvref->{'inststatus'};
                   6955:         } else {
1.1172.2.9  raeburn  6956:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6957:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6958:             $inststatus = $userenv{'inststatus'};
                   6959:         }
1.976     raeburn  6960:     }
                   6961: 
                   6962:     if ($toolstatus ne '') {
                   6963:         if ($toolstatus) {
                   6964:             $access = 1;
                   6965:         } else {
                   6966:             $access = 0;
                   6967:         }
                   6968:         return $access;
                   6969:     }
                   6970: 
1.1084    raeburn  6971:     my ($is_adv,%domdef);
                   6972:     if (ref($is_advref) eq 'HASH') {
                   6973:         $is_adv = $is_advref->{'is_adv'};
                   6974:     } else {
                   6975:         $is_adv = &is_advanced_user($udom,$uname);
                   6976:     }
                   6977:     if (ref($domdefref) eq 'HASH') {
                   6978:         %domdef = %{$domdefref};
                   6979:     } else {
                   6980:         %domdef = &get_domain_defaults($udom);
                   6981:     }
1.976     raeburn  6982:     if (ref($domdef{$tool}) eq 'HASH') {
                   6983:         if ($is_adv) {
                   6984:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6985:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6986:                     $access = 1;
                   6987:                 } else {
                   6988:                     $access = 0;
                   6989:                 }
                   6990:                 return $access;
                   6991:             }
                   6992:         }
                   6993:         if ($inststatus ne '') {
                   6994:             my ($hasaccess,$hasnoaccess);
                   6995:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6996:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6997:                     if ($domdef{$tool}{$affiliation}) {
                   6998:                         $hasaccess = 1;
                   6999:                     } else {
                   7000:                         $hasnoaccess = 1;
                   7001:                     }
                   7002:                 }
                   7003:             }
                   7004:             if ($hasaccess || $hasnoaccess) {
                   7005:                 if ($hasaccess) {
                   7006:                     $access = 1;
                   7007:                 } elsif ($hasnoaccess) {
                   7008:                     $access = 0; 
                   7009:                 }
                   7010:                 return $access;
                   7011:             }
                   7012:         } else {
                   7013:             if ($domdef{$tool}{'default'} ne '') {
                   7014:                 if ($domdef{$tool}{'default'}) {
                   7015:                     $access = 1;
                   7016:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7017:                     $access = 0;
                   7018:                 }
                   7019:                 return $access;
                   7020:             }
                   7021:         }
                   7022:     } else {
1.1172.2.6  raeburn  7023:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7024:             $access = 1;
                   7025:         } else {
                   7026:             $access = 0;
                   7027:         }
1.976     raeburn  7028:         return $access;
                   7029:     }
                   7030: }
                   7031: 
1.1050    raeburn  7032: sub is_course_owner {
                   7033:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7034:     if (($udom eq '') || ($uname eq '')) {
                   7035:         $udom = $env{'user.domain'};
                   7036:         $uname = $env{'user.name'};
                   7037:     }
                   7038:     unless (($udom eq '') || ($uname eq '')) {
                   7039:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7040:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7041:                 return 1;
                   7042:             } else {
                   7043:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7044:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7045:                     return 1;
                   7046:                 }
                   7047:             }
                   7048:         }
                   7049:     }
                   7050:     return;
                   7051: }
                   7052: 
1.976     raeburn  7053: sub is_advanced_user {
                   7054:     my ($udom,$uname) = @_;
1.1085    raeburn  7055:     if ($udom ne '' && $uname ne '') {
                   7056:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7057:             if (wantarray) {
                   7058:                 return ($env{'user.adv'},$env{'user.author'});
                   7059:             } else {
                   7060:                 return $env{'user.adv'};
                   7061:             }
1.1085    raeburn  7062:         }
                   7063:     }
1.976     raeburn  7064:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7065:     my %allroles;
1.1128    raeburn  7066:     my ($is_adv,$is_author);
1.976     raeburn  7067:     foreach my $role (keys(%roleshash)) {
                   7068:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7069:         my $area = '/'.$tdomain.'/'.$trest;
                   7070:         if ($sec ne '') {
                   7071:             $area .= '/'.$sec;
                   7072:         }
                   7073:         if (($area ne '') && ($trole ne '')) {
                   7074:             my $spec=$trole.'.'.$area;
                   7075:             if ($trole =~ /^cr\//) {
                   7076:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7077:             } elsif ($trole ne 'gr') {
                   7078:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7079:             }
1.1128    raeburn  7080:             if ($trole eq 'au') {
                   7081:                 $is_author = 1;
                   7082:             }
1.976     raeburn  7083:         }
                   7084:     }
                   7085:     foreach my $role (keys(%allroles)) {
                   7086:         last if ($is_adv);
                   7087:         foreach my $item (split(/:/,$allroles{$role})) {
                   7088:             if ($item ne '') {
                   7089:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7090:                 if ($privilege eq 'adv') {
                   7091:                     $is_adv = 1;
                   7092:                     last;
                   7093:                 }
                   7094:             }
                   7095:         }
                   7096:     }
1.1128    raeburn  7097:     if (wantarray) {
                   7098:         return ($is_adv,$is_author);
                   7099:     }
1.976     raeburn  7100:     return $is_adv;
                   7101: }
1.798     raeburn  7102: 
1.1035    raeburn  7103: sub check_can_request {
1.1036    raeburn  7104:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7105:     my $canreq = 0;
                   7106:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7107:     my @options = ('approval','validate','autolimit');
                   7108:     my $optregex = join('|',@options);
                   7109:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7110:         foreach my $type (@{$types}) {
                   7111:             if (&usertools_access($env{'user.name'},
                   7112:                                   $env{'user.domain'},
                   7113:                                   $type,undef,'requestcourses')) {
                   7114:                 $canreq ++;
1.1036    raeburn  7115:                 if (ref($request_domains) eq 'HASH') {
                   7116:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7117:                 }
1.1035    raeburn  7118:                 if ($dom eq $env{'user.domain'}) {
                   7119:                     $can_request->{$type} = 1;
                   7120:                 }
                   7121:             }
                   7122:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7123:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7124:                 if (@curr > 0) {
1.1036    raeburn  7125:                     foreach my $item (@curr) {
                   7126:                         if (ref($request_domains) eq 'HASH') {
                   7127:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7128:                             if ($otherdom ne '') {
                   7129:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7130:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7131:                                         push(@{$request_domains->{$type}},$otherdom);
                   7132:                                     }
                   7133:                                 } else {
                   7134:                                     push(@{$request_domains->{$type}},$otherdom);
                   7135:                                 }
                   7136:                             }
                   7137:                         }
                   7138:                     }
                   7139:                     unless($dom eq $env{'user.domain'}) {
                   7140:                         $canreq ++;
1.1035    raeburn  7141:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7142:                             $can_request->{$type} = 1;
                   7143:                         }
                   7144:                     }
                   7145:                 }
                   7146:             }
                   7147:         }
                   7148:     }
                   7149:     return $canreq;
                   7150: }
                   7151: 
1.341     www      7152: # ---------------------------------------------- Custom access rule evaluation
                   7153: 
                   7154: sub customaccess {
                   7155:     my ($priv,$uri)=@_;
1.807     albertel 7156:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7157:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7158:     $udom = &LONCAPA::clean_domain($udom);
                   7159:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7160:     my $access=0;
1.800     albertel 7161:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7162: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7163: 	if ($type eq 'user') {
                   7164: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7165: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7166: 		if ($tdom) {
                   7167: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7168: 		}
1.896     albertel 7169: 		if ($tuname) {
                   7170: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7171: 		}
                   7172: 		$access=($effect eq 'allow');
                   7173: 		last;
                   7174: 	    }
                   7175: 	} else {
                   7176: 	    if ($role) {
                   7177: 		if ($role ne $urole) { next; }
                   7178: 	    }
                   7179: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7180: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7181: 		if ($tdom) {
                   7182: 		    if ($tdom ne $udom) { next; }
                   7183: 		}
                   7184: 		if ($tcrs) {
                   7185: 		    if ($tcrs ne $ucrs) { next; }
                   7186: 		}
                   7187: 		if ($tsec) {
                   7188: 		    if ($tsec ne $usec) { next; }
                   7189: 		}
                   7190: 		$access=($effect eq 'allow');
                   7191: 		last;
                   7192: 	    }
                   7193: 	    if ($realm eq '' && $role eq '') {
                   7194: 		$access=($effect eq 'allow');
                   7195: 	    }
1.402     bowersj2 7196: 	}
1.341     www      7197:     }
                   7198:     return $access;
                   7199: }
                   7200: 
1.103     harris41 7201: # ------------------------------------------------- Check for a user privilege
1.12      www      7202: 
                   7203: sub allowed {
1.1172.2.65  raeburn  7204:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7205:     my $ver_orguri=$uri;
1.439     www      7206:     $uri=&deversion($uri);
1.152     www      7207:     my $orguri=$uri;
1.52      www      7208:     $uri=&declutter($uri);
1.809     raeburn  7209: 
1.810     raeburn  7210:     if ($priv eq 'evb') {
                   7211: # Evade communication block restrictions for specified role in a course
                   7212:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7213:             return $1;
                   7214:         } else {
                   7215:             return;
                   7216:         }
                   7217:     }
                   7218: 
1.620     albertel 7219:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7220: # Free bre access to adm and meta resources
1.775     albertel 7221:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 7222: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7223: 	&& ($priv eq 'bre')) {
1.14      www      7224: 	return 'F';
1.159     www      7225:     }
                   7226: 
1.545     banghart 7227: # Free bre access to user's own portfolio contents
1.714     raeburn  7228:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7229:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7230: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7231:         my %setters;
                   7232:         my ($startblock,$endblock) = 
                   7233:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7234:         if ($startblock && $endblock) {
                   7235:             return 'B';
                   7236:         } else {
                   7237:             return 'F';
                   7238:         }
1.545     banghart 7239:     }
                   7240: 
1.762     raeburn  7241: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7242:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7243:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7244:         if (exists($env{'request.course.id'})) {
                   7245:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7246:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7247:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7248:                 my $courseprivid=$env{'request.course.id'};
                   7249:                 $courseprivid=~s/\_/\//;
                   7250:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7251:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7252:                     return $1; 
1.762     raeburn  7253:                 } else {
                   7254:                     if ($env{'request.course.sec'}) {
                   7255:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7256:                     }
                   7257:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7258:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7259:                         return $2;
                   7260:                     }
1.714     raeburn  7261:                 }
                   7262:             }
                   7263:         }
                   7264:     }
                   7265: 
1.159     www      7266: # Free bre to public access
                   7267: 
                   7268:     if ($priv eq 'bre') {
1.238     www      7269:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7270: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7271:            return 'F'; 
                   7272:         }
1.238     www      7273:         if ($copyright eq 'priv') {
                   7274:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7275: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7276: 		return '';
                   7277:             }
                   7278:         }
                   7279:         if ($copyright eq 'domain') {
                   7280:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7281: 	    unless (($env{'user.domain'} eq $1) ||
                   7282:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7283: 		return '';
                   7284:             }
1.262     matthew  7285:         }
1.620     albertel 7286:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7287:             # Library role, so allow browsing of resources in this domain.
                   7288:             return 'F';
1.238     www      7289:         }
1.341     www      7290:         if ($copyright eq 'custom') {
                   7291: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7292:         }
1.14      www      7293:     }
1.264     matthew  7294:     # Domain coordinator is trying to create a course
1.620     albertel 7295:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7296:         # uri is the requested domain in this case.
                   7297:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7298:         # a role of dc for the domain in question.
1.620     albertel 7299:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7300:     }
1.29      www      7301: 
1.52      www      7302:     my $thisallowed='';
                   7303:     my $statecond=0;
                   7304:     my $courseprivid='';
                   7305: 
1.1039    raeburn  7306:     my $ownaccess;
1.1043    raeburn  7307:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7308:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7309:         if ($uri eq '') {
                   7310:             $ownaccess = 1;
                   7311:         } else {
                   7312:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7313:                 my $udom = $env{'user.domain'};
                   7314:                 my $uname = $env{'user.name'};
                   7315:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7316:                     $ownaccess = 1;
1.1040    raeburn  7317:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7318:                     unless ($uri =~ m{\.\./}) {
                   7319:                         $ownaccess = 1;
                   7320:                     }
                   7321:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7322:                     my $now = time;
                   7323:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7324:                         my $adom = $1;
                   7325:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7326:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7327:                                 my ($start,$end) = split('.',$env{$key});
                   7328:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7329:                                     $ownaccess = 1;
                   7330:                                     last;
                   7331:                                 }
                   7332:                             }
                   7333:                         }
                   7334:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7335:                         my $adom = $1;
                   7336:                         my $aname = $2;
1.1042    raeburn  7337:                         foreach my $role ('ca','aa') { 
                   7338:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7339:                                 my ($start,$end) =
                   7340:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7341:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7342:                                     $ownaccess = 1;
                   7343:                                     last;
                   7344:                                 }
1.1039    raeburn  7345:                             }
                   7346:                         }
                   7347:                     }
                   7348:                 }
                   7349:             }
                   7350:         }
                   7351:     }
                   7352: 
1.52      www      7353: # Course
                   7354: 
1.620     albertel 7355:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7356:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7357:             $thisallowed.=$1;
                   7358:         }
1.52      www      7359:     }
1.29      www      7360: 
1.52      www      7361: # Domain
                   7362: 
1.620     albertel 7363:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7364:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7365:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7366:             $thisallowed.=$1;
                   7367:         }
1.12      www      7368:     }
1.52      www      7369: 
1.1141    raeburn  7370: # User who is not author or co-author might still be able to edit
                   7371: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7372:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7373:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7374:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7375:             $thisallowed.=$1;
                   7376:         }
                   7377:     }
                   7378: 
1.52      www      7379: # Course: uri itself is a course
1.66      www      7380:     my $courseuri=$uri;
                   7381:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7382:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7383: 
1.620     albertel 7384:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7385:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7386:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7387:             $thisallowed.=$1;
                   7388:         }
1.12      www      7389:     }
1.29      www      7390: 
1.665     albertel 7391: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7392: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7393:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7394: 	$thisallowed='';
1.671     raeburn  7395:         my ($match)=&is_on_map($uri);
                   7396:         if ($match) {
                   7397:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7398:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  7399:                 my $value = $1;
                   7400:                 if ($noblockcheck) {
                   7401:                     $thisallowed.=$value;
1.1162    raeburn  7402:                 } else {
1.1172.2.65  raeburn  7403:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7404:                     if (@blockers > 0) {
                   7405:                         $thisallowed = 'B';
                   7406:                     } else {
                   7407:                         $thisallowed.=$value;
                   7408:                     }
1.1162    raeburn  7409:                 }
1.671     raeburn  7410:             }
                   7411:         } else {
1.705     albertel 7412:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7413:             if ($refuri) {
                   7414:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7415:                     $thisallowed='F';
1.671     raeburn  7416:                 } else {
                   7417:                     $refuri=&declutter($refuri);
                   7418:                     my ($match) = &is_on_map($refuri);
                   7419:                     if ($match) {
1.1172.2.65  raeburn  7420:                         if ($noblockcheck) {
1.1162    raeburn  7421:                             $thisallowed='F';
1.1172.2.65  raeburn  7422:                         } else {
                   7423:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7424:                             if (@blockers > 0) {
                   7425:                                 $thisallowed = 'B';
                   7426:                             } else {
                   7427:                                 $thisallowed='F';
                   7428:                             }
1.1162    raeburn  7429:                         }
1.671     raeburn  7430:                     }
1.669     raeburn  7431:                 }
1.671     raeburn  7432:             }
                   7433:         }
1.314     www      7434:     }
1.492     albertel 7435: 
1.766     albertel 7436:     if ($priv eq 'bre'
                   7437: 	&& $thisallowed ne 'F' 
                   7438: 	&& $thisallowed ne '2'
                   7439: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  7440: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7441:     }
                   7442:     
1.52      www      7443: # Full access at system, domain or course-wide level? Exit.
1.29      www      7444:     if ($thisallowed=~/F/) {
                   7445: 	return 'F';
                   7446:     }
                   7447: 
1.52      www      7448: # If this is generating or modifying users, exit with special codes
1.29      www      7449: 
1.643     www      7450:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7451: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7452: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7453: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7454: 	    unless ($auname) { return $thisallowed; }
                   7455: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7456: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7457: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7458: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7459: 	}
1.52      www      7460: 	return $thisallowed;
                   7461:     }
                   7462: #
1.103     harris41 7463: # Gathered so far: system, domain and course wide privileges
1.52      www      7464: #
                   7465: # Course: See if uri or referer is an individual resource that is part of 
                   7466: # the course
                   7467: 
1.620     albertel 7468:     if ($env{'request.course.id'}) {
1.232     www      7469: 
1.620     albertel 7470:        $courseprivid=$env{'request.course.id'};
                   7471:        if ($env{'request.course.sec'}) {
                   7472:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7473:        }
                   7474:        $courseprivid=~s/\_/\//;
                   7475:        my $checkreferer=1;
1.232     www      7476:        my ($match,$cond)=&is_on_map($uri);
                   7477:        if ($match) {
                   7478:            $statecond=$cond;
1.620     albertel 7479:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7480:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7481:                my $value = $1;
                   7482:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  7483:                    if ($noblockcheck) {
1.1162    raeburn  7484:                        $thisallowed.=$value;
1.1172.2.65  raeburn  7485:                    } else {
                   7486:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7487:                        if (@blockers > 0) {
                   7488:                            $thisallowed = 'B';
                   7489:                        } else {
                   7490:                            $thisallowed.=$value;
                   7491:                        }
1.1162    raeburn  7492:                    }
                   7493:                } else {
                   7494:                    $thisallowed.=$value;
                   7495:                }
1.52      www      7496:                $checkreferer=0;
                   7497:            }
1.29      www      7498:        }
1.83      www      7499:        
1.148     www      7500:        if ($checkreferer) {
1.620     albertel 7501: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7502:             unless ($refuri) {
1.800     albertel 7503:                 foreach my $key (keys(%env)) {
                   7504: 		    if ($key=~/^httpref\..*\*/) {
                   7505: 			my $pattern=$key;
1.156     www      7506:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7507:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7508:                         $pattern=~s/\//\\\//g;
1.152     www      7509:                         if ($orguri=~/$pattern/) {
1.800     albertel 7510: 			    $refuri=$env{$key};
1.148     www      7511:                         }
                   7512:                     }
1.191     harris41 7513:                 }
1.148     www      7514:             }
1.232     www      7515: 
1.148     www      7516:          if ($refuri) { 
1.152     www      7517: 	  $refuri=&declutter($refuri);
1.232     www      7518:           my ($match,$cond)=&is_on_map($refuri);
                   7519:             if ($match) {
                   7520:               my $refstatecond=$cond;
1.620     albertel 7521:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7522:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7523:                   my $value = $1;
                   7524:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  7525:                       if ($noblockcheck) {
1.1162    raeburn  7526:                           $thisallowed.=$value;
1.1172.2.65  raeburn  7527:                       } else {
                   7528:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7529:                           if (@blockers > 0) {
                   7530:                               $thisallowed = 'B';
                   7531:                           } else {
                   7532:                               $thisallowed.=$value;
                   7533:                           }
1.1162    raeburn  7534:                       }
                   7535:                   } else {
                   7536:                       $thisallowed.=$value;
                   7537:                   }
1.53      www      7538:                   $uri=$refuri;
                   7539:                   $statecond=$refstatecond;
1.52      www      7540:               }
                   7541:           }
1.148     www      7542:         }
1.29      www      7543:        }
1.52      www      7544:    }
1.29      www      7545: 
1.52      www      7546: #
1.103     harris41 7547: # Gathered now: all privileges that could apply, and condition number
1.52      www      7548: # 
                   7549: #
                   7550: # Full or no access?
                   7551: #
1.29      www      7552: 
1.52      www      7553:     if ($thisallowed=~/F/) {
                   7554: 	return 'F';
                   7555:     }
1.29      www      7556: 
1.52      www      7557:     unless ($thisallowed) {
                   7558:         return '';
                   7559:     }
1.29      www      7560: 
1.52      www      7561: # Restrictions exist, deal with them
                   7562: #
                   7563: #   C:according to course preferences
                   7564: #   R:according to resource settings
                   7565: #   L:unless locked
                   7566: #   X:according to user session state
                   7567: #
                   7568: 
                   7569: # Possibly locked functionality, check all courses
1.54      www      7570: # Locks might take effect only after 10 minutes cache expiration for other
                   7571: # courses, and 2 minutes for current course
1.52      www      7572: 
                   7573:     my $envkey;
                   7574:     if ($thisallowed=~/L/) {
1.1000    raeburn  7575:         foreach $envkey (keys(%env)) {
1.54      www      7576:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7577:                my $courseid=$2;
                   7578:                my $roleid=$1.'.'.$2;
1.92      www      7579:                $courseid=~s/^\///;
1.54      www      7580:                my $expiretime=600;
1.620     albertel 7581:                if ($env{'request.role'} eq $roleid) {
1.54      www      7582: 		  $expiretime=120;
                   7583:                }
                   7584: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7585:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7586:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7587: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7588:                }
1.620     albertel 7589:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7590:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7591: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7592:                        &log($env{'user.domain'},$env{'user.name'},
                   7593:                             $env{'user.home'},
1.57      www      7594:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7595:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7596:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7597: 		       return '';
                   7598:                    }
                   7599:                }
1.620     albertel 7600:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7601:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7602: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7603:                        &log($env{'user.domain'},$env{'user.name'},
                   7604:                             $env{'user.home'},
1.57      www      7605:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7606:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7607:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7608: 		       return '';
                   7609:                    }
                   7610:                }
                   7611: 	   }
1.29      www      7612:        }
1.52      www      7613:     }
                   7614:    
                   7615: #
                   7616: # Rest of the restrictions depend on selected course
                   7617: #
                   7618: 
1.620     albertel 7619:     unless ($env{'request.course.id'}) {
1.766     albertel 7620: 	if ($thisallowed eq 'A') {
                   7621: 	    return 'A';
1.814     raeburn  7622:         } elsif ($thisallowed eq 'B') {
                   7623:             return 'B';
1.766     albertel 7624: 	} else {
                   7625: 	    return '1';
                   7626: 	}
1.52      www      7627:     }
1.29      www      7628: 
1.52      www      7629: #
                   7630: # Now user is definitely in a course
                   7631: #
1.53      www      7632: 
                   7633: 
                   7634: # Course preferences
                   7635: 
                   7636:    if ($thisallowed=~/C/) {
1.620     albertel 7637:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7638:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7639:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7640: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  7641: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7642: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7643: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7644: 			$env{'request.course.id'});
                   7645: 	   }
1.237     www      7646:            return '';
                   7647:        }
                   7648: 
1.620     albertel 7649:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7650: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  7651: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7652: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7653: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7654: 			$env{'request.course.id'});
                   7655: 	   }
1.54      www      7656:            return '';
                   7657:        }
1.53      www      7658:    }
                   7659: 
                   7660: # Resource preferences
                   7661: 
                   7662:    if ($thisallowed=~/R/) {
1.620     albertel 7663:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7664:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7665: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7666: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7667: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7668: 	   }
                   7669: 	   return '';
1.54      www      7670:        }
1.53      www      7671:    }
1.30      www      7672: 
1.246     www      7673: # Restricted by state or randomout?
1.30      www      7674: 
1.52      www      7675:    if ($thisallowed=~/X/) {
1.620     albertel 7676:       if ($env{'acc.randomout'}) {
1.579     albertel 7677: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7678:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7679:             return ''; 
                   7680:          }
1.247     www      7681:       }
                   7682:       if (&condval($statecond)) {
1.52      www      7683: 	 return '2';
                   7684:       } else {
                   7685:          return '';
                   7686:       }
                   7687:    }
1.30      www      7688: 
1.766     albertel 7689:     if ($thisallowed eq 'A') {
                   7690: 	return 'A';
1.814     raeburn  7691:     } elsif ($thisallowed eq 'B') {
                   7692:         return 'B';
1.766     albertel 7693:     }
1.52      www      7694:    return 'F';
1.232     www      7695: }
1.1162    raeburn  7696: 
1.1172.2.13  raeburn  7697: # ------------------------------------------- Check construction space access
                   7698: 
                   7699: sub constructaccess {
                   7700:     my ($url,$setpriv)=@_;
                   7701: 
                   7702: # We do not allow editing of previous versions of files
                   7703:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7704: 
                   7705: # Get username and domain from URL
                   7706:     my ($ownername,$ownerdomain,$ownerhome);
                   7707: 
                   7708:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  7709:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  7710: 
                   7711: # The URL does not really point to any authorspace, forget it
                   7712:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7713: 
                   7714: # Now we need to see if the user has access to the authorspace of
                   7715: # $ownername at $ownerdomain
                   7716: 
                   7717:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7718: # Real author for this?
                   7719:        $ownerhome = $env{'user.home'};
                   7720:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7721:           return ($ownername,$ownerdomain,$ownerhome);
                   7722:        }
                   7723:     } else {
                   7724: # Co-author for this?
                   7725:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7726:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7727:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7728:             return ($ownername,$ownerdomain,$ownerhome);
                   7729:         }
                   7730:     }
                   7731: 
                   7732: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7733: # we might as well leave
                   7734:    unless ($setpriv) { return ''; }
                   7735: 
                   7736: # Backdoor access?
                   7737:     my $allowed=&allowed('eco',$ownerdomain);
                   7738: # Nope
                   7739:     unless ($allowed) { return ''; }
                   7740: # Looks like we may have access, but could be locked by the owner of the construction space
                   7741:     if ($allowed eq 'U') {
                   7742:         my %blocked=&get('environment',['domcoord.author'],
                   7743:                          $ownerdomain,$ownername);
                   7744: # Is blocked by owner
                   7745:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7746:     }
                   7747:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7748: # Grant temporary access
                   7749:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  7750:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  7751:         if (!$update) { $update = $then; }
                   7752:         my $refresh=$env{'user.refresh.time'};
                   7753:         if (!$refresh) { $refresh = $update; }
                   7754:         my $now = time;
                   7755:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7756:                            $now,'ca','constructaccess');
                   7757:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7758:         return($ownername,$ownerdomain,$ownerhome);
                   7759:     }
                   7760: # No business here
                   7761:     return '';
                   7762: }
                   7763: 
1.1172.2.66  raeburn  7764: # ----------------------------------------------------------- Content Blocking
                   7765: 
                   7766: {
                   7767: # Caches for faster Course Contents display where content blocking
                   7768: # is in operation (i.e., interval param set) for timed quiz.
                   7769: #
                   7770: # User for whom data are being temporarily cached.
                   7771: my $cacheduser='';
                   7772: # Cached blockers for this user (a hash of blocking items).
                   7773: my %cachedblockers=();
                   7774: # When the data were last cached.
                   7775: my $cachedlast='';
                   7776: 
                   7777: sub load_all_blockers {
                   7778:     my ($uname,$udom,$blocks)=@_;
                   7779:     if (($uname ne '') && ($udom ne '')) {
                   7780:         if (($cacheduser eq $uname.':'.$udom) &&
                   7781:             (abs($cachedlast-time)<5)) {
                   7782:             return;
                   7783:         }
                   7784:     }
                   7785:     $cachedlast=time;
                   7786:     $cacheduser=$uname.':'.$udom;
                   7787:     %cachedblockers = &get_commblock_resources($blocks);
                   7788: }
                   7789: 
1.1162    raeburn  7790: sub get_comm_blocks {
                   7791:     my ($cdom,$cnum) = @_;
                   7792:     if ($cdom eq '' || $cnum eq '') {
                   7793:         return unless ($env{'request.course.id'});
                   7794:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7795:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7796:     }
                   7797:     my %commblocks;
                   7798:     my $hashid=$cdom.'_'.$cnum;
                   7799:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7800:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7801:         %commblocks = %{$blocksref};
                   7802:     } else {
                   7803:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7804:         my $cachetime = 600;
                   7805:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7806:     }
                   7807:     return %commblocks;
                   7808: }
                   7809: 
1.1172.2.66  raeburn  7810: sub get_commblock_resources {
                   7811:     my ($blocks) = @_;
                   7812:     my %blockers = ();
                   7813:     return %blockers unless ($env{'request.course.id'});
                   7814:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  7815:     my %commblocks;
                   7816:     if (ref($blocks) eq 'HASH') {
                   7817:         %commblocks = %{$blocks};
                   7818:     } else {
                   7819:         %commblocks = &get_comm_blocks();
                   7820:     }
1.1172.2.66  raeburn  7821:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  7822:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  7823:     return %blockers unless (ref($navmap));
                   7824:     my $now = time;
1.1162    raeburn  7825:     foreach my $block (keys(%commblocks)) {
                   7826:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7827:             my ($start,$end) = ($1,$2);
                   7828:             if ($start <= $now && $end >= $now) {
                   7829:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7830:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7831:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  7832:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7833:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  7834:                             }
                   7835:                         }
                   7836:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  7837:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7838:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  7839:                             }
                   7840:                         }
                   7841:                     }
                   7842:                 }
                   7843:             }
                   7844:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7845:             my $item = $1;
1.1163    raeburn  7846:             my @to_test;
1.1162    raeburn  7847:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7848:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66  raeburn  7849:                     my @interval;
                   7850:                     my $type = 'map';
                   7851:                     if ($item eq 'course') {
                   7852:                         $type = 'course';
                   7853:                         @interval=&EXT("resource.0.interval");
                   7854:                     } else {
                   7855:                         if ($item =~ /___\d+___/) {
                   7856:                             $type = 'resource';
                   7857:                             @interval=&EXT("resource.0.interval",$item);
                   7858:                             if (ref($navmap)) {
                   7859:                                 my $res = $navmap->getBySymb($item);
                   7860:                                 push(@to_test,$res);
                   7861:                             }
1.1162    raeburn  7862:                         } else {
1.1172.2.66  raeburn  7863:                             my $mapsymb = &symbread($item,1);
                   7864:                             if ($mapsymb) {
                   7865:                                 if (ref($navmap)) {
                   7866:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   7867:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   7868:                                     foreach my $res (@to_test) {
                   7869:                                         my $symb = $res->symb();
                   7870:                                         next if ($symb eq $mapsymb);
                   7871:                                         if ($symb ne '') {
                   7872:                                             @interval=&EXT("resource.0.interval",$symb);
                   7873:                                             if ($interval[1] eq 'map') {
                   7874:                                                 last;
1.1162    raeburn  7875:                                             }
                   7876:                                         }
                   7877:                                     }
                   7878:                                 }
                   7879:                             }
                   7880:                         }
1.1172.2.66  raeburn  7881:                     }
                   7882:                     if ($interval[0] =~ /^\d+$/) {
                   7883:                         my $first_access;
                   7884:                         if ($type eq 'resource') {
                   7885:                             $first_access=&get_first_access($interval[1],$item);
                   7886:                         } elsif ($type eq 'map') {
                   7887:                             $first_access=&get_first_access($interval[1],undef,$item);
                   7888:                         } else {
                   7889:                             $first_access=&get_first_access($interval[1]);
                   7890:                         }
                   7891:                         if ($first_access) {
                   7892:                             my $timesup = $first_access+$interval[0];
                   7893:                             if ($timesup > $now) {
                   7894:                                 my $activeblock;
                   7895:                                 foreach my $res (@to_test) {
                   7896:                                     if ($res->answerable()) {
                   7897:                                         $activeblock = 1;
                   7898:                                         last;
                   7899:                                     }
                   7900:                                 }
                   7901:                                 if ($activeblock) {
                   7902:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7903:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7904:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   7905:                                          }
                   7906:                                     }
                   7907:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7908:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7909:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  7910:                                         }
1.1162    raeburn  7911:                                     }
                   7912:                                 }
                   7913:                             }
                   7914:                         }
                   7915:                     }
                   7916:                 }
                   7917:             }
                   7918:         }
                   7919:     }
1.1172.2.66  raeburn  7920:     return %blockers;
1.1162    raeburn  7921: }
                   7922: 
1.1172.2.66  raeburn  7923: sub has_comm_blocking {
                   7924:     my ($priv,$symb,$uri,$blocks) = @_;
                   7925:     my @blockers;
                   7926:     return unless ($env{'request.course.id'});
                   7927:     return unless ($priv eq 'bre');
                   7928:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7929:     return if ($env{'request.state'} eq 'construct');
                   7930:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   7931:     return unless (keys(%cachedblockers) > 0);
                   7932:     my (%possibles,@symbs);
                   7933:     if (!$symb) {
                   7934:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  7935:     }
1.1172.2.66  raeburn  7936:     if ($symb) {
                   7937:         @symbs = ($symb);
                   7938:     } elsif (keys(%possibles)) {
                   7939:         @symbs = keys(%possibles);
                   7940:     }
                   7941:     my $noblock;
                   7942:     foreach my $symb (@symbs) {
                   7943:         last if ($noblock);
                   7944:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   7945:         foreach my $block (keys(%cachedblockers)) {
                   7946:             if ($block =~ /^firstaccess____(.+)$/) {
                   7947:                 my $item = $1;
                   7948:                 if (($item eq $map) || ($item eq $symb)) {
                   7949:                     $noblock = 1;
                   7950:                     last;
                   7951:                 }
1.1162    raeburn  7952:             }
1.1172.2.66  raeburn  7953:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   7954:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   7955:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   7956:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   7957:                             push(@blockers,$block);
                   7958:                         }
                   7959:                     }
                   7960:                 }
                   7961:             }
                   7962:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   7963:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   7964:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   7965:                         push(@blockers,$block);
                   7966:                     }
                   7967:                 }
1.1162    raeburn  7968:             }
                   7969:         }
                   7970:     }
1.1172.2.66  raeburn  7971:     return if ($noblock);
                   7972:     return @blockers;
                   7973: }
1.1162    raeburn  7974: }
                   7975: 
1.1172.2.66  raeburn  7976: # -------------------------------- Deversion and split uri into path an filename
                   7977: 
1.1133    foxr     7978: #
1.1172.2.66  raeburn  7979: #   Removes the version from a URI and
1.1133    foxr     7980: #   splits it in to its filename and path to the filename.
                   7981: #   Seems like File::Basename could have done this more clearly.
                   7982: #   Parameters:
                   7983: #      $uri   - input URI
                   7984: #   Returns:
                   7985: #     Two element list consisting of 
                   7986: #     $pathname  - the URI up to and excluding the trailing /
                   7987: #     $filename  - The part of the URI following the last /
                   7988: #  NOTE:
                   7989: #    Another realization of this is simply:
                   7990: #    use File::Basename;
                   7991: #    ...
                   7992: #    $uri = shift;
                   7993: #    $filename = basename($uri);
                   7994: #    $path     = dirname($uri);
                   7995: #    return ($filename, $path);
                   7996: #
                   7997: #     The implementation below is probably faster however.
                   7998: #
1.710     albertel 7999: sub split_uri_for_cond {
                   8000:     my $uri=&deversion(&declutter(shift));
                   8001:     my @uriparts=split(/\//,$uri);
                   8002:     my $filename=pop(@uriparts);
                   8003:     my $pathname=join('/',@uriparts);
                   8004:     return ($pathname,$filename);
                   8005: }
1.232     www      8006: # --------------------------------------------------- Is a resource on the map?
                   8007: 
                   8008: sub is_on_map {
1.710     albertel 8009:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8010:     #Trying to find the conditional for the file
1.620     albertel 8011:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8012: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8013:     if ($match) {
1.289     bowersj2 8014: 	return (1,$1);
                   8015:     } else {
1.434     www      8016: 	return (0,0);
1.289     bowersj2 8017:     }
1.12      www      8018: }
                   8019: 
1.427     www      8020: # --------------------------------------------------------- Get symb from alias
                   8021: 
                   8022: sub get_symb_from_alias {
                   8023:     my $symb=shift;
                   8024:     my ($map,$resid,$url)=&decode_symb($symb);
                   8025: # Already is a symb
                   8026:     if ($url) { return $symb; }
                   8027: # Must be an alias
                   8028:     my $aliassymb='';
                   8029:     my %bighash;
1.620     albertel 8030:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8031:                             &GDBM_READER(),0640)) {
                   8032:         my $rid=$bighash{'mapalias_'.$symb};
                   8033: 	if ($rid) {
                   8034: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8035: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8036: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8037: 	}
                   8038:         untie %bighash;
                   8039:     }
                   8040:     return $aliassymb;
                   8041: }
                   8042: 
1.12      www      8043: # ----------------------------------------------------------------- Define Role
                   8044: 
                   8045: sub definerole {
                   8046:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  8047:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8048:     foreach my $role (split(':',$sysrole)) {
                   8049: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8050:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8051:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8052: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8053:                return "refused:s:$crole&$cqual"; 
                   8054:             }
                   8055:         }
1.191     harris41 8056:     }
1.800     albertel 8057:     foreach my $role (split(':',$domrole)) {
                   8058: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8059:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8060:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8061: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8062:                return "refused:d:$crole&$cqual"; 
                   8063:             }
                   8064:         }
1.191     harris41 8065:     }
1.800     albertel 8066:     foreach my $role (split(':',$courole)) {
                   8067: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8068:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8069:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8070: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8071:                return "refused:c:$crole&$cqual"; 
                   8072:             }
                   8073:         }
1.191     harris41 8074:     }
1.1172.2.84  raeburn  8075:     my $uhome;
                   8076:     if (($uname ne '') && ($udom ne '')) {
                   8077:         $uhome = &homeserver($uname,$udom);
                   8078:         return $uhome if ($uhome eq 'no_host');
                   8079:     } else {
                   8080:         $uname = $env{'user.name'};
                   8081:         $udom = $env{'user.domain'};
                   8082:         $uhome = $env{'user.home'};
                   8083:     }
1.620     albertel 8084:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  8085:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8086:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  8087:     return reply($command,$uhome);
1.12      www      8088:   } else {
                   8089:     return 'refused';
                   8090:   }
1.105     harris41 8091: }
                   8092: 
                   8093: # ---------------- Make a metadata query against the network of library servers
                   8094: 
                   8095: sub metadata_query {
1.1172.2.33  raeburn  8096:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8097:     my %rhash;
1.845     albertel 8098:     my %libserv = &all_library();
1.244     matthew  8099:     my @server_list = (defined($server_array) ? @$server_array
                   8100:                                               : keys(%libserv) );
                   8101:     for my $server (@server_list) {
1.1172.2.33  raeburn  8102:         my $domains = '';
                   8103:         if (ref($domains_hash) eq 'HASH') {
                   8104:             $domains = $domains_hash->{$server};    
                   8105:         }
1.118     harris41 8106: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  8107: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8108: 	    $rhash{$server}=$reply;
                   8109: 	}
                   8110: 	else {
                   8111: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  8112: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8113: 			     $server);
                   8114: 	    $rhash{$server}=$reply;
                   8115: 	}
1.112     harris41 8116:     }
1.118     harris41 8117:     return \%rhash;
1.240     www      8118: }
                   8119: 
                   8120: # ----------------------------------------- Send log queries and wait for reply
                   8121: 
                   8122: sub log_query {
                   8123:     my ($uname,$udom,$query,%filters)=@_;
                   8124:     my $uhome=&homeserver($uname,$udom);
                   8125:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8126:     my $uhost=&hostname($uhome);
1.800     albertel 8127:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8128:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8129:                        $uhome);
1.479     albertel 8130:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8131:     return get_query_reply($queryid);
                   8132: }
                   8133: 
1.818     raeburn  8134: # -------------------------- Update MySQL table for portfolio file
                   8135: 
                   8136: sub update_portfolio_table {
1.821     raeburn  8137:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8138:     if ($group ne '') {
                   8139:         $file_name =~s /^\Q$group\E//;
                   8140:     }
1.818     raeburn  8141:     my $homeserver = &homeserver($uname,$udom);
                   8142:     my $queryid=
1.821     raeburn  8143:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8144:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8145:     my $reply = &get_query_reply($queryid);
                   8146:     return $reply;
                   8147: }
                   8148: 
1.899     raeburn  8149: # -------------------------- Update MySQL allusers table
                   8150: 
                   8151: sub update_allusers_table {
                   8152:     my ($uname,$udom,$names) = @_;
                   8153:     my $homeserver = &homeserver($uname,$udom);
                   8154:     my $queryid=
                   8155:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8156:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8157:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8158:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8159:                'generation='.&escape($names->{'generation'}).'%%'.
                   8160:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8161:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8162:     return;
1.899     raeburn  8163: }
                   8164: 
1.508     raeburn  8165: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8166: 
                   8167: sub fetch_enrollment_query {
1.511     raeburn  8168:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  8169:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8170:     my $maxtries = 1;
1.508     raeburn  8171:     if ($context eq 'automated') {
                   8172:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  8173:         $sleep = 2;
                   8174:         $loopmax = 100;
1.547     raeburn  8175:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8176:     } else {
                   8177:         $homeserver = &homeserver($cnum,$dom);
                   8178:     }
1.838     albertel 8179:     my $host=&hostname($homeserver);
1.506     raeburn  8180:     my $cmd = '';
1.1000    raeburn  8181:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8182:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8183:     }
                   8184:     $cmd =~ s/%%$//;
                   8185:     $cmd = &escape($cmd);
                   8186:     my $query = 'fetchenrollment';
1.620     albertel 8187:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8188:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8189:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8190:         return 'error: '.$queryid;
                   8191:     }
1.1172.2.93  raeburn  8192:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8193:     my $tries = 1;
                   8194:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  8195:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8196:         $tries ++;
                   8197:     }
1.526     raeburn  8198:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8199:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8200:     } else {
1.901     albertel 8201:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  8202:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8203:             foreach my $line (@responses) {
                   8204:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8205:                 $$replyref{$key} = $value;
                   8206:             }
                   8207:         } else {
1.1117    foxr     8208:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8209:             foreach my $line (@responses) {
                   8210:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8211:                 $$replyref{$key} = $value;
                   8212:                 if ($value > 0) {
1.800     albertel 8213:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8214:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8215:                         my $destname = $pathname.'/'.$filename;
                   8216:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8217:                         if ($xml_classlist =~ /^error/) {
                   8218:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8219:                         } else {
1.1172.2.96  raeburn  8220:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8221:                                 print FILE &unescape($xml_classlist);
                   8222:                                 close(FILE);
1.526     raeburn  8223:                             } else {
                   8224:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8225:                             }
                   8226:                         }
                   8227:                     }
                   8228:                 }
                   8229:             }
                   8230:         }
                   8231:         return 'ok';
                   8232:     }
                   8233:     return 'error';
                   8234: }
                   8235: 
1.242     www      8236: sub get_query_reply {
1.1172.2.79  raeburn  8237:     my ($queryid,$sleep,$loopmax) = @_;
                   8238:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8239:         $sleep = 0.2;
                   8240:     }
                   8241:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8242:         $loopmax = 100;
                   8243:     }
1.1117    foxr     8244:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8245:     my $reply='';
1.1172.2.79  raeburn  8246:     for (1..$loopmax) {
                   8247: 	sleep($sleep);
1.240     www      8248:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  8249: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8250: 		$reply = join('',<$fh>);
                   8251: 		close($fh);
1.240     www      8252: 	   } else { return 'error: reply_file_error'; }
1.242     www      8253:            return &unescape($reply);
                   8254: 	}
1.240     www      8255:     }
1.242     www      8256:     return 'timeout:'.$queryid;
1.240     www      8257: }
                   8258: 
                   8259: sub courselog_query {
1.241     www      8260: #
                   8261: # possible filters:
                   8262: # url: url or symb
                   8263: # username
                   8264: # domain
                   8265: # action: view, submit, grade
                   8266: # start: timestamp
                   8267: # end: timestamp
                   8268: #
1.240     www      8269:     my (%filters)=@_;
1.620     albertel 8270:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8271:     if ($filters{'url'}) {
                   8272: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8273:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8274:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8275:     }
1.620     albertel 8276:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8277:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8278:     return &log_query($cname,$cdom,'courselog',%filters);
                   8279: }
                   8280: 
                   8281: sub userlog_query {
1.858     raeburn  8282: #
                   8283: # possible filters:
                   8284: # action: log check role
                   8285: # start: timestamp
                   8286: # end: timestamp
                   8287: #
1.240     www      8288:     my ($uname,$udom,%filters)=@_;
                   8289:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8290: }
                   8291: 
1.506     raeburn  8292: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8293: 
                   8294: sub auto_run {
1.508     raeburn  8295:     my ($cnum,$cdom) = @_;
1.876     raeburn  8296:     my $response = 0;
                   8297:     my $settings;
                   8298:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8299:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8300:         $settings = $domconfig{'autoenroll'};
                   8301:         if ($settings->{'run'} eq '1') {
                   8302:             $response = 1;
                   8303:         }
                   8304:     } else {
1.934     raeburn  8305:         my $homeserver;
                   8306:         if (&is_course($cdom,$cnum)) {
                   8307:             $homeserver = &homeserver($cnum,$cdom);
                   8308:         } else {
                   8309:             $homeserver = &domain($cdom,'primary');
                   8310:         }
                   8311:         if ($homeserver ne 'no_host') {
                   8312:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8313:         }
1.876     raeburn  8314:     }
1.506     raeburn  8315:     return $response;
                   8316: }
1.776     albertel 8317: 
1.506     raeburn  8318: sub auto_get_sections {
1.508     raeburn  8319:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8320:     my $homeserver;
                   8321:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8322:         $homeserver = &homeserver($cnum,$cdom);
                   8323:     }
                   8324:     if (!defined($homeserver)) { 
                   8325:         if ($cdom =~ /^$match_domain$/) {
                   8326:             $homeserver = &domain($cdom,'primary');
                   8327:         }
                   8328:     }
                   8329:     my @secs;
                   8330:     if (defined($homeserver)) {
                   8331:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8332:         unless ($response eq 'refused') {
                   8333:             @secs = split(/:/,$response);
                   8334:         }
1.506     raeburn  8335:     }
                   8336:     return @secs;
                   8337: }
1.776     albertel 8338: 
1.506     raeburn  8339: sub auto_new_course {
1.1099    raeburn  8340:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8341:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8342:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8343:     return $response;
                   8344: }
1.776     albertel 8345: 
1.506     raeburn  8346: sub auto_validate_courseID {
1.508     raeburn  8347:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8348:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8349:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8350:     return $response;
                   8351: }
1.776     albertel 8352: 
1.1007    raeburn  8353: sub auto_validate_instcode {
1.1020    raeburn  8354:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8355:     my ($homeserver,$response);
                   8356:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8357:         $homeserver = &homeserver($cnum,$cdom);
                   8358:     }
                   8359:     if (!defined($homeserver)) {
                   8360:         if ($cdom =~ /^$match_domain$/) {
                   8361:             $homeserver = &domain($cdom,'primary');
                   8362:         }
                   8363:     }
1.1065    raeburn  8364:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8365:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  8366:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8367:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8368: }
                   8369: 
1.506     raeburn  8370: sub auto_create_password {
1.873     raeburn  8371:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8372:     my ($homeserver,$response);
1.506     raeburn  8373:     my $create_passwd = 0;
                   8374:     my $authchk = '';
1.873     raeburn  8375:     if ($udom =~ /^$match_domain$/) {
                   8376:         $homeserver = &domain($udom,'primary');
                   8377:     }
                   8378:     if ($homeserver eq '') {
                   8379:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8380:             $homeserver = &homeserver($cnum,$cdom);
                   8381:         }
                   8382:     }
                   8383:     if ($homeserver eq '') {
                   8384:         $authchk = 'nodomain';
1.506     raeburn  8385:     } else {
1.873     raeburn  8386:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8387:         if ($response eq 'refused') {
                   8388:             $authchk = 'refused';
                   8389:         } else {
1.901     albertel 8390:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8391:         }
1.506     raeburn  8392:     }
                   8393:     return ($authparam,$create_passwd,$authchk);
                   8394: }
                   8395: 
1.706     raeburn  8396: sub auto_photo_permission {
                   8397:     my ($cnum,$cdom,$students) = @_;
                   8398:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8399:     my ($outcome,$perm_reqd,$conditions) = 
                   8400: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8401:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8402: 	return (undef,undef);
                   8403:     }
1.706     raeburn  8404:     return ($outcome,$perm_reqd,$conditions);
                   8405: }
                   8406: 
                   8407: sub auto_checkphotos {
                   8408:     my ($uname,$udom,$pid) = @_;
                   8409:     my $homeserver = &homeserver($uname,$udom);
                   8410:     my ($result,$resulttype);
                   8411:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8412: 				   &escape($uname).':'.&escape($pid),
                   8413: 				   $homeserver));
1.709     albertel 8414:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8415: 	return (undef,undef);
                   8416:     }
1.706     raeburn  8417:     if ($outcome) {
                   8418:         ($result,$resulttype) = split(/:/,$outcome);
                   8419:     } 
                   8420:     return ($result,$resulttype);
                   8421: }
                   8422: 
                   8423: sub auto_photochoice {
                   8424:     my ($cnum,$cdom) = @_;
                   8425:     my $homeserver = &homeserver($cnum,$cdom);
                   8426:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8427: 						       &escape($cdom),
                   8428: 						       $homeserver)));
1.709     albertel 8429:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8430: 	return (undef,undef);
                   8431:     }
1.706     raeburn  8432:     return ($update,$comment);
                   8433: }
                   8434: 
                   8435: sub auto_photoupdate {
                   8436:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8437:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8438:     my $host=&hostname($homeserver);
1.706     raeburn  8439:     my $cmd = '';
                   8440:     my $maxtries = 1;
1.800     albertel 8441:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8442:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8443:     }
                   8444:     $cmd =~ s/%%$//;
                   8445:     $cmd = &escape($cmd);
                   8446:     my $query = 'institutionalphotos';
                   8447:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8448:     unless ($queryid=~/^\Q$host\E\_/) {
                   8449:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8450:         return 'error: '.$queryid;
                   8451:     }
                   8452:     my $reply = &get_query_reply($queryid);
                   8453:     my $tries = 1;
                   8454:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8455:         $reply = &get_query_reply($queryid);
                   8456:         $tries ++;
                   8457:     }
                   8458:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8459:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8460:     } else {
                   8461:         my @responses = split(/:/,$reply);
                   8462:         my $outcome = shift(@responses); 
                   8463:         foreach my $item (@responses) {
                   8464:             my ($key,$value) = split(/=/,$item);
                   8465:             $$photo{$key} = $value;
                   8466:         }
                   8467:         return $outcome;
                   8468:     }
                   8469:     return 'error';
                   8470: }
                   8471: 
1.521     raeburn  8472: sub auto_instcode_format {
1.793     albertel 8473:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8474: 	$cat_order) = @_;
1.521     raeburn  8475:     my $courses = '';
1.772     raeburn  8476:     my @homeservers;
1.521     raeburn  8477:     if ($caller eq 'global') {
1.841     albertel 8478: 	my %servers = &get_servers($codedom,'library');
                   8479: 	foreach my $tryserver (keys(%servers)) {
                   8480: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8481: 		push(@homeservers,$tryserver);
                   8482: 	    }
1.584     raeburn  8483:         }
1.1022    raeburn  8484:     } elsif ($caller eq 'requests') {
                   8485:         if ($codedom =~ /^$match_domain$/) {
                   8486:             my $chome = &domain($codedom,'primary');
                   8487:             unless ($chome eq 'no_host') {
                   8488:                 push(@homeservers,$chome);
                   8489:             }
                   8490:         }
1.521     raeburn  8491:     } else {
1.772     raeburn  8492:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8493:     }
1.793     albertel 8494:     foreach my $code (keys(%{$instcodes})) {
                   8495:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8496:     }
                   8497:     chop($courses);
1.772     raeburn  8498:     my $ok_response = 0;
                   8499:     my $response;
                   8500:     while (@homeservers > 0 && $ok_response == 0) {
                   8501:         my $server = shift(@homeservers); 
                   8502:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8503:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8504:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8505: 		split(/:/,$response);
1.772     raeburn  8506:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8507:             push(@{$codetitles},&str2array($codetitles_str));
                   8508:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8509:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8510:             $ok_response = 1;
                   8511:         }
                   8512:     }
                   8513:     if ($ok_response) {
1.521     raeburn  8514:         return 'ok';
1.772     raeburn  8515:     } else {
                   8516:         return $response;
1.521     raeburn  8517:     }
                   8518: }
                   8519: 
1.792     raeburn  8520: sub auto_instcode_defaults {
                   8521:     my ($domain,$returnhash,$code_order) = @_;
                   8522:     my @homeservers;
1.841     albertel 8523: 
                   8524:     my %servers = &get_servers($domain,'library');
                   8525:     foreach my $tryserver (keys(%servers)) {
                   8526: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8527: 	    push(@homeservers,$tryserver);
                   8528: 	}
1.792     raeburn  8529:     }
1.841     albertel 8530: 
1.792     raeburn  8531:     my $response;
1.841     albertel 8532:     foreach my $server (@homeservers) {
1.792     raeburn  8533:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8534:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8535: 	
                   8536: 	foreach my $pair (split(/\&/,$response)) {
                   8537: 	    my ($name,$value)=split(/\=/,$pair);
                   8538: 	    if ($name eq 'code_order') {
                   8539: 		@{$code_order} = split(/\&/,&unescape($value));
                   8540: 	    } else {
                   8541: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8542: 	    }
                   8543: 	}
                   8544: 	return 'ok';
1.792     raeburn  8545:     }
1.841     albertel 8546: 
                   8547:     return $response;
1.1003    raeburn  8548: }
                   8549: 
                   8550: sub auto_possible_instcodes {
1.1007    raeburn  8551:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8552:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8553:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8554:         return;
                   8555:     }
1.1003    raeburn  8556:     my (@homeservers,$uhome);
                   8557:     if (defined(&domain($domain,'primary'))) {
                   8558:         $uhome=&domain($domain,'primary');
                   8559:         push(@homeservers,&domain($domain,'primary'));
                   8560:     } else {
                   8561:         my %servers = &get_servers($domain,'library');
                   8562:         foreach my $tryserver (keys(%servers)) {
                   8563:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8564:                 push(@homeservers,$tryserver);
                   8565:             }
                   8566:         }
                   8567:     }
                   8568:     my $response;
                   8569:     foreach my $server (@homeservers) {
                   8570:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8571:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8572:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8573:             split(':',$response);
                   8574:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8575:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8576:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8577:             my ($name,$value)=split('=',$item);
                   8578:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8579:         }
                   8580:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8581:             my ($name,$value)=split('=',$item);
                   8582:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8583:         }
                   8584:         return 'ok';
                   8585:     }
                   8586:     return $response;
                   8587: }
1.792     raeburn  8588: 
1.1010    raeburn  8589: sub auto_courserequest_checks {
                   8590:     my ($dom) = @_;
1.1020    raeburn  8591:     my ($homeserver,%validations);
                   8592:     if ($dom =~ /^$match_domain$/) {
                   8593:         $homeserver = &domain($dom,'primary');
                   8594:     }
                   8595:     unless ($homeserver eq 'no_host') {
                   8596:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8597:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8598:             my @items = split(/&/,$response);
                   8599:             foreach my $item (@items) {
                   8600:                 my ($key,$value) = split('=',$item);
                   8601:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8602:             }
                   8603:         }
                   8604:     }
1.1010    raeburn  8605:     return %validations; 
                   8606: }
                   8607: 
1.1020    raeburn  8608: sub auto_courserequest_validation {
1.1172.2.43  raeburn  8609:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8610:     my ($homeserver,$response);
                   8611:     if ($dom =~ /^$match_domain$/) {
                   8612:         $homeserver = &domain($dom,'primary');
                   8613:     }
1.1172.2.43  raeburn  8614:     unless ($homeserver eq 'no_host') {
                   8615:         my $customdata;
                   8616:         if (ref($custominfo) eq 'HASH') {
                   8617:             $customdata = &freeze_escape($custominfo);
                   8618:         }
1.1020    raeburn  8619:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8620:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  8621:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8622:                                     $customdata,$homeserver));
1.1020    raeburn  8623:     }
                   8624:     return $response;
                   8625: }
                   8626: 
1.777     albertel 8627: sub auto_validate_class_sec {
1.918     raeburn  8628:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8629:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8630:     my $ownerlist;
                   8631:     if (ref($owners) eq 'ARRAY') {
                   8632:         $ownerlist = join(',',@{$owners});
                   8633:     } else {
                   8634:         $ownerlist = $owners;
                   8635:     }
1.773     raeburn  8636:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8637:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8638:     return $response;
                   8639: }
                   8640: 
1.1172.2.94  raeburn  8641: sub auto_validate_instclasses {
                   8642:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   8643:     my ($homeserver,%validations);
                   8644:     $homeserver = &homeserver($cnum,$cdom);
                   8645:     unless ($homeserver eq 'no_host') {
                   8646:         my $ownerlist;
                   8647:         if (ref($owners) eq 'ARRAY') {
                   8648:             $ownerlist = join(',',@{$owners});
                   8649:         } else {
                   8650:             $ownerlist = $owners;
                   8651:         }
                   8652:         if (ref($classesref) eq 'HASH') {
                   8653:             my $classes = &freeze_escape($classesref);
                   8654:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   8655:                                 ':'.$cdom.':'.$classes,$homeserver);
                   8656:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8657:                 my @items = split(/&/,$response);
                   8658:                 foreach my $item (@items) {
                   8659:                     my ($key,$value) = split('=',$item);
                   8660:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   8661:                 }
                   8662:             }
                   8663:         }
                   8664:     }
                   8665:     return %validations;
                   8666: }
                   8667: 
1.1172.2.38  raeburn  8668: sub auto_crsreq_update {
                   8669:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  8670:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  8671:     my ($homeserver,%crsreqresponse);
                   8672:     if ($cdom =~ /^$match_domain$/) {
                   8673:         $homeserver = &domain($cdom,'primary');
                   8674:     }
                   8675:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8676:         my $info;
                   8677:         if (ref($inbound) eq 'HASH') {
                   8678:             $info = &freeze_escape($inbound);
                   8679:         }
                   8680:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8681:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8682:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  8683:                             &escape($title).':'.&escape($code).':'.
                   8684:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  8685:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8686:             my @items = split(/&/,$response);
                   8687:             foreach my $item (@items) {
                   8688:                 my ($key,$value) = split('=',$item);
                   8689:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8690:             }
                   8691:         }
                   8692:     }
                   8693:     return \%crsreqresponse;
                   8694: }
                   8695: 
1.1172.2.78  raeburn  8696: sub auto_export_grades {
                   8697:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   8698:     my ($homeserver,%exportresponse);
                   8699:     if ($cdom =~ /^$match_domain$/) {
                   8700:         $homeserver = &domain($cdom,'primary');
                   8701:     }
                   8702:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8703:         my $info;
                   8704:         if (ref($inforef) eq 'HASH') {
                   8705:             $info = &freeze_escape($inforef);
                   8706:         }
                   8707:         if (ref($gradesref) eq 'HASH') {
                   8708:             my $grades = &freeze_escape($gradesref);
                   8709:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   8710:                                 $info.':'.$grades,$homeserver);
                   8711:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   8712:                 my @items = split(/&/,$response);
                   8713:                 foreach my $item (@items) {
                   8714:                     my ($key,$value) = split('=',$item);
                   8715:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   8716:                 }
                   8717:             }
                   8718:         }
                   8719:     }
                   8720:     return \%exportresponse;
                   8721: }
                   8722: 
1.1172.2.68  raeburn  8723: sub check_instcode_cloning {
                   8724:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   8725:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8726:         return;
                   8727:     }
                   8728:     my $canclone;
                   8729:     if (@{$code_order} > 0) {
                   8730:         my $instcoderegexp ='^';
                   8731:         my @clonecodes = split(/\&/,$cloner);
                   8732:         foreach my $item (@{$code_order}) {
                   8733:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   8734:                 foreach my $pair (@clonecodes) {
                   8735:                     my ($key,$val) = split(/\=/,$pair,2);
                   8736:                     $val = &unescape($val);
                   8737:                     if ($key eq $item) {
                   8738:                         $instcoderegexp .= '('.$val.')';
                   8739:                         last;
                   8740:                     }
                   8741:                 }
                   8742:             } else {
                   8743:                 $instcoderegexp .= $codedefaults->{$item};
                   8744:             }
                   8745:         }
                   8746:         $instcoderegexp .= '$';
                   8747:         my (@from,@to);
                   8748:         eval {
                   8749:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8750:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8751:         };
                   8752:         if ((@from > 0) && (@to > 0)) {
                   8753:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8754:             if (!@diffs) {
                   8755:                 $canclone = 1;
                   8756:             }
                   8757:         }
                   8758:     }
                   8759:     return $canclone;
                   8760: }
                   8761: 
                   8762: sub default_instcode_cloning {
                   8763:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   8764:     my (%codedefaults,@code_order,$canclone);
                   8765:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   8766:         %codedefaults = %{$codedefaultsref};
                   8767:         @code_order = @{$codeorderref};
                   8768:     } elsif ($clonedom) {
                   8769:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   8770:     }
                   8771:     if (($domdefclone) && (@code_order)) {
                   8772:         my @clonecodes = split(/\+/,$domdefclone);
                   8773:         my $instcoderegexp ='^';
                   8774:         foreach my $item (@code_order) {
                   8775:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   8776:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   8777:             } else {
                   8778:                 $instcoderegexp .= $codedefaults{$item};
                   8779:             }
                   8780:         }
                   8781:         $instcoderegexp .= '$';
                   8782:         my (@from,@to);
                   8783:         eval {
                   8784:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8785:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8786:         };
                   8787:         if ((@from > 0) && (@to > 0)) {
                   8788:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8789:             if (!@diffs) {
                   8790:                 $canclone = 1;
                   8791:             }
                   8792:         }
                   8793:     }
                   8794:     return $canclone;
                   8795: }
                   8796: 
1.679     raeburn  8797: # ------------------------------------------------------- Course Group routines
                   8798: 
                   8799: sub get_coursegroups {
1.809     raeburn  8800:     my ($cdom,$cnum,$group,$namespace) = @_;
                   8801:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  8802: }
                   8803: 
1.679     raeburn  8804: sub modify_coursegroup {
                   8805:     my ($cdom,$cnum,$groupsettings) = @_;
                   8806:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   8807: }
                   8808: 
1.809     raeburn  8809: sub toggle_coursegroup_status {
                   8810:     my ($cdom,$cnum,$group,$action) = @_;
                   8811:     my ($from_namespace,$to_namespace);
                   8812:     if ($action eq 'delete') {
                   8813:         $from_namespace = 'coursegroups';
                   8814:         $to_namespace = 'deleted_groups';
                   8815:     } else {
                   8816:         $from_namespace = 'deleted_groups';
                   8817:         $to_namespace = 'coursegroups';
                   8818:     }
                   8819:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  8820:     if (my $tmp = &error(%curr_group)) {
                   8821:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   8822:         return ('read error',$tmp);
                   8823:     } else {
                   8824:         my %savedsettings = %curr_group; 
1.809     raeburn  8825:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  8826:         my $deloutcome;
                   8827:         if ($result eq 'ok') {
1.809     raeburn  8828:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  8829:         } else {
                   8830:             return ('write error',$result);
                   8831:         }
                   8832:         if ($deloutcome eq 'ok') {
                   8833:             return 'ok';
                   8834:         } else {
                   8835:             return ('delete error',$deloutcome);
                   8836:         }
                   8837:     }
                   8838: }
                   8839: 
1.679     raeburn  8840: sub modify_group_roles {
1.957     raeburn  8841:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  8842:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   8843:     my $role = 'gr/'.&escape($userprivs);
                   8844:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  8845:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  8846:     if ($result eq 'ok') {
                   8847:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   8848:     }
1.679     raeburn  8849:     return $result;
                   8850: }
                   8851: 
                   8852: sub modify_coursegroup_membership {
                   8853:     my ($cdom,$cnum,$membership) = @_;
                   8854:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   8855:     return $result;
                   8856: }
                   8857: 
1.682     raeburn  8858: sub get_active_groups {
                   8859:     my ($udom,$uname,$cdom,$cnum) = @_;
                   8860:     my $now = time;
                   8861:     my %groups = ();
                   8862:     foreach my $key (keys(%env)) {
1.811     albertel 8863:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  8864:             my ($start,$end) = split(/\./,$env{$key});
                   8865:             if (($end!=0) && ($end<$now)) { next; }
                   8866:             if (($start!=0) && ($start>$now)) { next; }
                   8867:             if ($1 eq $cdom && $2 eq $cnum) {
                   8868:                 $groups{$3} = $env{$key} ;
                   8869:             }
                   8870:         }
                   8871:     }
                   8872:     return %groups;
                   8873: }
                   8874: 
1.683     raeburn  8875: sub get_group_membership {
                   8876:     my ($cdom,$cnum,$group) = @_;
                   8877:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   8878: }
                   8879: 
                   8880: sub get_users_groups {
                   8881:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  8882:     my @usersgroups;
1.683     raeburn  8883:     my $cachetime=1800;
                   8884: 
                   8885:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  8886:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   8887:     if (defined($cached)) {
1.734     albertel 8888:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  8889:     } else {  
                   8890:         $grouplist = '';
1.816     raeburn  8891:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  8892:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  8893:         my $access_end = $env{'course.'.$courseid.
                   8894:                               '.default_enrollment_end_date'};
                   8895:         my $now = time;
                   8896:         foreach my $key (keys(%roleshash)) {
                   8897:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   8898:                 my $group = $1;
                   8899:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   8900:                     my $start = $2;
                   8901:                     my $end = $1;
                   8902:                     if ($start == -1) { next; } # deleted from group
                   8903:                     if (($start!=0) && ($start>$now)) { next; }
                   8904:                     if (($end!=0) && ($end<$now)) {
                   8905:                         if ($access_end && $access_end < $now) {
                   8906:                             if ($access_end - $end < 86400) {
                   8907:                                 push(@usersgroups,$group);
1.733     raeburn  8908:                             }
                   8909:                         }
1.817     raeburn  8910:                         next;
1.733     raeburn  8911:                     }
1.817     raeburn  8912:                     push(@usersgroups,$group);
1.683     raeburn  8913:                 }
                   8914:             }
                   8915:         }
1.817     raeburn  8916:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8917:         $grouplist = join(':',@usersgroups);
                   8918:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8919:     }
1.733     raeburn  8920:     return @usersgroups;
1.683     raeburn  8921: }
                   8922: 
                   8923: sub devalidate_getgroups_cache {
                   8924:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8925:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8926: 
1.683     raeburn  8927:     my $hashid="$udom:$uname:$courseid";
                   8928:     &devalidate_cache_new('getgroups',$hashid);
                   8929: }
                   8930: 
1.12      www      8931: # ------------------------------------------------------------------ Plain Text
                   8932: 
                   8933: sub plaintext {
1.988     raeburn  8934:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8935:     if ($short =~ m{^cr/}) {
1.758     albertel 8936: 	return (split('/',$short))[-1];
                   8937:     }
1.742     raeburn  8938:     if (!defined($cid)) {
                   8939:         $cid = $env{'request.course.id'};
                   8940:     }
                   8941:     my %rolenames = (
1.1008    raeburn  8942:                       Course    => 'std',
                   8943:                       Community => 'alt1',
1.742     raeburn  8944:                     );
1.1037    raeburn  8945:     if ($cid ne '') {
                   8946:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8947:             unless ($forcedefault) {
                   8948:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8949:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8950:                 return &Apache::lonlocal::mt($roletext);
                   8951:             }
                   8952:         }
                   8953:     }
                   8954:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8955:         (defined($rolenames{$type})) && 
                   8956:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8957:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8958:     } elsif ($cid ne '') {
                   8959:         my $crstype = $env{'course.'.$cid.'.type'};
                   8960:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8961:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8962:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8963:         }
1.742     raeburn  8964:     }
1.1037    raeburn  8965:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8966: }
                   8967: 
                   8968: # ----------------------------------------------------------------- Assign Role
                   8969: 
                   8970: sub assignrole {
1.957     raeburn  8971:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8972:         $context)=@_;
1.21      www      8973:     my $mrole;
                   8974:     if ($role =~ /^cr\//) {
1.393     www      8975:         my $cwosec=$url;
1.811     albertel 8976:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8977: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8978:            my $refused = 1;
                   8979:            if ($context eq 'requestcourses') {
                   8980:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8981:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8982:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8983:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8984:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8985:                            if ($crsenv{'internal.courseowner'} eq
                   8986:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8987:                                $refused = '';
                   8988:                            }
                   8989:                        }
                   8990:                    }
                   8991:                }
                   8992:            }
                   8993:            if ($refused) {
                   8994:                &logthis('Refused custom assignrole: '.
                   8995:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8996:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8997:                return 'refused';
                   8998:            }
1.104     www      8999:         }
1.21      www      9000:         $mrole='cr';
1.678     raeburn  9001:     } elsif ($role =~ /^gr\//) {
                   9002:         my $cwogrp=$url;
1.811     albertel 9003:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9004:         unless (&allowed('mdg',$cwogrp)) {
                   9005:             &logthis('Refused group assignrole: '.
                   9006:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9007:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9008:             return 'refused';
                   9009:         }
                   9010:         $mrole='gr';
1.21      www      9011:     } else {
1.82      www      9012:         my $cwosec=$url;
1.811     albertel 9013:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9014:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9015:             my $refused;
                   9016:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9017:                 if (!(&allowed('c'.$role,$url))) {
                   9018:                     $refused = 1;
                   9019:                 }
                   9020:             } else {
                   9021:                 $refused = 1;
                   9022:             }
1.947     raeburn  9023:             if ($refused) {
1.1045    raeburn  9024:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9025:                 if (!$selfenroll && $context eq 'course') {
                   9026:                     my %crsenv;
                   9027:                     if ($role eq 'cc' || $role eq 'co') {
                   9028:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9029:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9030:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9031:                                 if ($crsenv{'internal.courseowner'} eq 
                   9032:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9033:                                     $refused = '';
                   9034:                                 }
                   9035:                             }
                   9036:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9037:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9038:                                 if ($crsenv{'internal.courseowner'} eq 
                   9039:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9040:                                     $refused = '';
                   9041:                                 }
                   9042:                             }
                   9043:                         }
                   9044:                     }
                   9045:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  9046:                     $refused = '';
1.1017    raeburn  9047:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9048:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9049:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9050:                         my $wrongcc;
                   9051:                         if ($cnum =~ /^$match_community$/) {
                   9052:                             $wrongcc = 1 if ($role eq 'cc');
                   9053:                         } else {
                   9054:                             $wrongcc = 1 if ($role eq 'co');
                   9055:                         }
                   9056:                         unless ($wrongcc) {
                   9057:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9058:                             if ($crsenv{'internal.courseowner'} eq 
                   9059:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9060:                                 $refused = '';
                   9061:                             }
1.1017    raeburn  9062:                         }
                   9063:                     }
1.1172.2.9  raeburn  9064:                 } elsif ($context eq 'requestauthor') {
                   9065:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   9066:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9067:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9068:                             $refused = '';
                   9069:                         } else {
                   9070:                             my %domdefaults = &get_domain_defaults($udom);
                   9071:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9072:                                 my $checkbystatus;
                   9073:                                 if ($env{'user.adv'}) {
                   9074:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9075:                                     if ($disposition eq 'automatic') {
                   9076:                                         $refused = '';
                   9077:                                     } elsif ($disposition eq '') {
                   9078:                                         $checkbystatus = 1;
                   9079:                                     }
                   9080:                                 } else {
                   9081:                                     $checkbystatus = 1;
                   9082:                                 }
                   9083:                                 if ($checkbystatus) {
                   9084:                                     if ($env{'environment.inststatus'}) {
                   9085:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9086:                                         foreach my $type (@inststatuses) {
                   9087:                                             if (($type ne '') &&
                   9088:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9089:                                                 $refused = '';
                   9090:                                             }
                   9091:                                         }
                   9092:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9093:                                         $refused = '';
                   9094:                                     }
                   9095:                                 }
                   9096:                             }
                   9097:                         }
                   9098:                     }
1.1017    raeburn  9099:                 }
                   9100:                 if ($refused) {
1.947     raeburn  9101:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9102:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9103: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9104:                     return 'refused';
                   9105:                 }
1.932     raeburn  9106:             }
1.1131    raeburn  9107:         } elsif ($role eq 'au') {
                   9108:             if ($url ne '/'.$udom.'/') {
                   9109:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9110:                          ' to assign author role for '.$uname.':'.$udom.
                   9111:                          ' in domain: '.$url.' refused (wrong domain).');
                   9112:                 return 'refused';
                   9113:             }
1.104     www      9114:         }
1.21      www      9115:         $mrole=$role;
                   9116:     }
1.620     albertel 9117:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9118:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9119:     if ($end) { $command.='_'.$end; }
1.21      www      9120:     if ($start) {
                   9121: 	if ($end) { 
1.81      www      9122:            $command.='_'.$start; 
1.21      www      9123:         } else {
1.81      www      9124:            $command.='_0_'.$start;
1.21      www      9125:         }
                   9126:     }
1.739     raeburn  9127:     my $origstart = $start;
                   9128:     my $origend = $end;
1.957     raeburn  9129:     my $delflag;
1.357     www      9130: # actually delete
                   9131:     if ($deleteflag) {
1.373     www      9132: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9133: # modify command to delete the role
1.620     albertel 9134:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9135:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9136: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9137: # set start and finish to negative values for userrolelog
                   9138:            $start=-1;
                   9139:            $end=-1;
1.957     raeburn  9140:            $delflag = 1;
1.357     www      9141:         }
                   9142:     }
                   9143: # send command
1.349     www      9144:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9145: # log new user role if status is ok
1.349     www      9146:     if ($answer eq 'ok') {
1.663     raeburn  9147: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  9148:         if (($role eq 'cc') || ($role eq 'in') ||
                   9149:             ($role eq 'ep') || ($role eq 'ad') ||
                   9150:             ($role eq 'ta') || ($role eq 'st') ||
                   9151:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9152:             ($role eq 'co')) {
1.1172.2.13  raeburn  9153: # for course roles, perform group memberships changes triggered by role change.
                   9154:             unless ($role =~ /^gr/) {
                   9155:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9156:                                                  $origstart,$selfenroll,$context);
                   9157:             }
1.1172.2.9  raeburn  9158:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9159:                            $selfenroll,$context);
                   9160:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  9161:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9162:                  ($role eq 'da')) {
1.1172.2.9  raeburn  9163:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9164:                            $context);
                   9165:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9166:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9167:                              $context);
                   9168:         }
1.1053    raeburn  9169:         if ($role eq 'cc') {
                   9170:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9171:         }
1.349     www      9172:     }
                   9173:     return $answer;
1.169     harris41 9174: }
                   9175: 
1.1053    raeburn  9176: sub autoupdate_coowners {
                   9177:     my ($url,$end,$start,$uname,$udom) = @_;
                   9178:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9179:     if (($cdom ne '') && ($cnum ne '')) {
                   9180:         my $now = time;
                   9181:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9182:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9183:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9184:             my $instcode = $coursehash{'internal.coursecode'};
                   9185:             if ($instcode ne '') {
1.1056    raeburn  9186:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9187:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9188:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9189:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9190:                         if ($result eq 'valid') {
                   9191:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9192:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9193:                                     push(@newcoowners,$coowner);
                   9194:                                 }
                   9195:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9196:                                     push(@newcoowners,$uname.':'.$udom);
                   9197:                                 }
                   9198:                                 @newcoowners = sort(@newcoowners);
                   9199:                             } else {
                   9200:                                 push(@newcoowners,$uname.':'.$udom);
                   9201:                             }
                   9202:                         } else {
                   9203:                             if ($coursehash{'internal.co-owners'}) {
                   9204:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9205:                                     unless ($coowner eq $uname.':'.$udom) {
                   9206:                                         push(@newcoowners,$coowner);
                   9207:                                     }
                   9208:                                 }
                   9209:                                 unless (@newcoowners > 0) {
                   9210:                                     $delcoowners = 1;
                   9211:                                     $coowners = '';
                   9212:                                 }
                   9213:                             }
                   9214:                         }
                   9215:                         if (@newcoowners || $delcoowners) {
                   9216:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9217:                                             $delcoowners,@newcoowners);
                   9218:                         }
                   9219:                     }
                   9220:                 }
                   9221:             }
                   9222:         }
                   9223:     }
                   9224: }
                   9225: 
                   9226: sub store_coowners {
                   9227:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9228:     my $cid = $cdom.'_'.$cnum;
                   9229:     my ($coowners,$delresult,$putresult);
                   9230:     if (@newcoowners) {
                   9231:         $coowners = join(',',@newcoowners);
                   9232:         my %coownershash = (
                   9233:                             'internal.co-owners' => $coowners,
                   9234:                            );
                   9235:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9236:         if ($putresult eq 'ok') {
                   9237:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9238:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9239:             }
                   9240:         }
                   9241:     }
                   9242:     if ($delcoowners) {
                   9243:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9244:         if ($delresult eq 'ok') {
                   9245:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9246:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9247:             }
                   9248:         }
                   9249:     }
                   9250:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9251:         my %crsinfo =
                   9252:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9253:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9254:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9255:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9256:         }
                   9257:     }
                   9258: }
                   9259: 
1.169     harris41 9260: # -------------------------------------------------- Modify user authentication
1.197     www      9261: # Overrides without validation
                   9262: 
1.169     harris41 9263: sub modifyuserauth {
                   9264:     my ($udom,$uname,$umode,$upass)=@_;
                   9265:     my $uhome=&homeserver($uname,$udom);
1.197     www      9266:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   9267:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9268:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9269:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9270:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9271: 		     &escape($upass),$uhome);
1.620     albertel 9272:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9273:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9274:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9275:     &log($udom,,$uname,$uhome,
1.620     albertel 9276:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9277:                                      $env{'user.name'}.', '.$umode.
1.197     www      9278:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9279:     unless ($reply eq 'ok') {
1.197     www      9280:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9281: 	return 'error: '.$reply;
                   9282:     }   
1.170     harris41 9283:     return 'ok';
1.80      www      9284: }
                   9285: 
1.81      www      9286: # --------------------------------------------------------------- Modify a user
1.80      www      9287: 
1.81      www      9288: sub modifyuser {
1.206     matthew  9289:     my ($udom,    $uname, $uid,
                   9290:         $umode,   $upass, $first,
                   9291:         $middle,  $last,  $gene,
1.1058    raeburn  9292:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9293:     $udom= &LONCAPA::clean_domain($udom);
                   9294:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9295:     my $showcandelete = 'none';
                   9296:     if (ref($candelete) eq 'ARRAY') {
                   9297:         if (@{$candelete} > 0) {
                   9298:             $showcandelete = join(', ',@{$candelete});
                   9299:         }
                   9300:     }
1.81      www      9301:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9302:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9303: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9304:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9305:                                      ' desiredhome not specified'). 
1.620     albertel 9306:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9307:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9308:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9309:     my $newuser;
                   9310:     if ($uhome eq 'no_host') {
                   9311:         $newuser = 1;
                   9312:     }
1.80      www      9313: # ----------------------------------------------------------------- Create User
1.406     albertel 9314:     if (($uhome eq 'no_host') && 
                   9315: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      9316:         my $unhome='';
1.844     albertel 9317:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9318:             $unhome = $desiredhome;
1.620     albertel 9319: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9320: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9321:         } else { # load balancing routine for determining $unhome
1.81      www      9322:             my $loadm=10000000;
1.841     albertel 9323: 	    my %servers = &get_servers($udom,'library');
                   9324: 	    foreach my $tryserver (keys(%servers)) {
                   9325: 		my $answer=reply('load',$tryserver);
                   9326: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9327: 		    $loadm=$answer;
                   9328: 		    $unhome=$tryserver;
                   9329: 		}
1.80      www      9330: 	    }
                   9331:         }
                   9332:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9333: 	    return 'error: unable to find a home server for '.$uname.
                   9334:                    ' in domain '.$udom;
1.80      www      9335:         }
                   9336:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9337:                          &escape($upass),$unhome);
                   9338: 	unless ($reply eq 'ok') {
                   9339:             return 'error: '.$reply;
                   9340:         }   
1.230     stredwic 9341:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9342:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9343: 	    return 'error: unable verify users home machine.';
1.80      www      9344:         }
1.209     matthew  9345:     }   # End of creation of new user
1.80      www      9346: # ---------------------------------------------------------------------- Add ID
                   9347:     if ($uid) {
                   9348:        $uid=~tr/A-Z/a-z/;
                   9349:        my %uidhash=&idrget($udom,$uname);
1.196     www      9350:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9351:          && (!$forceid)) {
1.80      www      9352: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9353: 	      return 'error: user id "'.$uid.'" does not match '.
                   9354:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9355:           }
                   9356:        } else {
                   9357: 	  &idput($udom,($uname => $uid));
                   9358:        }
                   9359:     }
                   9360: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9361:     my @tmp=&get('environment',
1.899     raeburn  9362: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9363:                     'permanentemail','inststatus'],
1.134     albertel 9364: 		   $udom,$uname);
1.1075    raeburn  9365:     my (%names,%oldnames);
1.313     matthew  9366:     if ($tmp[0] =~ m/^error:.*/) { 
                   9367:         %names=(); 
                   9368:     } else {
                   9369:         %names = @tmp;
1.1075    raeburn  9370:         %oldnames = %names;
1.313     matthew  9371:     }
1.388     www      9372: #
1.1058    raeburn  9373: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9374: # of users did not contain them), do not overwrite existing values
                   9375: # unless field is in $candelete array ref.  
                   9376: #
                   9377: 
                   9378:     my @fields = ('firstname','middlename','lastname','generation',
                   9379:                   'permanentemail','id');
                   9380:     my %newvalues;
                   9381:     if (ref($candelete) eq 'ARRAY') {
                   9382:         foreach my $field (@fields) {
                   9383:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9384:                 if ($field eq 'firstname') {
                   9385:                     $names{$field} = $first;
                   9386:                 } elsif ($field eq 'middlename') {
                   9387:                     $names{$field} = $middle;
                   9388:                 } elsif ($field eq 'lastname') {
                   9389:                     $names{$field} = $last;
                   9390:                 } elsif ($field eq 'generation') { 
                   9391:                     $names{$field} = $gene;
                   9392:                 } elsif ($field eq 'permanentemail') {
                   9393:                     $names{$field} = $email;
                   9394:                 } elsif ($field eq 'id') {
                   9395:                     $names{$field}  = $uid;
                   9396:                 }
                   9397:             }
                   9398:         }
                   9399:     }
1.388     www      9400:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9401:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9402:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9403:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9404:     if ($email) {
                   9405:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9406:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9407:     }
1.899     raeburn  9408:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9409:     if (defined($inststatus)) {
                   9410:         $names{'inststatus'} = '';
                   9411:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9412:         if (ref($usertypes) eq 'HASH') {
                   9413:             my @okstatuses; 
                   9414:             foreach my $item (split(/:/,$inststatus)) {
                   9415:                 if (defined($usertypes->{$item})) {
                   9416:                     push(@okstatuses,$item);  
                   9417:                 }
                   9418:             }
                   9419:             if (@okstatuses) {
                   9420:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9421:             }
                   9422:         }
                   9423:     }
1.1075    raeburn  9424:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9425:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9426:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9427:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9428:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9429:     } else {
                   9430:         $logmsg .= ' during self creation';
                   9431:     }
1.1075    raeburn  9432:     my $changed;
                   9433:     if ($newuser) {
                   9434:         $changed = 1;
                   9435:     } else {
                   9436:         foreach my $field (@fields) {
                   9437:             if ($names{$field} ne $oldnames{$field}) {
                   9438:                 $changed = 1;
                   9439:                 last;
                   9440:             }
                   9441:         }
                   9442:     }
                   9443:     unless ($changed) {
                   9444:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9445:         &logthis($logmsg);
                   9446:         return 'ok';
                   9447:     }
                   9448:     my $reply = &put('environment', \%names, $udom,$uname);
                   9449:     if ($reply ne 'ok') { 
                   9450:         return 'error: '.$reply;
                   9451:     }
1.1087    raeburn  9452:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9453:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9454:     }
1.1075    raeburn  9455:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9456:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9457:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9458:     &logthis($logmsg);
1.134     albertel 9459:     return 'ok';
1.80      www      9460: }
                   9461: 
1.81      www      9462: # -------------------------------------------------------------- Modify student
1.80      www      9463: 
1.81      www      9464: sub modifystudent {
                   9465:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9466:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  9467:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9468:     if (!$cid) {
1.620     albertel 9469: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9470: 	    return 'not_in_class';
                   9471: 	}
1.80      www      9472:     }
                   9473: # --------------------------------------------------------------- Make the user
1.81      www      9474:     my $reply=&modifyuser
1.209     matthew  9475: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9476:          $desiredhome,$email,$inststatus);
1.80      www      9477:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9478:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  9479:     # student's environment
1.297     matthew  9480:     $uid = undef if (!$forceid);
1.455     albertel 9481:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  9482: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  9483:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9484:     return $reply;
                   9485: }
                   9486: 
                   9487: sub modify_student_enrollment {
1.1172.2.23  raeburn  9488:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  9489:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9490:     my ($cdom,$cnum,$chome);
                   9491:     if (!$cid) {
1.620     albertel 9492: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9493: 	    return 'not_in_class';
                   9494: 	}
1.620     albertel 9495: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9496: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9497:     } else {
                   9498: 	($cdom,$cnum)=split(/_/,$cid);
                   9499:     }
1.620     albertel 9500:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9501:     if (!$chome) {
1.457     raeburn  9502: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9503:     }
1.455     albertel 9504:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9505:     # Make sure the user exists
1.81      www      9506:     my $uhome=&homeserver($uname,$udom);
                   9507:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9508: 	return 'error: no such user';
                   9509:     }
1.297     matthew  9510:     # Get student data if we were not given enough information
                   9511:     if (!defined($first)  || $first  eq '' || 
                   9512:         !defined($last)   || $last   eq '' || 
                   9513:         !defined($uid)    || $uid    eq '' || 
                   9514:         !defined($middle) || $middle eq '' || 
                   9515:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9516:         # They did not supply us with enough data to enroll the student, so
                   9517:         # we need to pick up more information.
1.297     matthew  9518:         my %tmp = &get('environment',
1.294     matthew  9519:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9520:                        ,$udom,$uname);
                   9521: 
1.800     albertel 9522:         #foreach my $key (keys(%tmp)) {
                   9523:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9524:         #}
1.294     matthew  9525:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9526:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9527:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9528:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9529:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9530:     }
1.556     albertel 9531:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9532:     my $user = "$uname:$udom";
                   9533:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9534:     my $reply=cput('classlist',
1.1148    raeburn  9535: 		   {$user => 
1.1172.2.76  raeburn  9536: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 9537: 		   $cdom,$cnum);
1.1148    raeburn  9538:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9539:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9540:     } else { 
1.81      www      9541: 	return 'error: '.$reply;
                   9542:     }
1.297     matthew  9543:     # Add student role to user
1.83      www      9544:     my $uurl='/'.$cid;
1.81      www      9545:     $uurl=~s/\_/\//g;
                   9546:     if ($usec) {
                   9547: 	$uurl.='/'.$usec;
                   9548:     }
1.1148    raeburn  9549:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9550:                              $selfenroll,$context);
                   9551:     if ($result ne 'ok') {
                   9552:         if ($old_entry{$user} ne '') {
                   9553:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9554:         } else {
                   9555:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9556:         }
                   9557:     }
                   9558:     return $result; 
1.21      www      9559: }
                   9560: 
1.556     albertel 9561: sub format_name {
                   9562:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9563:     my $name;
                   9564:     if ($first ne 'lastname') {
                   9565: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9566:     } else {
                   9567: 	if ($lastname=~/\S/) {
                   9568: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9569: 	    $name=~s/\s+,/,/;
                   9570: 	} else {
                   9571: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9572: 	}
                   9573:     }
                   9574:     $name=~s/^\s+//;
                   9575:     $name=~s/\s+$//;
                   9576:     $name=~s/\s+/ /g;
                   9577:     return $name;
                   9578: }
                   9579: 
1.84      www      9580: # ------------------------------------------------- Write to course preferences
                   9581: 
                   9582: sub writecoursepref {
                   9583:     my ($courseid,%prefs)=@_;
                   9584:     $courseid=~s/^\///;
                   9585:     $courseid=~s/\_/\//g;
                   9586:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9587:     my $chome=homeserver($cnum,$cdomain);
                   9588:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9589: 	return 'error: no such course';
                   9590:     }
                   9591:     my $cstring='';
1.800     albertel 9592:     foreach my $pref (keys(%prefs)) {
                   9593: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9594:     }
1.84      www      9595:     $cstring=~s/\&$//;
                   9596:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9597: }
                   9598: 
                   9599: # ---------------------------------------------------------- Make/modify course
                   9600: 
                   9601: sub createcourse {
1.741     raeburn  9602:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  9603:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      9604:     $url=&declutter($url);
                   9605:     my $cid='';
1.1028    raeburn  9606:     if ($context eq 'requestcourses') {
                   9607:         my $can_create = 0;
                   9608:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9609:         if ($udom eq $ownerdom) {
                   9610:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   9611:                                   $context)) {
                   9612:                 $can_create = 1;
                   9613:             }
                   9614:         } else {
                   9615:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9616:                                            $category);
                   9617:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   9618:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   9619:                 if (@curr > 0) {
                   9620:                     my @options = qw(approval validate autolimit);
                   9621:                     my $optregex = join('|',@options);
                   9622:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   9623:                         $can_create = 1;
                   9624:                     }
                   9625:                 }
                   9626:             }
                   9627:         }
                   9628:         if ($can_create) {
                   9629:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   9630:                 unless (&allowed('ccc',$udom)) {
                   9631:                     return 'refused'; 
                   9632:                 }
1.1017    raeburn  9633:             }
                   9634:         } else {
                   9635:             return 'refused';
                   9636:         }
1.1028    raeburn  9637:     } elsif (!&allowed('ccc',$udom)) {
                   9638:         return 'refused';
1.84      www      9639:     }
1.1011    raeburn  9640: # --------------------------------------------------------------- Get Unique ID
                   9641:     my $uname;
                   9642:     if ($cnum =~ /^$match_courseid$/) {
                   9643:         my $chome=&homeserver($cnum,$udom,'true');
                   9644:         if (($chome eq '') || ($chome eq 'no_host')) {
                   9645:             $uname = $cnum;
                   9646:         } else {
1.1038    raeburn  9647:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9648:         }
                   9649:     } else {
1.1038    raeburn  9650:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9651:     }
                   9652:     return $uname if ($uname =~ /^error/);
                   9653: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  9654:     if (!defined($course_server)) {
                   9655:         if (defined(&domain($udom,'primary'))) {
                   9656:             $course_server = &domain($udom,'primary');
                   9657:         } else {
                   9658:             $course_server = $env{'user.home'}; 
                   9659:         }
                   9660:     }
                   9661:     my %host_servers =
                   9662:         &Apache::lonnet::get_servers($udom,'library');
                   9663:     unless ($host_servers{$course_server}) {
                   9664:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  9665:     }
1.84      www      9666: # ------------------------------------------------------------- Make the course
                   9667:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  9668:                       $course_server);
1.84      www      9669:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  9670:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      9671:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9672: 	return 'error: no such course';
                   9673:     }
1.271     www      9674: # ----------------------------------------------------------------- Course made
1.516     raeburn  9675: # log existence
1.1029    raeburn  9676:     my $now = time;
1.918     raeburn  9677:     my $newcourse = {
                   9678:                     $udom.'_'.$uname => {
1.921     raeburn  9679:                                      description => $description,
                   9680:                                      inst_code   => $inst_code,
                   9681:                                      owner       => $course_owner,
                   9682:                                      type        => $crstype,
1.1029    raeburn  9683:                                      creator     => $env{'user.name'}.':'.
                   9684:                                                     $env{'user.domain'},
                   9685:                                      created     => $now,
                   9686:                                      context     => $context,
1.918     raeburn  9687:                                                 },
                   9688:                     };
1.921     raeburn  9689:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      9690: # set toplevel url
1.271     www      9691:     my $topurl=$url;
                   9692:     unless ($nonstandard) {
                   9693: # ------------------------------------------ For standard courses, make top url
                   9694:         my $mapurl=&clutter($url);
1.278     www      9695:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 9696:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      9697: <map>
                   9698: <resource id="1" type="start"></resource>
                   9699: <resource id="2" src="$mapurl"></resource>
                   9700: <resource id="3" type="finish"></resource>
                   9701: <link index="1" from="1" to="2"></link>
                   9702: <link index="2" from="2" to="3"></link>
                   9703: </map>
                   9704: ENDINITMAP
                   9705:         $topurl=&declutter(
1.638     albertel 9706:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      9707:                           );
                   9708:     }
                   9709: # ----------------------------------------------------------- Write preferences
1.84      www      9710:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  9711:                      ('description'              => $description,
                   9712:                       'url'                      => $topurl,
                   9713:                       'internal.creator'         => $env{'user.name'}.':'.
                   9714:                                                     $env{'user.domain'},
                   9715:                       'internal.created'         => $now,
                   9716:                       'internal.creationcontext' => $context)
                   9717:                     );
1.84      www      9718:     return '/'.$udom.'/'.$uname;
                   9719: }
                   9720: 
1.1011    raeburn  9721: # ------------------------------------------------------------------- Create ID
                   9722: sub generate_coursenum {
1.1038    raeburn  9723:     my ($udom,$crstype) = @_;
1.1011    raeburn  9724:     my $domdesc = &domain($udom);
                   9725:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  9726:     my $first;
                   9727:     if ($crstype eq 'Community') {
                   9728:         $first = '0';
                   9729:     } else {
                   9730:         $first = int(1+rand(9)); 
                   9731:     } 
                   9732:     my $uname=$first.
1.1011    raeburn  9733:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9734:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9735:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9736: # ----------------------------------------------- Make sure that does not exist
                   9737:     my $uhome=&homeserver($uname,$udom,'true');
                   9738:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  9739:         if ($crstype eq 'Community') {
                   9740:             $first = '0';
                   9741:         } else {
                   9742:             $first = int(1+rand(9));
                   9743:         }
                   9744:         $uname=$first.
1.1011    raeburn  9745:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9746:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9747:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9748:         $uhome=&homeserver($uname,$udom,'true');
                   9749:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   9750:             return 'error: unable to generate unique course-ID';
                   9751:         }
                   9752:     }
                   9753:     return $uname;
                   9754: }
                   9755: 
1.813     albertel 9756: sub is_course {
1.1167    droeschl 9757:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   9758:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  9759:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   9760:     my $uhome=&homeserver($cnum,$cdom);
                   9761:     my $iscourse;
                   9762:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   9763:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   9764:     } else {
                   9765:         my $hashid = $cdom.':'.$cnum;
                   9766:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   9767:         unless (defined($cached)) {
                   9768:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   9769:                                         $cnum,undef,undef,'.');
                   9770:             $iscourse = 0;
                   9771:             if (exists($courses{$cdom.'_'.$cnum})) {
                   9772:                 $iscourse = 1;
                   9773:             }
                   9774:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   9775:         }
                   9776:     }
                   9777:     return unless($iscourse);
1.1167    droeschl 9778:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 9779: }
                   9780: 
1.1015    raeburn  9781: sub store_userdata {
                   9782:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  9783:     my $result;
1.1016    raeburn  9784:     if ($datakey ne '') {
1.1013    raeburn  9785:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  9786:             if ($udom eq '' || $uname eq '') {
                   9787:                 $udom = $env{'user.domain'};
                   9788:                 $uname = $env{'user.name'};
                   9789:             }
                   9790:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  9791:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   9792:                 $result = 'error: no_host';
                   9793:             } else {
                   9794:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   9795:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   9796: 
                   9797:                 my $namevalue='';
                   9798:                 foreach my $key (keys(%{$storehash})) {
                   9799:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   9800:                 }
                   9801:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  9802:                 unless ($namespace eq 'courserequests') {
                   9803:                     $datakey = &escape($datakey);
                   9804:                 }
1.1105    raeburn  9805:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   9806:                                   $namevalue,$uhome);
1.1013    raeburn  9807:             }
                   9808:         } else {
                   9809:             $result = 'error: data to store was not a hash reference'; 
                   9810:         }
                   9811:     } else {
                   9812:         $result= 'error: invalid requestkey'; 
                   9813:     }
                   9814:     return $result;
                   9815: }
                   9816: 
1.21      www      9817: # ---------------------------------------------------------- Assign Custom Role
                   9818: 
                   9819: sub assigncustomrole {
1.957     raeburn  9820:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9821:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  9822:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      9823: }
                   9824: 
                   9825: # ----------------------------------------------------------------- Revoke Role
                   9826: 
                   9827: sub revokerole {
1.957     raeburn  9828:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9829:     my $now=time;
1.965     raeburn  9830:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      9831: }
                   9832: 
                   9833: # ---------------------------------------------------------- Revoke Custom Role
                   9834: 
                   9835: sub revokecustomrole {
1.957     raeburn  9836:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9837:     my $now=time;
1.357     www      9838:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  9839:            $deleteflag,$selfenroll,$context);
1.17      www      9840: }
                   9841: 
1.533     banghart 9842: # ------------------------------------------------------------ Disk usage
1.535     albertel 9843: sub diskusage {
1.955     raeburn  9844:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   9845:     $directorypath =~ s/\/$//;
                   9846:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   9847:                        .&escape($getpropath).':'.&escape($uname).':'
                   9848:                        .&escape($udom),homeserver($uname,$udom));
                   9849:     if ($listing eq 'unknown_cmd') {
                   9850:         if ($getpropath) {
                   9851:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   9852:         }
                   9853:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   9854:     }
1.514     albertel 9855:     return $listing;
1.512     banghart 9856: }
                   9857: 
1.566     banghart 9858: sub is_locked {
1.1096    raeburn  9859:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 9860:     my @check;
                   9861:     my $is_locked;
1.1093    raeburn  9862:     push (@check,$file_name);
1.613     albertel 9863:     my %locked = &get('file_permissions',\@check,
1.620     albertel 9864: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 9865:     my ($tmp)=keys(%locked);
                   9866:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  9867:     
1.566     banghart 9868:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  9869:         $is_locked = 'false';
                   9870:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  9871:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  9872:                $is_locked = 'true';
1.1096    raeburn  9873:                if (ref($which) eq 'ARRAY') {
                   9874:                    push(@{$which},$entry);
                   9875:                } else {
                   9876:                    last;
                   9877:                }
1.745     raeburn  9878:            }
                   9879:        }
1.566     banghart 9880:     } else {
                   9881:         $is_locked = 'false';
                   9882:     }
1.1093    raeburn  9883:     return $is_locked;
1.566     banghart 9884: }
                   9885: 
1.759     albertel 9886: sub declutter_portfile {
                   9887:     my ($file) = @_;
1.833     albertel 9888:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 9889:     return $file;
                   9890: }
                   9891: 
1.559     banghart 9892: # ------------------------------------------------------------- Mark as Read Only
                   9893: 
                   9894: sub mark_as_readonly {
                   9895:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 9896:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9897:     my ($tmp)=keys(%current_permissions);
                   9898:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 9899:     foreach my $file (@{$files}) {
1.759     albertel 9900: 	$file = &declutter_portfile($file);
1.561     banghart 9901:         push(@{$current_permissions{$file}},$what);
1.559     banghart 9902:     }
1.613     albertel 9903:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9904:     return;
                   9905: }
                   9906: 
1.572     banghart 9907: # ------------------------------------------------------------Save Selected Files
                   9908: 
                   9909: sub save_selected_files {
                   9910:     my ($user, $path, @files) = @_;
                   9911:     my $filename = $user."savedfiles";
1.573     banghart 9912:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  9913:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 9914:     foreach my $file (@files) {
1.620     albertel 9915:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 9916:     }
                   9917:     foreach my $file (@other_files) {
1.574     banghart 9918:         print (OUT $file."\n");
1.572     banghart 9919:     }
1.574     banghart 9920:     close (OUT);
1.572     banghart 9921:     return 'ok';
                   9922: }
                   9923: 
1.574     banghart 9924: sub clear_selected_files {
                   9925:     my ($user) = @_;
                   9926:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  9927:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 9928:     print (OUT undef);
                   9929:     close (OUT);
                   9930:     return ("ok");    
                   9931: }
                   9932: 
1.572     banghart 9933: sub files_in_path {
                   9934:     my ($user, $path) = @_;
                   9935:     my $filename = $user."savedfiles";
                   9936:     my %return_files;
1.1172.2.96  raeburn  9937:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 9938:     while (my $line_in = <IN>) {
1.574     banghart 9939:         chomp ($line_in);
                   9940:         my @paths_and_file = split (m!/!, $line_in);
                   9941:         my $file_part = pop (@paths_and_file);
                   9942:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9943:         $path_part.='/';
                   9944:         my $path_and_file = $path_part.$file_part;
                   9945:         if ($path_part eq $path) {
                   9946:             $return_files{$file_part}= 'selected';
                   9947:         }
                   9948:     }
1.574     banghart 9949:     close (IN);
                   9950:     return (\%return_files);
1.572     banghart 9951: }
                   9952: 
                   9953: # called in portfolio select mode, to show files selected NOT in current directory
                   9954: sub files_not_in_path {
                   9955:     my ($user, $path) = @_;
                   9956:     my $filename = $user."savedfiles";
                   9957:     my @return_files;
                   9958:     my $path_part;
1.1172.2.96  raeburn  9959:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 9960:     while (my $line = <IN>) {
1.572     banghart 9961:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9962:         my @paths_and_file = split(m|/|, $line);
                   9963:         my $file_part = pop(@paths_and_file);
                   9964:         chomp($file_part);
                   9965:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9966:         $path_part .= '/';
                   9967:         my $path_and_file = $path_part.$file_part;
                   9968:         if ($path_part ne $path) {
1.800     albertel 9969:             push(@return_files, ($path_and_file));
1.572     banghart 9970:         }
                   9971:     }
1.800     albertel 9972:     close(OUT);
1.574     banghart 9973:     return (@return_files);
1.572     banghart 9974: }
                   9975: 
1.745     raeburn  9976: #----------------------------------------------Get portfolio file permissions
1.629     banghart 9977: 
1.745     raeburn  9978: sub get_portfile_permissions {
                   9979:     my ($domain,$user) = @_;
1.613     albertel 9980:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9981:     my ($tmp)=keys(%current_permissions);
                   9982:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9983:     return \%current_permissions;
                   9984: }
                   9985: 
                   9986: #---------------------------------------------Get portfolio file access controls
                   9987: 
1.749     raeburn  9988: sub get_access_controls {
1.745     raeburn  9989:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 9990:     my %access;
                   9991:     my $real_file = $file;
                   9992:     $file =~ s/\.meta$//;
1.745     raeburn  9993:     if (defined($file)) {
1.749     raeburn  9994:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   9995:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 9996:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  9997:             }
                   9998:         }
1.745     raeburn  9999:     } else {
1.749     raeburn  10000:         foreach my $key (keys(%{$current_permissions})) {
                   10001:             if ($key =~ /\0accesscontrol$/) {
                   10002:                 if (defined($group)) {
                   10003:                     if ($key !~ m-^\Q$group\E/-) {
                   10004:                         next;
                   10005:                     }
                   10006:                 }
                   10007:                 my ($fullpath) = split(/\0/,$key);
                   10008:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10009:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10010:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10011:                     }
                   10012:                 }
                   10013:             }
                   10014:         }
                   10015:     }
                   10016:     return %access;
                   10017: }
                   10018: 
                   10019: sub modify_access_controls {
                   10020:     my ($file_name,$changes,$domain,$user)=@_;
                   10021:     my ($outcome,$deloutcome);
                   10022:     my %store_permissions;
                   10023:     my %new_values;
                   10024:     my %new_control;
                   10025:     my %translation;
                   10026:     my @deletions = ();
                   10027:     my $now = time;
                   10028:     if (exists($$changes{'activate'})) {
                   10029:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10030:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10031:             my $numnew = scalar(@newitems);
                   10032:             for (my $i=0; $i<$numnew; $i++) {
                   10033:                 my $newkey = $newitems[$i];
                   10034:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10035:                 if ($newkey =~ /^\d+:/) { 
                   10036:                     $newkey =~ s/^(\d+)/$newid/;
                   10037:                     $translation{$1} = $newid;
                   10038:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10039:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10040:                     $translation{$1} = $newid;
                   10041:                 }
1.749     raeburn  10042:                 $new_values{$file_name."\0".$newkey} = 
                   10043:                                           $$changes{'activate'}{$newitems[$i]};
                   10044:                 $new_control{$newkey} = $now;
                   10045:             }
                   10046:         }
                   10047:     }
                   10048:     my %todelete;
                   10049:     my %changed_items;
                   10050:     foreach my $action ('delete','update') {
                   10051:         if (exists($$changes{$action})) {
                   10052:             if (ref($$changes{$action}) eq 'HASH') {
                   10053:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10054:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10055:                     if ($action eq 'delete') { 
                   10056:                         $todelete{$itemnum} = 1;
                   10057:                     } else {
                   10058:                         $changed_items{$itemnum} = $key;
                   10059:                     }
                   10060:                 }
1.745     raeburn  10061:             }
                   10062:         }
1.749     raeburn  10063:     }
                   10064:     # get lock on access controls for file.
                   10065:     my $lockhash = {
                   10066:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10067:                                                        ':'.$env{'user.domain'},
                   10068:                    }; 
                   10069:     my $tries = 0;
                   10070:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10071:    
1.1172.2.79  raeburn  10072:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10073:         $tries ++;
1.1172.2.79  raeburn  10074:         sleep(0.1);
1.749     raeburn  10075:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10076:     }
                   10077:     if ($gotlock eq 'ok') {
                   10078:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10079:         my ($tmp)=keys(%curr_permissions);
                   10080:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10081:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10082:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10083:             if (ref($curr_controls) eq 'HASH') {
                   10084:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10085:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10086:                     if (defined($todelete{$itemnum})) {
                   10087:                         push(@deletions,$file_name."\0".$control_item);
                   10088:                     } else {
                   10089:                         if (defined($changed_items{$itemnum})) {
                   10090:                             $new_control{$changed_items{$itemnum}} = $now;
                   10091:                             push(@deletions,$file_name."\0".$control_item);
                   10092:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10093:                         } else {
                   10094:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10095:                         }
                   10096:                     }
1.745     raeburn  10097:                 }
                   10098:             }
                   10099:         }
1.970     raeburn  10100:         my ($group);
                   10101:         if (&is_course($domain,$user)) {
                   10102:             ($group,my $file) = split(/\//,$file_name,2);
                   10103:         }
1.749     raeburn  10104:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10105:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10106:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10107:         #  remove lock
                   10108:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10109:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10110:         my $sqlresult =
1.970     raeburn  10111:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10112:                                     $group);
1.749     raeburn  10113:     } else {
                   10114:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10115:     }
1.749     raeburn  10116:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10117: }
                   10118: 
1.827     raeburn  10119: sub make_public_indefinitely {
                   10120:     my ($requrl) = @_;
                   10121:     my $now = time;
                   10122:     my $action = 'activate';
                   10123:     my $aclnum = 0;
                   10124:     if (&is_portfolio_url($requrl)) {
                   10125:         my (undef,$udom,$unum,$file_name,$group) =
                   10126:             &parse_portfolio_url($requrl);
                   10127:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   10128:         my %access_controls = &get_access_controls($current_perms,
                   10129:                                                    $group,$file_name);
                   10130:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10131:             my ($num,$scope,$end,$start) = 
                   10132:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   10133:             if ($scope eq 'public') {
                   10134:                 if ($start <= $now && $end == 0) {
                   10135:                     $action = 'none';
                   10136:                 } else {
                   10137:                     $action = 'update';
                   10138:                     $aclnum = $num;
                   10139:                 }
                   10140:                 last;
                   10141:             }
                   10142:         }
                   10143:         if ($action eq 'none') {
                   10144:              return 'ok';
                   10145:         } else {
                   10146:             my %changes;
                   10147:             my $newend = 0;
                   10148:             my $newstart = $now;
                   10149:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   10150:             $changes{$action}{$newkey} = {
                   10151:                 type => 'public',
                   10152:                 time => {
                   10153:                     start => $newstart,
                   10154:                     end   => $newend,
                   10155:                 },
                   10156:             };
                   10157:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10158:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   10159:             return $outcome;
                   10160:         }
                   10161:     } else {
                   10162:         return 'invalid';
                   10163:     }
                   10164: }
                   10165: 
1.745     raeburn  10166: #------------------------------------------------------Get Marked as Read Only
                   10167: 
                   10168: sub get_marked_as_readonly {
                   10169:     my ($domain,$user,$what,$group) = @_;
                   10170:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10171:     my @readonly_files;
1.629     banghart 10172:     my $cmp1=$what;
                   10173:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10174:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10175:         if (defined($group)) {
                   10176:             if ($file_name !~ m-^\Q$group\E/-) {
                   10177:                 next;
                   10178:             }
                   10179:         }
1.561     banghart 10180:         if (ref($value) eq "ARRAY"){
                   10181:             foreach my $stored_what (@{$value}) {
1.629     banghart 10182:                 my $cmp2=$stored_what;
1.759     albertel 10183:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10184:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10185:                 }
1.629     banghart 10186:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10187:                     push(@readonly_files, $file_name);
1.745     raeburn  10188:                     last;
1.563     banghart 10189:                 } elsif (!defined($what)) {
                   10190:                     push(@readonly_files, $file_name);
1.745     raeburn  10191:                     last;
1.561     banghart 10192:                 }
                   10193:             }
1.745     raeburn  10194:         }
1.561     banghart 10195:     }
                   10196:     return @readonly_files;
                   10197: }
1.577     banghart 10198: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10199: 
1.577     banghart 10200: sub get_marked_as_readonly_hash {
1.745     raeburn  10201:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10202:     my %readonly_files;
1.745     raeburn  10203:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10204:         if (defined($group)) {
                   10205:             if ($file_name !~ m-^\Q$group\E/-) {
                   10206:                 next;
                   10207:             }
                   10208:         }
1.577     banghart 10209:         if (ref($value) eq "ARRAY"){
                   10210:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10211:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10212:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10213:                         if ($lock_descriptor eq 'graded') {
                   10214:                             $readonly_files{$file_name} = 'graded';
                   10215:                         } elsif ($lock_descriptor eq 'handback') {
                   10216:                             $readonly_files{$file_name} = 'handback';
                   10217:                         } else {
                   10218:                             if (!exists($readonly_files{$file_name})) {
                   10219:                                 $readonly_files{$file_name} = 'locked';
                   10220:                             }
                   10221:                         }
1.745     raeburn  10222:                     }
1.750     banghart 10223:                 } 
1.577     banghart 10224:             }
                   10225:         } 
                   10226:     }
                   10227:     return %readonly_files;
                   10228: }
1.559     banghart 10229: # ------------------------------------------------------------ Unmark as Read Only
                   10230: 
                   10231: sub unmark_as_readonly {
1.629     banghart 10232:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10233:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10234:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10235:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10236:     my $symb_crs = $what;
                   10237:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10238:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10239:     my ($tmp)=keys(%current_permissions);
                   10240:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10241:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10242:     foreach my $file (@readonly_files) {
1.759     albertel 10243: 	my $clean_file = &declutter_portfile($file);
                   10244: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10245: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10246:         my @new_locks;
                   10247:         my @del_keys;
                   10248:         if (ref($current_locks) eq "ARRAY"){
                   10249:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10250:                 my $compare=$locker;
1.749     raeburn  10251:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10252:                     $compare=join('',@{$locker});
1.746     raeburn  10253:                     if ($compare ne $symb_crs) {
                   10254:                         push(@new_locks, $locker);
                   10255:                     }
1.563     banghart 10256:                 }
                   10257:             }
1.650     albertel 10258:             if (scalar(@new_locks) > 0) {
1.563     banghart 10259:                 $current_permissions{$file} = \@new_locks;
                   10260:             } else {
                   10261:                 push(@del_keys, $file);
1.613     albertel 10262:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10263:                 delete($current_permissions{$file});
1.563     banghart 10264:             }
                   10265:         }
1.561     banghart 10266:     }
1.613     albertel 10267:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10268:     return;
                   10269: }
1.512     banghart 10270: 
1.17      www      10271: # ------------------------------------------------------------ Directory lister
                   10272: 
                   10273: sub dirlist {
1.955     raeburn  10274:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10275:     $uri=~s/^\///;
                   10276:     $uri=~s/\/$//;
1.253     stredwic 10277:     my ($udom, $uname);
1.955     raeburn  10278:     if ($getuserdir) {
1.253     stredwic 10279:         $udom = $userdomain;
                   10280:         $uname = $username;
1.955     raeburn  10281:     } else {
                   10282:         (undef,$udom,$uname)=split(/\//,$uri);
                   10283:         if(defined($userdomain)) {
                   10284:             $udom = $userdomain;
                   10285:         }
                   10286:         if(defined($username)) {
                   10287:             $uname = $username;
                   10288:         }
1.253     stredwic 10289:     }
1.955     raeburn  10290:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10291: 
1.955     raeburn  10292:     $dirRoot = $perlvar{'lonDocRoot'};
                   10293:     if (defined($getpropath)) {
                   10294:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10295:         $dirRoot =~ s/\/$//;
1.955     raeburn  10296:     } elsif (defined($getuserdir)) {
                   10297:         my $subdir=$uname.'__';
                   10298:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10299:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10300:                    ."/$udom/$subdir/$uname";
                   10301:     } elsif (defined($alternateRoot)) {
                   10302:         $dirRoot = $alternateRoot;
1.751     banghart 10303:     }
1.253     stredwic 10304: 
                   10305:     if($udom) {
                   10306:         if($uname) {
1.1135    raeburn  10307:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10308:             if ($uhome eq 'no_host') {
                   10309:                 return ([],'no_host');
                   10310:             }
1.955     raeburn  10311:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10312:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10313:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10314:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10315:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10316:             } else {
                   10317:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10318:             }
1.605     matthew  10319:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10320:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10321:                 @listing_results = split(/:/,$listing);
                   10322:             } else {
                   10323:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10324:             }
1.1135    raeburn  10325:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10326:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10327:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10328:                 return ([],$listing);
                   10329:             } else {
                   10330:                 return (\@listing_results);
1.1135    raeburn  10331:             }
1.955     raeburn  10332:         } elsif(!$alternateRoot) {
1.1136    raeburn  10333:             my (%allusers,%listerror);
1.841     albertel 10334: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10335:  	    foreach my $tryserver (keys(%servers)) {
                   10336:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10337:                                   &escape($udom),$tryserver);
                   10338:                 if ($listing eq 'unknown_cmd') {
                   10339: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10340: 				      $udom, $tryserver);
                   10341:                 } else {
                   10342:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10343:                 }
1.841     albertel 10344: 		if ($listing eq 'unknown_cmd') {
                   10345: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10346: 				      $udom, $tryserver);
                   10347: 		    @listing_results = split(/:/,$listing);
                   10348: 		} else {
                   10349: 		    @listing_results =
                   10350: 			map { &unescape($_); } split(/:/,$listing);
                   10351: 		}
1.1136    raeburn  10352:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10353:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10354:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10355:                     $listerror{$tryserver} = $listing;
                   10356:                 } else {
1.841     albertel 10357: 		    foreach my $line (@listing_results) {
                   10358: 			my ($entry) = split(/&/,$line,2);
                   10359: 			$allusers{$entry} = 1;
                   10360: 		    }
                   10361: 		}
1.253     stredwic 10362:             }
1.1136    raeburn  10363:             my @alluserslist=();
1.800     albertel 10364:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10365:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10366:             }
1.1172.2.80  raeburn  10367:             if (!%listerror) {
                   10368:                 # no errors
                   10369:                 return (\@alluserslist);
                   10370:             } elsif (scalar(keys(%servers)) == 1) {
                   10371:                 # one library server, one error
                   10372:                 my ($key) = keys(%listerror);
                   10373:                 return (\@alluserslist, $listerror{$key});
                   10374:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10375:                 # con_lost indicates that we might miss data from at least one
                   10376:                 # library server
                   10377:                 return (\@alluserslist, 'con_lost');
                   10378:             } else {
                   10379:                 # multiple library servers and no con_lost -> data should be
                   10380:                 # complete.
                   10381:                 return (\@alluserslist);
                   10382:             }
                   10383: 
1.253     stredwic 10384:         } else {
1.1136    raeburn  10385:             return ([],'missing username');
1.253     stredwic 10386:         }
1.955     raeburn  10387:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10388:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10389:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10390:         return (\@all_domains);
1.955     raeburn  10391:     } else {
1.1136    raeburn  10392:         return ([],'missing domain');
1.275     stredwic 10393:     }
                   10394: }
                   10395: 
                   10396: # --------------------------------------------- GetFileTimestamp
                   10397: # This function utilizes dirlist and returns the date stamp for
                   10398: # when it was last modified.  It will also return an error of -1
                   10399: # if an error occurs
                   10400: 
                   10401: sub GetFileTimestamp {
1.955     raeburn  10402:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10403:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10404:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10405:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10406:                                     undef,$getuserdir);
                   10407:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10408:         return -1;
                   10409:     }
                   10410:     if (ref($fileref) eq 'ARRAY') {
                   10411:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10412:         # @stats contains first the filename, then the stat output
                   10413:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10414:     } else {
                   10415:         return -1;
1.253     stredwic 10416:     }
1.26      www      10417: }
                   10418: 
1.712     albertel 10419: sub stat_file {
                   10420:     my ($uri) = @_;
1.787     albertel 10421:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10422: 
1.955     raeburn  10423:     my ($udom,$uname,$file);
1.712     albertel 10424:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10425: 	($udom,$uname,$file) =
1.811     albertel 10426: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10427: 	$file = 'userfiles/'.$file;
                   10428:     }
                   10429:     if ($uri =~ m-^/res/-) {
                   10430: 	($udom,$uname) = 
1.807     albertel 10431: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10432: 	$file = $uri;
                   10433:     }
                   10434: 
                   10435:     if (!$udom || !$uname || !$file) {
                   10436: 	# unable to handle the uri
                   10437: 	return ();
                   10438:     }
1.956     raeburn  10439:     my $getpropath;
                   10440:     if ($file =~ /^userfiles\//) {
                   10441:         $getpropath = 1;
                   10442:     }
1.1136    raeburn  10443:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10444:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10445:         return ();
                   10446:     } else {
                   10447:         if (ref($listref) eq 'ARRAY') {
                   10448:             my @stats = split('&',$listref->[0]);
                   10449: 	    shift(@stats); #filename is first
                   10450: 	    return @stats;
                   10451:         }
1.712     albertel 10452:     }
                   10453:     return ();
                   10454: }
                   10455: 
1.26      www      10456: # -------------------------------------------------------- Value of a Condition
                   10457: 
1.713     albertel 10458: # gets the value of a specific preevaluated condition
                   10459: #    stored in the string  $env{user.state.<cid>}
                   10460: # or looks up a condition reference in the bighash and if if hasn't
                   10461: # already been evaluated recurses into docondval to get the value of
                   10462: # the condition, then memoizing it to 
                   10463: #   $env{user.state.<cid>.<condition>}
1.40      www      10464: sub directcondval {
                   10465:     my $number=shift;
1.620     albertel 10466:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 10467: 	&Apache::lonuserstate::evalstate();
                   10468:     }
1.713     albertel 10469:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   10470: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   10471:     } elsif ($number =~ /^_/) {
                   10472: 	my $sub_condition;
                   10473: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10474: 		&GDBM_READER(),0640)) {
                   10475: 	    $sub_condition=$bighash{'conditions'.$number};
                   10476: 	    untie(%bighash);
                   10477: 	}
                   10478: 	my $value = &docondval($sub_condition);
1.949     raeburn  10479: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 10480: 	return $value;
                   10481:     }
1.620     albertel 10482:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   10483:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      10484:     } else {
                   10485:        return 2;
                   10486:     }
                   10487: }
                   10488: 
1.713     albertel 10489: # get the collection of conditions for this resource
1.26      www      10490: sub condval {
                   10491:     my $condidx=shift;
1.54      www      10492:     my $allpathcond='';
1.713     albertel 10493:     foreach my $cond (split(/\|/,$condidx)) {
                   10494: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   10495: 	    $allpathcond.=
                   10496: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   10497: 	}
1.191     harris41 10498:     }
1.54      www      10499:     $allpathcond=~s/\|$//;
1.713     albertel 10500:     return &docondval($allpathcond);
                   10501: }
                   10502: 
                   10503: #evaluates an expression of conditions
                   10504: sub docondval {
                   10505:     my ($allpathcond) = @_;
                   10506:     my $result=0;
                   10507:     if ($env{'request.course.id'}
                   10508: 	&& defined($allpathcond)) {
                   10509: 	my $operand='|';
                   10510: 	my @stack;
                   10511: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   10512: 	    if ($chunk eq '(') {
                   10513: 		push @stack,($operand,$result);
                   10514: 	    } elsif ($chunk eq ')') {
                   10515: 		my $before=pop @stack;
                   10516: 		if (pop @stack eq '&') {
                   10517: 		    $result=$result>$before?$before:$result;
                   10518: 		} else {
                   10519: 		    $result=$result>$before?$result:$before;
                   10520: 		}
                   10521: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   10522: 		$operand=$chunk;
                   10523: 	    } else {
                   10524: 		my $new=directcondval($chunk);
                   10525: 		if ($operand eq '&') {
                   10526: 		    $result=$result>$new?$new:$result;
                   10527: 		} else {
                   10528: 		    $result=$result>$new?$result:$new;
                   10529: 		}
                   10530: 	    }
                   10531: 	}
1.26      www      10532:     }
                   10533:     return $result;
1.421     albertel 10534: }
                   10535: 
                   10536: # ---------------------------------------------------- Devalidate courseresdata
                   10537: 
                   10538: sub devalidatecourseresdata {
                   10539:     my ($coursenum,$coursedomain)=@_;
                   10540:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10541:     &devalidate_cache_new('courseres',$hashid);
1.28      www      10542: }
                   10543: 
1.763     www      10544: 
1.200     www      10545: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     10546: #
                   10547: #  Parameters:
                   10548: #      $coursenum    - Number of the course.
                   10549: #      $coursedomain - Domain at which the course was created.
                   10550: #  Returns:
                   10551: #     A hash of the course parameters along (I think) with timestamps
                   10552: #     and version info.
1.877     foxr     10553: 
1.624     albertel 10554: sub get_courseresdata {
                   10555:     my ($coursenum,$coursedomain)=@_;
1.200     www      10556:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   10557:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10558:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 10559:     my %dumpreply;
1.417     albertel 10560:     unless (defined($cached)) {
1.624     albertel 10561: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 10562: 	$result=\%dumpreply;
1.251     albertel 10563: 	my ($tmp) = keys(%dumpreply);
                   10564: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 10565: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 10566: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   10567: 	    return $tmp;
1.416     albertel 10568: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 10569: 	    $result=undef;
1.599     albertel 10570: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 10571: 	}
                   10572:     }
1.624     albertel 10573:     return $result;
                   10574: }
                   10575: 
1.633     albertel 10576: sub devalidateuserresdata {
                   10577:     my ($uname,$udom)=@_;
                   10578:     my $hashid="$udom:$uname";
                   10579:     &devalidate_cache_new('userres',$hashid);
                   10580: }
                   10581: 
1.624     albertel 10582: sub get_userresdata {
                   10583:     my ($uname,$udom)=@_;
                   10584:     #most student don\'t have any data set, check if there is some data
                   10585:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   10586: 
                   10587:     my $hashid="$udom:$uname";
                   10588:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   10589:     if (!defined($cached)) {
                   10590: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   10591: 	$result=\%resourcedata;
                   10592: 	&do_cache_new('userres',$hashid,$result,600);
                   10593:     }
                   10594:     my ($tmp)=keys(%$result);
                   10595:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   10596: 	return $result;
                   10597:     }
                   10598:     #error 2 occurs when the .db doesn't exist
                   10599:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  10600:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   10601: 	    &logthis("<font color=\"blue\">WARNING:".
                   10602: 		     " Trying to get resource data for ".
                   10603: 		     $uname." at ".$udom.": ".
                   10604: 		     $tmp."</font>");
                   10605:         }
1.624     albertel 10606:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 10607: 	#&EXT_cache_set($udom,$uname);
                   10608: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 10609: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 10610:     }
                   10611:     return $tmp;
                   10612: }
1.879     foxr     10613: #----------------------------------------------- resdata - return resource data
                   10614: #  Purpose:
                   10615: #    Return resource data for either users or for a course.
                   10616: #  Parameters:
                   10617: #     $name      - Course/user name.
                   10618: #     $domain    - Name of the domain the user/course is registered on.
                   10619: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   10620: #     @which     - Array of names of resources desired.
                   10621: #  Returns:
                   10622: #     The value of the first reasource in @which that is found in the
                   10623: #     resource hash.
                   10624: #  Exceptional Conditions:
                   10625: #     If the $type passed in is not valid (not the string 'course' or 
                   10626: #     'user', an undefined  reference is returned.
                   10627: #     If none of the resources are found, an undef is returned
1.624     albertel 10628: sub resdata {
                   10629:     my ($name,$domain,$type,@which)=@_;
                   10630:     my $result;
                   10631:     if ($type eq 'course') {
                   10632: 	$result=&get_courseresdata($name,$domain);
                   10633:     } elsif ($type eq 'user') {
                   10634: 	$result=&get_userresdata($name,$domain);
                   10635:     }
                   10636:     if (!ref($result)) { return $result; }    
1.251     albertel 10637:     foreach my $item (@which) {
1.927     albertel 10638: 	if (defined($result->{$item->[0]})) {
                   10639: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 10640: 	}
1.250     albertel 10641:     }
1.291     albertel 10642:     return undef;
1.200     www      10643: }
                   10644: 
1.1172.2.31  raeburn  10645: sub get_numsuppfiles {
                   10646:     my ($cnum,$cdom,$ignorecache)=@_;
                   10647:     my $hashid=$cnum.':'.$cdom;
                   10648:     my ($suppcount,$cached);
                   10649:     unless ($ignorecache) {
                   10650:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   10651:     }
                   10652:     unless (defined($cached)) {
                   10653:         my $chome=&homeserver($cnum,$cdom);
                   10654:         unless ($chome eq 'no_host') {
                   10655:             ($suppcount,my $errors) = (0,0);
                   10656:             my $suppmap = 'supplemental.sequence';
                   10657:             ($suppcount,$errors) =
                   10658:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   10659:         }
                   10660:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   10661:     }
                   10662:     return $suppcount;
                   10663: }
                   10664: 
1.379     matthew  10665: #
                   10666: # EXT resource caching routines
                   10667: #
                   10668: 
                   10669: sub clear_EXT_cache_status {
1.383     albertel 10670:     &delenv('cache.EXT.');
1.379     matthew  10671: }
                   10672: 
                   10673: sub EXT_cache_status {
                   10674:     my ($target_domain,$target_user) = @_;
1.383     albertel 10675:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 10676:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  10677:         # We know already the user has no data
                   10678:         return 1;
                   10679:     } else {
                   10680:         return 0;
                   10681:     }
                   10682: }
                   10683: 
                   10684: sub EXT_cache_set {
                   10685:     my ($target_domain,$target_user) = @_;
1.383     albertel 10686:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  10687:     #&appenv({$cachename => time});
1.379     matthew  10688: }
                   10689: 
1.28      www      10690: # --------------------------------------------------------- Value of a Variable
1.58      www      10691: sub EXT {
1.715     albertel 10692: 
1.1172.2.28  raeburn  10693:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      10694:     unless ($varname) { return ''; }
1.218     albertel 10695:     #get real user name/domain, courseid and symb
                   10696:     my $courseid;
1.359     albertel 10697:     my $publicuser;
1.427     www      10698:     if ($symbparm) {
                   10699: 	$symbparm=&get_symb_from_alias($symbparm);
                   10700:     }
1.218     albertel 10701:     if (!($uname && $udom)) {
1.790     albertel 10702:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 10703:       if (!$symbparm) {	$symbparm=$cursymb; }
                   10704:     } else {
1.620     albertel 10705: 	$courseid=$env{'request.course.id'};
1.218     albertel 10706:     }
1.48      www      10707:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   10708:     my $rest;
1.320     albertel 10709:     if (defined($therest[0])) {
1.48      www      10710:        $rest=join('.',@therest);
                   10711:     } else {
                   10712:        $rest='';
                   10713:     }
1.320     albertel 10714: 
1.57      www      10715:     my $qualifierrest=$qualifier;
                   10716:     if ($rest) { $qualifierrest.='.'.$rest; }
                   10717:     my $spacequalifierrest=$space;
                   10718:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      10719:     if ($realm eq 'user') {
1.48      www      10720: # --------------------------------------------------------------- user.resource
                   10721: 	if ($space eq 'resource') {
1.651     albertel 10722: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   10723: 		  || defined($Apache::lonhomework::parsing_a_task))
                   10724: 		 &&
1.744     albertel 10725: 		 ($symbparm eq &symbread()) ) {	
                   10726: 		# if we are in the middle of processing the resource the
                   10727: 		# get the value we are planning on committing
                   10728:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   10729:                     return $Apache::lonhomework::results{$qualifierrest};
                   10730:                 } else {
                   10731:                     return $Apache::lonhomework::history{$qualifierrest};
                   10732:                 }
1.335     albertel 10733: 	    } else {
1.359     albertel 10734: 		my %restored;
1.620     albertel 10735: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 10736: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   10737: 		} else {
                   10738: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   10739: 		}
1.335     albertel 10740: 		return $restored{$qualifierrest};
                   10741: 	    }
1.48      www      10742: # ----------------------------------------------------------------- user.access
                   10743:         } elsif ($space eq 'access') {
1.218     albertel 10744: 	    # FIXME - not supporting calls for a specific user
1.48      www      10745:             return &allowed($qualifier,$rest);
                   10746: # ------------------------------------------ user.preferences, user.environment
                   10747:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 10748: 	    if (($uname eq $env{'user.name'}) &&
                   10749: 		($udom eq $env{'user.domain'})) {
                   10750: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 10751: 	    } else {
1.359     albertel 10752: 		my %returnhash;
                   10753: 		if (!$publicuser) {
                   10754: 		    %returnhash=&userenvironment($udom,$uname,
                   10755: 						 $qualifierrest);
                   10756: 		}
1.218     albertel 10757: 		return $returnhash{$qualifierrest};
                   10758: 	    }
1.48      www      10759: # ----------------------------------------------------------------- user.course
                   10760:         } elsif ($space eq 'course') {
1.218     albertel 10761: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10762:             return $env{join('.',('request.course',$qualifier))};
1.48      www      10763: # ------------------------------------------------------------------- user.role
                   10764:         } elsif ($space eq 'role') {
1.218     albertel 10765: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10766:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      10767:             if ($qualifier eq 'value') {
                   10768: 		return $role;
                   10769:             } elsif ($qualifier eq 'extent') {
                   10770:                 return $where;
                   10771:             }
                   10772: # ----------------------------------------------------------------- user.domain
                   10773:         } elsif ($space eq 'domain') {
1.218     albertel 10774:             return $udom;
1.48      www      10775: # ------------------------------------------------------------------- user.name
                   10776:         } elsif ($space eq 'name') {
1.218     albertel 10777:             return $uname;
1.48      www      10778: # ---------------------------------------------------- Any other user namespace
1.29      www      10779:         } else {
1.359     albertel 10780: 	    my %reply;
                   10781: 	    if (!$publicuser) {
                   10782: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   10783: 	    }
                   10784: 	    return $reply{$qualifierrest};
1.48      www      10785:         }
1.236     www      10786:     } elsif ($realm eq 'query') {
                   10787: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 10788:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   10789: 						[$spacequalifierrest]);
1.620     albertel 10790: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      10791:    } elsif ($realm eq 'request') {
1.48      www      10792: # ------------------------------------------------------------- request.browser
                   10793:         if ($space eq 'browser') {
1.1145    bisitz   10794:             return $env{'browser.'.$qualifier};
1.57      www      10795: # ------------------------------------------------------------ request.filename
                   10796:         } else {
1.620     albertel 10797:             return $env{'request.'.$spacequalifierrest};
1.29      www      10798:         }
1.28      www      10799:     } elsif ($realm eq 'course') {
1.48      www      10800: # ---------------------------------------------------------- course.description
1.620     albertel 10801:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      10802:     } elsif ($realm eq 'resource') {
1.165     www      10803: 
1.620     albertel 10804: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 10805: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   10806: 	}
1.693     albertel 10807: 
1.1172.2.30  raeburn  10808:         if ($qualifier eq '') {
                   10809: 	    if ($space eq 'title') {
                   10810: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   10811: 	        return &gettitle($symbparm);
                   10812: 	    }
1.693     albertel 10813: 	
1.1172.2.30  raeburn  10814: 	    if ($space eq 'map') {
                   10815: 	        my ($map) = &decode_symb($symbparm);
                   10816: 	        return &symbread($map);
                   10817: 	    }
                   10818:             if ($space eq 'maptitle') {
                   10819:                 my ($map) = &decode_symb($symbparm);
                   10820:                 return &gettitle($map);
                   10821:             }
                   10822: 	    if ($space eq 'filename') {
                   10823: 	        if ($symbparm) {
                   10824: 		    return &clutter((&decode_symb($symbparm))[2]);
                   10825: 	        }
                   10826: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 10827: 	    }
1.1172.2.30  raeburn  10828: 
                   10829:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   10830:                 if ($space eq 'visibleparts') {
                   10831:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10832:                     my $item;
                   10833:                     if (ref($navmap)) {
                   10834:                         my $res = $navmap->getBySymb($symbparm);
                   10835:                         my $parts = $res->parts();
                   10836:                         if (ref($parts) eq 'ARRAY') {
                   10837:                             $item = join(',',@{$parts});
                   10838:                         }
                   10839:                         undef($navmap);
                   10840:                     }
                   10841:                     return $item;
                   10842:                 }
                   10843:             }
                   10844:         }
1.693     albertel 10845: 
                   10846: 	my ($section, $group, @groups);
1.593     albertel 10847: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  10848:         if (($courseid eq '') && ($cid)) {
                   10849:             $courseid = $cid;
                   10850:         }
                   10851: 	if (($symbparm && $courseid) && 
                   10852: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      10853: 
1.218     albertel 10854: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      10855: 
1.60      www      10856: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 10857: 	    my $symbp=$symbparm;
1.735     albertel 10858: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 10859: 
                   10860: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   10861: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   10862: 
1.620     albertel 10863: 	    if (($env{'user.name'} eq $uname) &&
                   10864: 		($env{'user.domain'} eq $udom)) {
                   10865: 		$section=$env{'request.course.sec'};
1.733     raeburn  10866:                 @groups = split(/:/,$env{'request.course.groups'});  
                   10867:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 10868: 	    } else {
1.539     albertel 10869: 		if (! defined($usection)) {
1.551     albertel 10870: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 10871: 		} else {
                   10872: 		    $section = $usection;
                   10873: 		}
1.733     raeburn  10874:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 10875: 	    }
                   10876: 
                   10877: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   10878: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   10879: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   10880: 
1.593     albertel 10881: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 10882: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 10883: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      10884: 
1.60      www      10885: # ----------------------------------------------------------- first, check user
1.624     albertel 10886: 
                   10887: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 10888: 				       ([$courselevelr,'resource'],
                   10889: 					[$courselevelm,'map'     ],
                   10890: 					[$courselevel, 'course'  ]));
1.931     albertel 10891: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      10892: 
1.594     albertel 10893: # ------------------------------------------------ second, check some of course
1.684     raeburn  10894:             my $coursereply;
1.691     raeburn  10895:             if (@groups > 0) {
                   10896:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   10897:                                        $mapparm,$spacequalifierrest);
1.927     albertel 10898:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  10899:             }
1.96      www      10900: 
1.684     raeburn  10901: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 10902: 				  $env{'course.'.$courseid.'.domain'},
                   10903: 				  'course',
                   10904: 				  ([$seclevelr,   'resource'],
                   10905: 				   [$seclevelm,   'map'     ],
                   10906: 				   [$seclevel,    'course'  ],
                   10907: 				   [$courselevelr,'resource']));
                   10908: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      10909: 
1.60      www      10910: # ------------------------------------------------------ third, check map parms
1.218     albertel 10911: 	    my %parmhash=();
                   10912: 	    my $thisparm='';
                   10913: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 10914: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 10915: 		    &GDBM_READER(),0640)) {
1.218     albertel 10916: 		$thisparm=$parmhash{$symbparm};
                   10917: 		untie(%parmhash);
                   10918: 	    }
1.927     albertel 10919: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 10920: 	}
1.594     albertel 10921: # ------------------------------------------ fourth, look in resource metadata
1.71      www      10922: 
1.218     albertel 10923: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 10924: 	my $filename;
                   10925: 	if (!$symbparm) { $symbparm=&symbread(); }
                   10926: 	if ($symbparm) {
1.409     www      10927: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 10928: 	} else {
1.620     albertel 10929: 	    $filename=$env{'request.filename'};
1.282     albertel 10930: 	}
                   10931: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 10932: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 10933: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 10934: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      10935: 
1.927     albertel 10936: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 10937: 	if ($symbparm && defined($courseid) && 
1.620     albertel 10938: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 10939: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   10940: 				     $env{'course.'.$courseid.'.domain'},
                   10941: 				     'course',
1.927     albertel 10942: 				     ([$courselevelm,'map'   ],
                   10943: 				      [$courselevel, 'course']));
                   10944: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 10945: 	}
1.145     www      10946: # ------------------------------------------------------------------ Cascade up
1.218     albertel 10947: 	unless ($space eq '0') {
1.336     albertel 10948: 	    my @parts=split(/_/,$space);
                   10949: 	    my $id=pop(@parts);
                   10950: 	    my $part=join('_',@parts);
                   10951: 	    if ($part eq '') { $part='0'; }
1.927     albertel 10952: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 10953: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  10954: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 10955: 	}
1.395     albertel 10956: 	if ($recurse) { return undef; }
                   10957: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 10958: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      10959: # ---------------------------------------------------- Any other user namespace
                   10960:     } elsif ($realm eq 'environment') {
                   10961: # ----------------------------------------------------------------- environment
1.620     albertel 10962: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   10963: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 10964: 	} else {
1.770     albertel 10965: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   10966: 		return '';
                   10967: 	    }
1.219     albertel 10968: 	    my %returnhash=&userenvironment($udom,$uname,
                   10969: 					    $spacequalifierrest);
                   10970: 	    return $returnhash{$spacequalifierrest};
                   10971: 	}
1.28      www      10972:     } elsif ($realm eq 'system') {
1.48      www      10973: # ----------------------------------------------------------------- system.time
                   10974: 	if ($space eq 'time') {
                   10975: 	    return time;
                   10976:         }
1.696     albertel 10977:     } elsif ($realm eq 'server') {
                   10978: # ----------------------------------------------------------------- system.time
                   10979: 	if ($space eq 'name') {
                   10980: 	    return $ENV{'SERVER_NAME'};
                   10981:         }
1.28      www      10982:     }
1.48      www      10983:     return '';
1.61      www      10984: }
                   10985: 
1.927     albertel 10986: sub get_reply {
                   10987:     my ($reply_value) = @_;
1.940     raeburn  10988:     if (ref($reply_value) eq 'ARRAY') {
                   10989:         if (wantarray) {
                   10990: 	    return @$reply_value;
                   10991:         }
                   10992:         return $reply_value->[0];
                   10993:     } else {
                   10994:         return $reply_value;
1.927     albertel 10995:     }
                   10996: }
                   10997: 
1.691     raeburn  10998: sub check_group_parms {
                   10999:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   11000:     my @groupitems = ();
                   11001:     my $resultitem;
1.927     albertel 11002:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  11003:     foreach my $group (@{$groups}) {
                   11004:         foreach my $level (@levels) {
1.927     albertel 11005:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11006:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11007:         }
                   11008:     }
                   11009:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11010:                             $env{'course.'.$courseid.'.domain'},
                   11011:                                      'course',@groupitems);
                   11012:     return $coursereply;
                   11013: }
                   11014: 
                   11015: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11016:     my ($courseid,@groups) = @_;
                   11017:     @groups = sort(@groups);
1.691     raeburn  11018:     return @groups;
                   11019: }
                   11020: 
1.395     albertel 11021: sub packages_tab_default {
                   11022:     my ($uri,$varname)=@_;
                   11023:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11024: 
                   11025:     my (@extension,@specifics,$do_default);
                   11026:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11027: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11028: 	if ($pack_type eq 'default') {
                   11029: 	    $do_default=1;
                   11030: 	} elsif ($pack_type eq 'extension') {
                   11031: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11032: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11033: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11034: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11035: 	}
                   11036:     }
                   11037:     # first look for a package that matches the requested part id
                   11038:     foreach my $package (@specifics) {
                   11039: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11040: 	next if ($pack_part ne $part);
                   11041: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11042: 	    return $packagetab{"$pack_type&$name&default"};
                   11043: 	}
                   11044:     }
                   11045:     # look for any possible matching non extension_ package
                   11046:     foreach my $package (@specifics) {
                   11047: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11048: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11049: 	    return $packagetab{"$pack_type&$name&default"};
                   11050: 	}
1.585     albertel 11051: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11052: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11053: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11054: 	}
                   11055:     }
1.738     albertel 11056:     # look for any posible extension_ match
                   11057:     foreach my $package (@extension) {
                   11058: 	my ($package,$pack_type)=@{$package};
                   11059: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11060: 	    return $packagetab{"$pack_type&$name&default"};
                   11061: 	}
                   11062: 	if (defined($packagetab{$package."&$name&default"})) {
                   11063: 	    return $packagetab{$package."&$name&default"};
                   11064: 	}
                   11065:     }
                   11066:     # look for a global default setting
                   11067:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11068: 	return $packagetab{"default&$name&default"};
                   11069:     }
1.395     albertel 11070:     return undef;
                   11071: }
                   11072: 
1.334     albertel 11073: sub add_prefix_and_part {
                   11074:     my ($prefix,$part)=@_;
                   11075:     my $keyroot;
                   11076:     if (defined($prefix) && $prefix !~ /^__/) {
                   11077: 	# prefix that has a part already
                   11078: 	$keyroot=$prefix;
                   11079:     } elsif (defined($prefix)) {
                   11080: 	# prefix that is missing a part
                   11081: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11082:     } else {
                   11083: 	# no prefix at all
                   11084: 	if (defined($part)) { $keyroot='_'.$part; }
                   11085:     }
                   11086:     return $keyroot;
                   11087: }
                   11088: 
1.71      www      11089: # ---------------------------------------------------------------- Get metadata
                   11090: 
1.599     albertel 11091: my %metaentry;
1.1070    www      11092: my %importedpartids;
1.1172.2.99  raeburn  11093: my %importedrespids;
1.71      www      11094: sub metadata {
1.176     www      11095:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11096:     $uri=&declutter($uri);
1.288     albertel 11097:     # if it is a non metadata possible uri return quickly
1.529     albertel 11098:     if (($uri eq '') || 
                   11099: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  11100: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  11101:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11102: 	return undef;
                   11103:     }
1.1172.2.49  raeburn  11104:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11105: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11106: 	return undef;
1.288     albertel 11107:     }
1.73      www      11108:     my $filename=$uri;
                   11109:     $uri=~s/\.meta$//;
1.172     www      11110: #
                   11111: # Is the metadata already cached?
1.177     www      11112: # Look at timestamp of caching
1.172     www      11113: # Everything is cached by the main uri, libraries are never directly cached
                   11114: #
1.428     albertel 11115:     if (!defined($liburi)) {
1.599     albertel 11116: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11117: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11118:     }
                   11119:     {
1.1069    www      11120: # Imported parts would go here
1.1172.2.99  raeburn  11121:         my @origfiletagids=();
1.1069    www      11122:         my $importedparts=0;
1.1172.2.99  raeburn  11123: 
                   11124: # Imported responseids would go here
                   11125:         my $importedresponses=0;
1.172     www      11126: #
                   11127: # Is this a recursive call for a library?
                   11128: #
1.599     albertel 11129: #	if (! exists($metacache{$uri})) {
                   11130: #	    $metacache{$uri}={};
                   11131: #	}
1.924     albertel 11132: 	my $cachetime = 60*60;
1.171     www      11133:         if ($liburi) {
                   11134: 	    $liburi=&declutter($liburi);
                   11135:             $filename=$liburi;
1.401     bowersj2 11136:         } else {
1.599     albertel 11137: 	    &devalidate_cache_new('meta',$uri);
                   11138: 	    undef(%metaentry);
1.401     bowersj2 11139: 	}
1.140     www      11140:         my %metathesekeys=();
1.73      www      11141:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11142: 	my $metastring;
1.1140    www      11143: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11144: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11145: 	    $metastring = 
1.929     albertel 11146: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11147: 					  ('grade_target' => 'meta'));
                   11148: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11149: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11150:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11151: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11152: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11153: 	    $metastring=&getfile($file);
1.489     albertel 11154: 	}
1.208     albertel 11155:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11156:         my $token;
1.140     www      11157:         undef %metathesekeys;
1.71      www      11158:         while ($token=$parser->get_token) {
1.339     albertel 11159: 	    if ($token->[0] eq 'S') {
                   11160: 		if (defined($token->[2]->{'package'})) {
1.172     www      11161: #
                   11162: # This is a package - get package info
                   11163: #
1.339     albertel 11164: 		    my $package=$token->[2]->{'package'};
                   11165: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11166: 		    if (defined($token->[2]->{'id'})) { 
                   11167: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11168: 		    }
1.599     albertel 11169: 		    if ($metaentry{':packages'}) {
                   11170: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11171: 		    } else {
1.599     albertel 11172: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11173: 		    }
1.736     albertel 11174: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11175: 			my $part=$keyroot;
                   11176: 			$part=~s/^\_//;
1.736     albertel 11177: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11178: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11179: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11180: 			    # ignore package.tab specified default values
                   11181:                             # here &package_tab_default() will fetch those
                   11182: 			    if ($subp eq 'default') { next; }
1.736     albertel 11183: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11184: 			    my $unikey;
                   11185: 			    if ($pack =~ /_0$/) {
                   11186: 				$unikey='parameter_0_'.$name;
                   11187: 				$part=0;
                   11188: 			    } else {
                   11189: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11190: 			    }
1.339     albertel 11191: 			    if ($subp eq 'display') {
                   11192: 				$value.=' [Part: '.$part.']';
                   11193: 			    }
1.599     albertel 11194: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11195: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11196: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11197: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11198: 			    }
1.599     albertel 11199: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11200: 				$metaentry{':'.$unikey}=
                   11201: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11202: 			    }
1.339     albertel 11203: 			}
                   11204: 		    }
                   11205: 		} else {
1.172     www      11206: #
                   11207: # This is not a package - some other kind of start tag
1.339     albertel 11208: #
                   11209: 		    my $entry=$token->[1];
1.1068    www      11210: 		    my $unikey='';
1.175     www      11211: 
1.339     albertel 11212: 		    if ($entry eq 'import') {
1.175     www      11213: #
                   11214: # Importing a library here
1.339     albertel 11215: #
1.1067    www      11216:                         my $location=$parser->get_text('/import');
                   11217:                         my $dir=$filename;
                   11218:                         $dir=~s|[^/]*$||;
                   11219:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  11220: 
                   11221:                         my $importid=$token->[2]->{'id'};
1.1068    www      11222:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  11223: #
                   11224: # Check metadata for imported file to
                   11225: # see if it contained response items
                   11226: #
                   11227:                         my %currmetaentry = %metaentry;
                   11228:                         my $libresponseorder = &metadata($location,'responseorder');
                   11229:                         my $origfile;
                   11230:                         if ($libresponseorder ne '') {
                   11231:                             if ($#origfiletagids<0) {
                   11232:                                 undef(%importedrespids);
                   11233:                                 undef(%importedpartids);
                   11234:                             }
                   11235:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   11236:                             if (@{$importedrespids{$importid}} > 0) {
                   11237:                                 $importedresponses = 1;
                   11238: # We need to get the original file and the imported file to get the response order correct
                   11239: # Load and inspect original file
                   11240:                                 if ($#origfiletagids<0) {
                   11241:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11242:                                     $origfile=&getfile($origfilelocation);
                   11243:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11244:                                 }
                   11245:                             }
                   11246:                         }
                   11247: # Do not overwrite contents of %metaentry hash for resource itself with 
                   11248: # hash populated for imported library file
                   11249:                         %metaentry = %currmetaentry;
                   11250:                         undef(%currmetaentry);
1.1068    www      11251:                         if ($importmode eq 'problem') {
1.1069    www      11252: # Import as problem/response
1.1068    www      11253:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11254:                         } elsif ($importmode eq 'part') {
                   11255: # Import as part(s)
1.1069    www      11256:                            $importedparts=1;
                   11257: # We need to get the original file and the imported file to get the part order correct
                   11258: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  11259: # Load and inspect original file if we didn't do that already
                   11260:                            if ($#origfiletagids<0) {
                   11261:                                undef(%importedrespids);
                   11262:                                undef(%importedpartids);
                   11263:                                if ($origfile eq '') {
                   11264:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11265:                                    $origfile=&getfile($origfilelocation);
                   11266:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11267:                                }
1.1070    www      11268:                            }
                   11269: 
1.1069    www      11270: # Load and inspect imported file
                   11271:                            my $impfile=&getfile($location);
                   11272:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11273:                            if ($#impfilepartids>=0) {
                   11274: # This problem had parts
1.1070    www      11275:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11276:                            } else {
                   11277: # Importing by turning a single problem into a problem part
                   11278: # It gets the import-tags ID as part-ID
                   11279:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11280:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11281:                            }
1.1068    www      11282:                         } else {
                   11283: # Normal import
                   11284:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11285:                            if (defined($token->[2]->{'id'})) {
                   11286:                               $unikey.='_'.$token->[2]->{'id'};
                   11287:                            }
1.1067    www      11288:                         }
                   11289: 
1.339     albertel 11290: 			if ($depthcount<20) {
1.736     albertel 11291: 			    my $metadata = 
                   11292: 				&metadata($uri,'keys', $location,$unikey,
                   11293: 					  $depthcount+1);
                   11294: 			    foreach my $meta (split(',',$metadata)) {
                   11295: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   11296: 				$metathesekeys{$meta}=1;
1.339     albertel 11297: 			    }
1.1068    www      11298: 			
                   11299:                         }
1.1067    www      11300: 		    } else {
                   11301: #
                   11302: # Not importing, some other kind of non-package, non-library start tag
                   11303: # 
                   11304:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11305:                         if (defined($token->[2]->{'id'})) {
                   11306:                             $unikey.='_'.$token->[2]->{'id'};
                   11307:                         }
1.339     albertel 11308: 			if (defined($token->[2]->{'name'})) { 
                   11309: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   11310: 			}
                   11311: 			$metathesekeys{$unikey}=1;
1.736     albertel 11312: 			foreach my $param (@{$token->[3]}) {
                   11313: 			    $metaentry{':'.$unikey.'.'.$param} =
                   11314: 				$token->[2]->{$param};
1.339     albertel 11315: 			}
                   11316: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 11317: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 11318: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   11319: 		 # only ws inside the tag, and not in default, so use default
                   11320: 		 # as value
1.599     albertel 11321: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 11322: 			} elsif ( $internaltext =~ /\S/ ) {
                   11323: 		  # something interesting inside the tag
                   11324: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 11325: 			} else {
1.908     albertel 11326: 		  # no interesting values, don't set a default
1.339     albertel 11327: 			}
1.172     www      11328: # end of not-a-package not-a-library import
1.339     albertel 11329: 		    }
1.172     www      11330: # end of not-a-package start tag
1.339     albertel 11331: 		}
1.172     www      11332: # the next is the end of "start tag"
1.339     albertel 11333: 	    }
                   11334: 	}
1.483     albertel 11335: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 11336: 	$extension = lc($extension);
                   11337: 	if ($extension eq 'htm') { $extension='html'; }
                   11338: 
1.737     albertel 11339: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 11340: 	    #no specific packages #how's our extension
                   11341: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 11342: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 11343: 					 \%metathesekeys);
                   11344: 	}
1.883     albertel 11345: 
                   11346: 	if (!exists($metaentry{':packages'})
                   11347: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 11348: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 11349: 		#no specific packages well let's get default then
                   11350: 		if ($key!~/^default&/) { next; }
1.488     albertel 11351: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 11352: 					     \%metathesekeys);
                   11353: 	    }
                   11354: 	}
1.338     www      11355: # are there custom rights to evaluate
1.599     albertel 11356: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 11357: 
1.338     www      11358:     #
                   11359:     # Importing a rights file here
1.339     albertel 11360:     #
                   11361: 	    unless ($depthcount) {
1.599     albertel 11362: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 11363: 		my $dir=$filename;
                   11364: 		$dir=~s|[^/]*$||;
                   11365: 		$location=&filelocation($dir,$location);
1.736     albertel 11366: 		my $rights_metadata =
                   11367: 		    &metadata($uri,'keys',$location,'_rights',
                   11368: 			      $depthcount+1);
                   11369: 		foreach my $rights (split(',',$rights_metadata)) {
                   11370: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   11371: 		    $metathesekeys{$rights}=1;
1.339     albertel 11372: 		}
                   11373: 	    }
                   11374: 	}
1.737     albertel 11375: 	# uniqifiy package listing
                   11376: 	my %seen;
                   11377: 	my @uniq_packages =
                   11378: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   11379: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   11380: 
1.1172.2.99  raeburn  11381:         if (($importedresponses) || ($importedparts)) {
                   11382:             if ($importedparts) {
1.1070    www      11383: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  11384:                 $metaentry{':partorder'}='';
                   11385:                 $metathesekeys{'partorder'}=1;
                   11386:             }
                   11387:             if ($importedresponses) {
                   11388: # We had imported responses and need to rebuild responseorder
                   11389:                 $metaentry{':responseorder'}='';
                   11390:                 $metathesekeys{'responseorder'}=1;
                   11391:             }
                   11392:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   11393:                 my $origid = $origfiletagids[$index+1];
                   11394:                 if ($origfiletagids[$index] eq 'part') {
                   11395: # Original part, part of the problem
                   11396:                     if ($importedparts) {
                   11397:                         $metaentry{':partorder'}.=','.$origid;
                   11398:                     }
                   11399:                 } elsif ($origfiletagids[$index] eq 'import') {
                   11400:                     if ($importedparts) {
                   11401: # We have imported parts at this position
                   11402:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   11403:                     }
                   11404:                     if ($importedresponses) {
                   11405: # We have imported responses at this position
                   11406:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   11407:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   11408:                         }
                   11409:                     }
                   11410:                 } else {
                   11411: # Original response item, part of the problem
                   11412:                     if ($importedresponses) {
                   11413:                         $metaentry{':responseorder'}.=','.$origid;
                   11414:                     }
                   11415:                 }
                   11416:             }
                   11417:             if ($importedparts) {
                   11418:                 $metaentry{':partorder'}=~s/^\,//;
                   11419:             }
                   11420:             if ($importedresponses) {
                   11421:                 $metaentry{':responseorder'}=~s/^\,//;
                   11422:             }
1.1070    www      11423:         }
                   11424: 
1.737     albertel 11425: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 11426: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  11427: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 11428: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      11429: # this is the end of "was not already recently cached
1.71      www      11430:     }
1.599     albertel 11431:     return $metaentry{':'.$what};
1.261     albertel 11432: }
                   11433: 
1.488     albertel 11434: sub metadata_create_package_def {
1.483     albertel 11435:     my ($uri,$key,$package,$metathesekeys)=@_;
                   11436:     my ($pack,$name,$subp)=split(/\&/,$key);
                   11437:     if ($subp eq 'default') { next; }
                   11438:     
1.599     albertel 11439:     if (defined($metaentry{':packages'})) {
                   11440: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 11441:     } else {
1.599     albertel 11442: 	$metaentry{':packages'}=$package;
1.483     albertel 11443:     }
                   11444:     my $value=$packagetab{$key};
                   11445:     my $unikey;
                   11446:     $unikey='parameter_0_'.$name;
1.599     albertel 11447:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 11448:     $$metathesekeys{$unikey}=1;
1.599     albertel 11449:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11450: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 11451:     }
1.599     albertel 11452:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   11453: 	$metaentry{':'.$unikey}=
                   11454: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 11455:     }
                   11456: }
                   11457: 
1.261     albertel 11458: sub metadata_generate_part0 {
                   11459:     my ($metadata,$metacache,$uri) = @_;
                   11460:     my %allnames;
1.737     albertel 11461:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 11462: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 11463: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   11464: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 11465: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 11466: 	    $allnames{$name}=$part;
                   11467: 	  }
                   11468: 	}
                   11469:     }
                   11470:     foreach my $name (keys(%allnames)) {
                   11471:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 11472:       my $key=":parameter_0_$name";
1.261     albertel 11473:       $$metacache{"$key.part"}='0';
                   11474:       $$metacache{"$key.name"}=$name;
1.428     albertel 11475:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 11476: 					   $allnames{$name}.'_'.$name.
                   11477: 					   '.type'};
1.428     albertel 11478:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 11479: 			     '.display'};
1.644     www      11480:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 11481:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 11482:       $$metacache{"$key.display"}=$olddis;
                   11483:     }
1.71      www      11484: }
                   11485: 
1.764     albertel 11486: # ------------------------------------------------------ Devalidate title cache
                   11487: 
                   11488: sub devalidate_title_cache {
                   11489:     my ($url)=@_;
                   11490:     if (!$env{'request.course.id'}) { return; }
                   11491:     my $symb=&symbread($url);
                   11492:     if (!$symb) { return; }
                   11493:     my $key=$env{'request.course.id'}."\0".$symb;
                   11494:     &devalidate_cache_new('title',$key);
                   11495: }
                   11496: 
1.1014    droeschl 11497: # ------------------------------------------------- Get the title of a course
                   11498: 
                   11499: sub current_course_title {
                   11500:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   11501: }
1.301     www      11502: # ------------------------------------------------- Get the title of a resource
                   11503: 
                   11504: sub gettitle {
                   11505:     my $urlsymb=shift;
                   11506:     my $symb=&symbread($urlsymb);
1.534     albertel 11507:     if ($symb) {
1.620     albertel 11508: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 11509: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 11510: 	if (defined($cached)) { 
                   11511: 	    return $result;
                   11512: 	}
1.534     albertel 11513: 	my ($map,$resid,$url)=&decode_symb($symb);
                   11514: 	my $title='';
1.907     albertel 11515: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   11516: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   11517: 	} else {
                   11518: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11519: 		    &GDBM_READER(),0640)) {
                   11520: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   11521: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   11522: 		untie(%bighash);
                   11523: 	    }
1.534     albertel 11524: 	}
                   11525: 	$title=~s/\&colon\;/\:/gs;
                   11526: 	if ($title) {
1.1159    www      11527: # Remember both $symb and $title for dynamic metadata
                   11528:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      11529:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      11530: # Cache this title and then return it
1.599     albertel 11531: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 11532: 	}
                   11533: 	$urlsymb=$url;
                   11534:     }
                   11535:     my $title=&metadata($urlsymb,'title');
                   11536:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   11537:     return $title;
1.301     www      11538: }
1.613     albertel 11539: 
1.614     albertel 11540: sub get_slot {
                   11541:     my ($which,$cnum,$cdom)=@_;
                   11542:     if (!$cnum || !$cdom) {
1.790     albertel 11543: 	(undef,my $courseid)=&whichuser();
1.620     albertel 11544: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   11545: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 11546:     }
1.703     albertel 11547:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   11548:     my %slotinfo;
                   11549:     if (exists($remembered{$key})) {
                   11550: 	$slotinfo{$which} = $remembered{$key};
                   11551:     } else {
                   11552: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   11553: 	&Apache::lonhomework::showhash(%slotinfo);
                   11554: 	my ($tmp)=keys(%slotinfo);
                   11555: 	if ($tmp=~/^error:/) { return (); }
                   11556: 	$remembered{$key} = $slotinfo{$which};
                   11557:     }
1.616     albertel 11558:     if (ref($slotinfo{$which}) eq 'HASH') {
                   11559: 	return %{$slotinfo{$which}};
                   11560:     }
                   11561:     return $slotinfo{$which};
1.614     albertel 11562: }
1.1150    raeburn  11563: 
                   11564: sub get_reservable_slots {
                   11565:     my ($cnum,$cdom,$uname,$udom) = @_;
                   11566:     my $now = time;
                   11567:     my $reservable_info;
                   11568:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   11569:     if (exists($remembered{$key})) {
                   11570:         $reservable_info = $remembered{$key};
                   11571:     } else {
                   11572:         my %resv;
                   11573:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   11574:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   11575:         $reservable_info = \%resv;
                   11576:         $remembered{$key} = $reservable_info;
                   11577:     }
                   11578:     return $reservable_info;
                   11579: }
                   11580: 
                   11581: sub get_course_slots {
                   11582:     my ($cnum,$cdom) = @_;
                   11583:     my $hashid=$cnum.':'.$cdom;
                   11584:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   11585:     if (defined($cached)) {
                   11586:         if (ref($result) eq 'HASH') {
                   11587:             return %{$result};
                   11588:         }
                   11589:     } else {
                   11590:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   11591:         my ($tmp) = keys(%slots);
                   11592:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  11593:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  11594:             return %slots;
                   11595:         }
                   11596:     }
                   11597:     return;
                   11598: }
                   11599: 
                   11600: sub devalidate_slots_cache {
                   11601:     my ($cnum,$cdom)=@_;
                   11602:     my $hashid=$cnum.':'.$cdom;
                   11603:     &devalidate_cache_new('allslots',$hashid);
                   11604: }
                   11605: 
1.1172.2.8  raeburn  11606: sub get_coursechange {
                   11607:     my ($cdom,$cnum) = @_;
                   11608:     if ($cdom eq '' || $cnum eq '') {
                   11609:         return unless ($env{'request.course.id'});
                   11610:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   11611:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11612:     }
                   11613:     my $hashid=$cdom.'_'.$cnum;
                   11614:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   11615:     if ((defined($cached)) && ($change ne '')) {
                   11616:         return $change;
                   11617:     } else {
                   11618:         my %crshash;
                   11619:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   11620:         if ($crshash{'internal.contentchange'} eq '') {
                   11621:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   11622:             if ($change eq '') {
                   11623:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   11624:                 $change = $crshash{'internal.created'};
                   11625:             }
                   11626:         } else {
                   11627:             $change = $crshash{'internal.contentchange'};
                   11628:         }
                   11629:         my $cachetime = 600;
                   11630:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   11631:     }
                   11632:     return $change;
                   11633: }
                   11634: 
                   11635: sub devalidate_coursechange_cache {
                   11636:     my ($cnum,$cdom)=@_;
                   11637:     my $hashid=$cnum.':'.$cdom;
                   11638:     &devalidate_cache_new('crschange',$hashid);
                   11639: }
                   11640: 
1.31      www      11641: # ------------------------------------------------- Update symbolic store links
                   11642: 
                   11643: sub symblist {
                   11644:     my ($mapname,%newhash)=@_;
1.438     www      11645:     $mapname=&deversion(&declutter($mapname));
1.31      www      11646:     my %hash;
1.620     albertel 11647:     if (($env{'request.course.fn'}) && (%newhash)) {
                   11648:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11649:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  11650: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 11651: 		next if ($url eq 'last_known'
                   11652: 			 && $env{'form.no_update_last_known'});
                   11653: 		$hash{declutter($url)}=&encode_symb($mapname,
                   11654: 						    $newhash{$url}->[1],
                   11655: 						    $newhash{$url}->[0]);
1.191     harris41 11656:             }
1.31      www      11657:             if (untie(%hash)) {
                   11658: 		return 'ok';
                   11659:             }
                   11660:         }
                   11661:     }
                   11662:     return 'error';
1.212     www      11663: }
                   11664: 
                   11665: # --------------------------------------------------------------- Verify a symb
                   11666: 
                   11667: sub symbverify {
1.1172.2.11  raeburn  11668:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      11669:     my $thisfn=$thisurl;
1.439     www      11670:     $thisfn=&declutter($thisfn);
1.215     www      11671: # direct jump to resource in page or to a sequence - will construct own symbs
                   11672:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   11673: # check URL part
1.409     www      11674:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      11675: 
1.431     www      11676:     unless ($url eq $thisfn) { return 0; }
1.213     www      11677: 
1.216     www      11678:     $symb=&symbclean($symb);
1.510     www      11679:     $thisurl=&deversion($thisurl);
1.439     www      11680:     $thisfn=&deversion($thisfn);
1.213     www      11681: 
                   11682:     my %bighash;
                   11683:     my $okay=0;
1.431     www      11684: 
1.620     albertel 11685:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11686:                             &GDBM_READER(),0640)) {
1.1172.2.13  raeburn  11687:         my $noclutter;
1.1032    raeburn  11688:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   11689:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  11690:             if ($map =~ m{^uploaded/.+\.page$}) {
                   11691:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   11692:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   11693:                 $noclutter = 1;
                   11694:             }
                   11695:         }
                   11696:         my $ids;
                   11697:         if ($noclutter) {
                   11698:             $ids=$bighash{'ids_'.$thisurl};
                   11699:         } else {
                   11700:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  11701:         }
1.1102    raeburn  11702:         unless ($ids) {
1.1172.2.13  raeburn  11703:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  11704:             $ids=$bighash{$idkey};
1.216     www      11705:         }
                   11706:         if ($ids) {
                   11707: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  11708:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   11709:                 $symb =~ s/\?.+$//;
                   11710:             }
1.800     albertel 11711: 	    foreach my $id (split(/\,/,$ids)) {
                   11712: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      11713:                if (
                   11714:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  11715:    eq $symb) {
1.1172.2.11  raeburn  11716:                    if (ref($encstate)) {
                   11717:                        $$encstate = $bighash{'encrypted_'.$id};
                   11718:                    }
1.1172.2.13  raeburn  11719:                    if (($env{'request.role.adv'}) ||
                   11720:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  11721:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  11722:                        $okay=1;
                   11723:                        last;
                   11724:                    }
                   11725:                }
                   11726:            }
1.216     www      11727:         }
1.213     www      11728: 	untie(%bighash);
                   11729:     }
                   11730:     return $okay;
1.31      www      11731: }
                   11732: 
1.210     www      11733: # --------------------------------------------------------------- Clean-up symb
                   11734: 
                   11735: sub symbclean {
                   11736:     my $symb=shift;
1.568     albertel 11737:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      11738: # remove version from map
                   11739:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      11740: 
1.210     www      11741: # remove version from URL
                   11742:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      11743: 
1.507     www      11744: # remove wrapper
                   11745: 
1.510     www      11746:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 11747:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      11748:     return $symb;
1.409     www      11749: }
                   11750: 
                   11751: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 11752: 
                   11753: sub encode_symb {
                   11754:     my ($map,$resid,$url)=@_;
                   11755:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   11756: }
1.409     www      11757: 
                   11758: sub decode_symb {
1.568     albertel 11759:     my $symb=shift;
                   11760:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   11761:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      11762:     return (&fixversion($map),$resid,&fixversion($url));
                   11763: }
                   11764: 
                   11765: sub fixversion {
                   11766:     my $fn=shift;
1.609     banghart 11767:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      11768:     my %bighash;
                   11769:     my $uri=&clutter($fn);
1.620     albertel 11770:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      11771: # is this cached?
1.599     albertel 11772:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      11773:     if (defined($cached)) { return $result; }
                   11774: # unfortunately not cached, or expired
1.620     albertel 11775:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      11776: 	    &GDBM_READER(),0640)) {
                   11777:  	if ($bighash{'version_'.$uri}) {
                   11778:  	    my $version=$bighash{'version_'.$uri};
1.444     www      11779:  	    unless (($version eq 'mostrecent') || 
                   11780: 		    ($version==&getversion($uri))) {
1.440     www      11781:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   11782:  	    }
                   11783:  	}
                   11784:  	untie %bighash;
1.413     www      11785:     }
1.599     albertel 11786:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      11787: }
                   11788: 
                   11789: sub deversion {
                   11790:     my $url=shift;
                   11791:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   11792:     return $url;
1.210     www      11793: }
                   11794: 
1.31      www      11795: # ------------------------------------------------------ Return symb list entry
                   11796: 
                   11797: sub symbread {
1.1172.2.66  raeburn  11798:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54  raeburn  11799:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66  raeburn  11800:     if (defined($env{$cache_str})) {
                   11801:         if ($ignorecachednull) {
                   11802:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   11803:         } else {
                   11804:             return $env{$cache_str};
                   11805:         }
                   11806:     }
1.242     www      11807: # no filename provided? try from environment
1.1172.2.54  raeburn  11808:     unless ($thisfn) {
1.620     albertel 11809:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  11810:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   11811:         }
                   11812:         $thisfn=$env{'request.filename'};
1.44      www      11813:     }
1.569     albertel 11814:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      11815: # is that filename actually a symb? Verify, clean, and return
                   11816:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 11817: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 11818: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 11819: 	}
1.242     www      11820:     }
1.44      www      11821:     $thisfn=declutter($thisfn);
1.31      www      11822:     my %hash;
1.37      www      11823:     my %bighash;
                   11824:     my $syval='';
1.620     albertel 11825:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  11826:         my $targetfn = $thisfn;
1.609     banghart 11827:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  11828:             $targetfn = 'adm/wrapper/'.$thisfn;
                   11829:         }
1.687     albertel 11830: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   11831: 	    $targetfn=$1;
                   11832: 	}
1.620     albertel 11833:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11834:                       &GDBM_READER(),0640)) {
1.481     raeburn  11835: 	    $syval=$hash{$targetfn};
1.37      www      11836:             untie(%hash);
                   11837:         }
                   11838: # ---------------------------------------------------------- There was an entry
                   11839:         if ($syval) {
1.601     albertel 11840: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 11841: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  11842: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11843: 		    #return $env{$cache_str}='';
1.601     albertel 11844: 		#}    
                   11845: 		#$syval.=$1;
                   11846: 	    #}
1.37      www      11847:         } else {
                   11848: # ------------------------------------------------------- Was not in symb table
1.620     albertel 11849:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11850:                             &GDBM_READER(),0640)) {
1.37      www      11851: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      11852:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      11853:               unless ($ids) { 
                   11854:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      11855:               }
                   11856:               unless ($ids) {
                   11857: # alias?
                   11858: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      11859:               }
1.37      www      11860:               if ($ids) {
                   11861: # ------------------------------------------------------------------- Has ID(s)
                   11862:                  my @possibilities=split(/\,/,$ids);
1.39      www      11863:                  if ($#possibilities==0) {
                   11864: # ----------------------------------------------- There is only one possibility
1.37      www      11865: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 11866: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11867: 						    $resid,$thisfn);
1.1172.2.66  raeburn  11868:                      if (ref($possibles) eq 'HASH') {
                   11869:                          $possibles->{$syval} = 1;
                   11870:                      }
                   11871:                      if ($checkforblock) {
                   11872:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   11873:                          if (@blockers) {
                   11874:                              $syval = '';
                   11875:                              return;
                   11876:                          }
                   11877:                      }
                   11878:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      11879: # ------------------------------------------ There is more than one possibility
                   11880:                      my $realpossible=0;
1.800     albertel 11881:                      foreach my $id (@possibilities) {
                   11882: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  11883:                          my $canaccess;
                   11884:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   11885:                              $canaccess = 1;
                   11886:                          } else {
                   11887:                              $canaccess = &allowed('bre',$file);
                   11888:                          }
                   11889:                          if ($canaccess) {
                   11890:          		     my ($mapid,$resid)=split(/\./,$id);
                   11891:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   11892:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11893:                                                              $resid,$thisfn);
                   11894:                                  if (ref($possibles) eq 'HASH') {
                   11895:                                      $possibles->{$syval} = 1;
                   11896:                                  }
                   11897:                                  if ($checkforblock) {
                   11898:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   11899:                                      unless (@blockers > 0) {
                   11900:                                          $syval = $poss_syval;
                   11901:                                          $realpossible++;
                   11902:                                      }
                   11903:                                  } else {
                   11904:                                      $syval = $poss_syval;
                   11905:                                      $realpossible++;
                   11906:                                  }
                   11907:                              }
1.39      www      11908: 			 }
1.191     harris41 11909:                      }
1.39      www      11910: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      11911:                  } else {
                   11912:                      $syval='';
1.37      www      11913:                  }
                   11914: 	      }
1.1172.2.66  raeburn  11915:               untie(%bighash);
1.481     raeburn  11916:            }
1.31      www      11917:         }
1.62      www      11918:         if ($syval) {
1.620     albertel 11919: 	    return $env{$cache_str}=$syval;
1.62      www      11920:         }
1.31      www      11921:     }
1.949     raeburn  11922:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11923:     return $env{$cache_str}='';
1.31      www      11924: }
                   11925: 
                   11926: # ---------------------------------------------------------- Return random seed
                   11927: 
1.32      www      11928: sub numval {
                   11929:     my $txt=shift;
                   11930:     $txt=~tr/A-J/0-9/;
                   11931:     $txt=~tr/a-j/0-9/;
                   11932:     $txt=~tr/K-T/0-9/;
                   11933:     $txt=~tr/k-t/0-9/;
                   11934:     $txt=~tr/U-Z/0-5/;
                   11935:     $txt=~tr/u-z/0-5/;
                   11936:     $txt=~s/\D//g;
1.564     albertel 11937:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      11938:     return int($txt);
1.368     albertel 11939: }
                   11940: 
1.484     albertel 11941: sub numval2 {
                   11942:     my $txt=shift;
                   11943:     $txt=~tr/A-J/0-9/;
                   11944:     $txt=~tr/a-j/0-9/;
                   11945:     $txt=~tr/K-T/0-9/;
                   11946:     $txt=~tr/k-t/0-9/;
                   11947:     $txt=~tr/U-Z/0-5/;
                   11948:     $txt=~tr/u-z/0-5/;
                   11949:     $txt=~s/\D//g;
                   11950:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11951:     my $total;
                   11952:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 11953:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 11954:     return int($total);
                   11955: }
                   11956: 
1.575     albertel 11957: sub numval3 {
                   11958:     use integer;
                   11959:     my $txt=shift;
                   11960:     $txt=~tr/A-J/0-9/;
                   11961:     $txt=~tr/a-j/0-9/;
                   11962:     $txt=~tr/K-T/0-9/;
                   11963:     $txt=~tr/k-t/0-9/;
                   11964:     $txt=~tr/U-Z/0-5/;
                   11965:     $txt=~tr/u-z/0-5/;
                   11966:     $txt=~s/\D//g;
                   11967:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11968:     my $total;
                   11969:     foreach my $val (@txts) { $total+=$val; }
                   11970:     if ($_64bit) { $total=(($total<<32)>>32); }
                   11971:     return $total;
                   11972: }
                   11973: 
1.675     albertel 11974: sub digest {
                   11975:     my ($data)=@_;
                   11976:     my $digest=&Digest::MD5::md5($data);
                   11977:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   11978:     my ($e,$f);
                   11979:     {
                   11980:         use integer;
                   11981:         $e=($a+$b);
                   11982:         $f=($c+$d);
                   11983:         if ($_64bit) {
                   11984:             $e=(($e<<32)>>32);
                   11985:             $f=(($f<<32)>>32);
                   11986:         }
                   11987:     }
                   11988:     if (wantarray) {
                   11989: 	return ($e,$f);
                   11990:     } else {
                   11991: 	my $g;
                   11992: 	{
                   11993: 	    use integer;
                   11994: 	    $g=($e+$f);
                   11995: 	    if ($_64bit) {
                   11996: 		$g=(($g<<32)>>32);
                   11997: 	    }
                   11998: 	}
                   11999: 	return $g;
                   12000:     }
                   12001: }
                   12002: 
1.368     albertel 12003: sub latest_rnd_algorithm_id {
1.675     albertel 12004:     return '64bit5';
1.366     albertel 12005: }
1.32      www      12006: 
1.503     albertel 12007: sub get_rand_alg {
                   12008:     my ($courseid)=@_;
1.790     albertel 12009:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12010:     if ($courseid) {
1.620     albertel 12011: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12012:     }
                   12013:     return &latest_rnd_algorithm_id();
                   12014: }
                   12015: 
1.562     albertel 12016: sub validCODE {
                   12017:     my ($CODE)=@_;
                   12018:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12019:     return 0;
                   12020: }
                   12021: 
1.491     albertel 12022: sub getCODE {
1.620     albertel 12023:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12024:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12025: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12026: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12027: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12028:     }
                   12029:     return undef;
                   12030: }
1.1133    foxr     12031: #
                   12032: #  Determines the random seed for a specific context:
                   12033: #
                   12034: # parameters:
                   12035: #   symb      - in course context the symb for the seed.
                   12036: #   course_id - The course id of the form domain_coursenum.
                   12037: #   domain    - Domain for the user.
                   12038: #   course    - Course for the user.
                   12039: #   cenv      - environment of the course.
                   12040: #
                   12041: # NOTE:
                   12042: #   All parameters are picked out of the environment if missing
                   12043: #   or not defined.
                   12044: #   If a symb cannot be determined the current time is used instead.
                   12045: #
                   12046: #  For a given well defined symb, courside, domain, username,
                   12047: #  and course environment, the seed is reproducible.
                   12048: #
1.31      www      12049: sub rndseed {
1.1133    foxr     12050:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12051:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12052:     if (!defined($symb)) {
1.366     albertel 12053: 	unless ($symb=$wsymb) { return time; }
                   12054:     }
1.1146    foxr     12055:     if (!defined $courseid) { 
                   12056: 	$courseid=$wcourseid; 
                   12057:     }
                   12058:     if (!defined $domain) { $domain=$wdomain; }
                   12059:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12060: 
                   12061:     my $which;
                   12062:     if (defined($cenv->{'rndseed'})) {
                   12063: 	$which = $cenv->{'rndseed'};
                   12064:     } else {
                   12065: 	$which =&get_rand_alg($courseid);
                   12066:     }
1.491     albertel 12067:     if (defined(&getCODE())) {
1.675     albertel 12068: 	if ($which eq '64bit5') {
                   12069: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12070: 	} elsif ($which eq '64bit4') {
1.575     albertel 12071: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12072: 	} else {
                   12073: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12074: 	}
1.675     albertel 12075:     } elsif ($which eq '64bit5') {
                   12076: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12077:     } elsif ($which eq '64bit4') {
                   12078: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12079:     } elsif ($which eq '64bit3') {
                   12080: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12081:     } elsif ($which eq '64bit2') {
                   12082: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12083:     } elsif ($which eq '64bit') {
                   12084: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12085:     }
                   12086:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12087: }
                   12088: 
                   12089: sub rndseed_32bit {
                   12090:     my ($symb,$courseid,$domain,$username)=@_;
                   12091:     {
                   12092: 	use integer;
                   12093: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12094: 	my $symbseed=numval($symb) << 22;
                   12095: 	my $namechck=unpack("%32C*",$username) << 17;
                   12096: 	my $nameseed=numval($username) << 12;
                   12097: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12098: 	my $courseseed=unpack("%32C*",$courseid);
                   12099: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12100: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12101: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12102: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12103: 	return $num;
                   12104:     }
                   12105: }
                   12106: 
                   12107: sub rndseed_64bit {
                   12108:     my ($symb,$courseid,$domain,$username)=@_;
                   12109:     {
                   12110: 	use integer;
                   12111: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12112: 	my $symbseed=numval($symb) << 10;
                   12113: 	my $namechck=unpack("%32S*",$username);
                   12114: 	
                   12115: 	my $nameseed=numval($username) << 21;
                   12116: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12117: 	my $courseseed=unpack("%32S*",$courseid);
                   12118: 	
                   12119: 	my $num1=$symbchck+$symbseed+$namechck;
                   12120: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12121: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12122: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12123: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12124: 	return "$num1,$num2";
1.155     albertel 12125:     }
1.366     albertel 12126: }
                   12127: 
1.443     albertel 12128: sub rndseed_64bit2 {
                   12129:     my ($symb,$courseid,$domain,$username)=@_;
                   12130:     {
                   12131: 	use integer;
                   12132: 	# strings need to be an even # of cahracters long, it it is odd the
                   12133:         # last characters gets thrown away
                   12134: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12135: 	my $symbseed=numval($symb) << 10;
                   12136: 	my $namechck=unpack("%32S*",$username.' ');
                   12137: 	
                   12138: 	my $nameseed=numval($username) << 21;
1.501     albertel 12139: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12140: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12141: 	
                   12142: 	my $num1=$symbchck+$symbseed+$namechck;
                   12143: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12144: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12145: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12146: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12147: 	return "$num1,$num2";
                   12148:     }
                   12149: }
                   12150: 
                   12151: sub rndseed_64bit3 {
                   12152:     my ($symb,$courseid,$domain,$username)=@_;
                   12153:     {
                   12154: 	use integer;
                   12155: 	# strings need to be an even # of cahracters long, it it is odd the
                   12156:         # last characters gets thrown away
                   12157: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12158: 	my $symbseed=numval2($symb) << 10;
                   12159: 	my $namechck=unpack("%32S*",$username.' ');
                   12160: 	
                   12161: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12162: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12163: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12164: 	
                   12165: 	my $num1=$symbchck+$symbseed+$namechck;
                   12166: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12167: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12168: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12169: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12170: 	
1.503     albertel 12171: 	return "$num1:$num2";
1.443     albertel 12172:     }
                   12173: }
                   12174: 
1.575     albertel 12175: sub rndseed_64bit4 {
                   12176:     my ($symb,$courseid,$domain,$username)=@_;
                   12177:     {
                   12178: 	use integer;
                   12179: 	# strings need to be an even # of cahracters long, it it is odd the
                   12180:         # last characters gets thrown away
                   12181: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12182: 	my $symbseed=numval3($symb) << 10;
                   12183: 	my $namechck=unpack("%32S*",$username.' ');
                   12184: 	
                   12185: 	my $nameseed=numval3($username) << 21;
                   12186: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12187: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12188: 	
                   12189: 	my $num1=$symbchck+$symbseed+$namechck;
                   12190: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12191: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12192: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12193: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12194: 	
1.575     albertel 12195: 	return "$num1:$num2";
                   12196:     }
                   12197: }
                   12198: 
1.675     albertel 12199: sub rndseed_64bit5 {
                   12200:     my ($symb,$courseid,$domain,$username)=@_;
                   12201:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12202:     return "$num1:$num2";
                   12203: }
                   12204: 
1.366     albertel 12205: sub rndseed_CODE_64bit {
                   12206:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12207:     {
1.366     albertel 12208: 	use integer;
1.443     albertel 12209: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12210: 	my $symbseed=numval2($symb);
1.491     albertel 12211: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12212: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12213: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12214: 	my $num1=$symbseed+$CODEchck;
                   12215: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12216: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12217: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12218: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12219: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12220: 	return "$num1:$num2";
1.366     albertel 12221:     }
                   12222: }
                   12223: 
1.575     albertel 12224: sub rndseed_CODE_64bit4 {
                   12225:     my ($symb,$courseid,$domain,$username)=@_;
                   12226:     {
                   12227: 	use integer;
                   12228: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12229: 	my $symbseed=numval3($symb);
                   12230: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12231: 	my $CODEseed=numval3(&getCODE());
                   12232: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12233: 	my $num1=$symbseed+$CODEchck;
                   12234: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12235: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12236: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12237: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12238: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12239: 	return "$num1:$num2";
                   12240:     }
                   12241: }
                   12242: 
1.675     albertel 12243: sub rndseed_CODE_64bit5 {
                   12244:     my ($symb,$courseid,$domain,$username)=@_;
                   12245:     my $code = &getCODE();
                   12246:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12247:     return "$num1:$num2";
                   12248: }
                   12249: 
1.366     albertel 12250: sub setup_random_from_rndseed {
                   12251:     my ($rndseed)=@_;
1.503     albertel 12252:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  12253: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12254:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12255:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   12256:         } else {
                   12257:             &Math::Random::random_set_seed($num1,$num2);
                   12258:         }
1.366     albertel 12259:     } else {
                   12260: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12261:     }
1.36      albertel 12262: }
                   12263: 
1.474     albertel 12264: sub latest_receipt_algorithm_id {
1.835     albertel 12265:     return 'receipt3';
1.474     albertel 12266: }
                   12267: 
1.480     www      12268: sub recunique {
                   12269:     my $fucourseid=shift;
                   12270:     my $unique;
1.835     albertel 12271:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   12272: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12273: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      12274:     } else {
                   12275: 	$unique=$perlvar{'lonReceipt'};
                   12276:     }
                   12277:     return unpack("%32C*",$unique);
                   12278: }
                   12279: 
                   12280: sub recprefix {
                   12281:     my $fucourseid=shift;
                   12282:     my $prefix;
1.835     albertel 12283:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   12284: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12285: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      12286:     } else {
                   12287: 	$prefix=$perlvar{'lonHostID'};
                   12288:     }
                   12289:     return unpack("%32C*",$prefix);
                   12290: }
                   12291: 
1.76      www      12292: sub ireceipt {
1.474     albertel 12293:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 12294: 
                   12295:     my $return =&recprefix($fucourseid).'-';
                   12296: 
                   12297:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   12298: 	$env{'request.state'} eq 'construct') {
                   12299: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   12300: 	return $return;
                   12301:     }
                   12302: 
1.76      www      12303:     my $cuname=unpack("%32C*",$funame);
                   12304:     my $cudom=unpack("%32C*",$fudom);
                   12305:     my $cucourseid=unpack("%32C*",$fucourseid);
                   12306:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      12307:     my $cunique=&recunique($fucourseid);
1.474     albertel 12308:     my $cpart=unpack("%32S*",$part);
1.835     albertel 12309:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   12310: 
1.790     albertel 12311: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 12312: 			       
                   12313: 	$return.= ($cunique%$cuname+
                   12314: 		   $cunique%$cudom+
                   12315: 		   $cusymb%$cuname+
                   12316: 		   $cusymb%$cudom+
                   12317: 		   $cucourseid%$cuname+
                   12318: 		   $cucourseid%$cudom+
                   12319: 		   $cpart%$cuname+
                   12320: 		   $cpart%$cudom);
                   12321:     } else {
                   12322: 	$return.= ($cunique%$cuname+
                   12323: 		   $cunique%$cudom+
                   12324: 		   $cusymb%$cuname+
                   12325: 		   $cusymb%$cudom+
                   12326: 		   $cucourseid%$cuname+
                   12327: 		   $cucourseid%$cudom);
                   12328:     }
                   12329:     return $return;
1.76      www      12330: }
                   12331: 
                   12332: sub receipt {
1.474     albertel 12333:     my ($part)=@_;
1.790     albertel 12334:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 12335:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      12336: }
1.260     ng       12337: 
1.790     albertel 12338: sub whichuser {
                   12339:     my ($passedsymb)=@_;
                   12340:     my ($symb,$courseid,$domain,$name,$publicuser);
                   12341:     if (defined($env{'form.grade_symb'})) {
                   12342: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   12343: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   12344: 	if (!$allowed &&
                   12345: 	    exists($env{'request.course.sec'}) &&
                   12346: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   12347: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   12348: 			      '/'.$env{'request.course.sec'});
                   12349: 	}
                   12350: 	if ($allowed) {
                   12351: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   12352: 	    $courseid=$tmp_courseid;
                   12353: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   12354: 	    ($name)=&get_env_multiple('form.grade_username');
                   12355: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   12356: 	}
                   12357:     }
                   12358:     if (!$passedsymb) {
                   12359: 	$symb=&symbread();
                   12360:     } else {
                   12361: 	$symb=$passedsymb;
                   12362:     }
                   12363:     $courseid=$env{'request.course.id'};
                   12364:     $domain=$env{'user.domain'};
                   12365:     $name=$env{'user.name'};
                   12366:     if ($name eq 'public' && $domain eq 'public') {
                   12367: 	if (!defined($env{'form.username'})) {
                   12368: 	    $env{'form.username'}.=time.rand(10000000);
                   12369: 	}
                   12370: 	$name.=$env{'form.username'};
                   12371:     }
                   12372:     return ($symb,$courseid,$domain,$name,$publicuser);
                   12373: 
                   12374: }
                   12375: 
1.36      albertel 12376: # ------------------------------------------------------------ Serves up a file
1.472     albertel 12377: # returns either the contents of the file or 
                   12378: # -1 if the file doesn't exist
1.481     raeburn  12379: #
                   12380: # if the target is a file that was uploaded via DOCS, 
                   12381: # a check will be made to see if a current copy exists on the local server,
                   12382: # if it does this will be served, otherwise a copy will be retrieved from
                   12383: # the home server for the course and stored in /home/httpd/html/userfiles on
                   12384: # the local server.   
1.472     albertel 12385: 
1.36      albertel 12386: sub getfile {
1.538     albertel 12387:     my ($file) = @_;
1.609     banghart 12388:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 12389:     &repcopy($file);
                   12390:     return &readfile($file);
                   12391: }
                   12392: 
                   12393: sub repcopy_userfile {
                   12394:     my ($file)=@_;
1.1142    raeburn  12395:     my $londocroot = $perlvar{'lonDocRoot'};
                   12396:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  12397:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 12398:     my ($cdom,$cnum,$filename) = 
1.811     albertel 12399: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 12400:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   12401:     if (-e "$file") {
1.828     www      12402: # we already have a local copy, check it out
1.538     albertel 12403: 	my @fileinfo = stat($file);
1.828     www      12404: 	my $rtncode;
                   12405: 	my $info;
1.538     albertel 12406: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 12407: 	if ($lwpresp ne 'ok') {
1.828     www      12408: # there is no such file anymore, even though we had a local copy
1.482     albertel 12409: 	    if ($rtncode eq '404') {
1.538     albertel 12410: 		unlink($file);
1.482     albertel 12411: 	    }
                   12412: 	    return -1;
                   12413: 	}
                   12414: 	if ($info < $fileinfo[9]) {
1.828     www      12415: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  12416: 	    return 'ok';
1.828     www      12417: 	} else {
                   12418: # the file is outdated, get rid of it
                   12419: 	    unlink($file);
1.482     albertel 12420: 	}
1.828     www      12421:     }
                   12422: # one way or the other, at this point, we don't have the file
                   12423: # construct the correct path for the file
                   12424:     my @parts = ($cdom,$cnum); 
                   12425:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   12426: 	push @parts, split(/\//,$1);
                   12427:     }
                   12428:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   12429:     foreach my $part (@parts) {
                   12430: 	$path .= '/'.$part;
                   12431: 	if (!-e $path) {
                   12432: 	    mkdir($path,0770);
1.482     albertel 12433: 	}
                   12434:     }
1.828     www      12435: # now the path exists for sure
                   12436: # get a user agent
                   12437:     my $ua=new LWP::UserAgent;
                   12438:     my $transferfile=$file.'.in.transfer';
                   12439: # FIXME: this should flock
                   12440:     if (-e $transferfile) { return 'ok'; }
                   12441:     my $request;
                   12442:     $uri=~s/^\///;
1.980     raeburn  12443:     my $homeserver = &homeserver($cnum,$cdom);
                   12444:     my $protocol = $protocol{$homeserver};
                   12445:     $protocol = 'http' if ($protocol ne 'https');
                   12446:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      12447:     my $response=$ua->request($request,$transferfile);
                   12448: # did it work?
                   12449:     if ($response->is_error()) {
                   12450: 	unlink($transferfile);
                   12451: 	&logthis("Userfile repcopy failed for $uri");
                   12452: 	return -1;
                   12453:     }
                   12454: # worked, rename the transfer file
                   12455:     rename($transferfile,$file);
1.607     raeburn  12456:     return 'ok';
1.481     raeburn  12457: }
                   12458: 
1.517     albertel 12459: sub tokenwrapper {
                   12460:     my $uri=shift;
1.980     raeburn  12461:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 12462:     $uri=~s|^/||;
1.620     albertel 12463:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 12464:     my $token=$1;
1.552     albertel 12465:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   12466:     if ($udom && $uname && $file) {
                   12467: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  12468:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  12469:         my $homeserver = &homeserver($uname,$udom);
                   12470:         my $protocol = $protocol{$homeserver};
                   12471:         $protocol = 'http' if ($protocol ne 'https');
                   12472:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 12473:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   12474:                                '&tokenissued='.$perlvar{'lonHostID'};
                   12475:     } else {
                   12476:         return '/adm/notfound.html';
                   12477:     }
                   12478: }
                   12479: 
1.828     www      12480: # call with reqtype HEAD: get last modification time
                   12481: # call with reqtype GET: get the file contents
                   12482: # Do not call this with reqtype GET for large files! It loads everything into memory
                   12483: #
1.481     raeburn  12484: sub getuploaded {
                   12485:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   12486:     $uri=~s/^\///;
1.980     raeburn  12487:     my $homeserver = &homeserver($cnum,$cdom);
                   12488:     my $protocol = $protocol{$homeserver};
                   12489:     $protocol = 'http' if ($protocol ne 'https');
                   12490:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  12491:     my $ua=new LWP::UserAgent;
                   12492:     my $request=new HTTP::Request($reqtype,$uri);
                   12493:     my $response=$ua->request($request);
                   12494:     $$rtncode = $response->code;
1.482     albertel 12495:     if (! $response->is_success()) {
                   12496: 	return 'failed';
                   12497:     }      
                   12498:     if ($reqtype eq 'HEAD') {
1.486     www      12499: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 12500:     } elsif ($reqtype eq 'GET') {
                   12501: 	$$info = $response->content;
1.472     albertel 12502:     }
1.482     albertel 12503:     return 'ok';
1.36      albertel 12504: }
                   12505: 
1.481     raeburn  12506: sub readfile {
                   12507:     my $file = shift;
                   12508:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   12509:     my $fh;
1.1172.2.96  raeburn  12510:     open($fh,"<",$file);
1.481     raeburn  12511:     my $a='';
1.800     albertel 12512:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  12513:     return $a;
                   12514: }
                   12515: 
1.36      albertel 12516: sub filelocation {
1.590     banghart 12517:     my ($dir,$file) = @_;
                   12518:     my $location;
                   12519:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 12520: 
                   12521:     if ($file =~ m-^/adm/-) {
                   12522: 	$file=~s-^/adm/wrapper/-/-;
                   12523: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   12524:     }
1.882     albertel 12525: 
1.1139    www      12526:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  12527:         $location = $file;
1.609     banghart 12528:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 12529:         my ($udom,$uname,$filename)=
1.811     albertel 12530:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 12531:         my $home=&homeserver($uname,$udom);
                   12532:         my $is_me=0;
                   12533:         my @ids=&current_machine_ids();
                   12534:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   12535:         if ($is_me) {
1.1117    foxr     12536:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 12537:         } else {
                   12538:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   12539:   	      $udom.'/'.$uname.'/'.$filename;
                   12540:         }
1.882     albertel 12541:     } elsif ($file =~ m-^/adm/-) {
                   12542: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 12543:     } else {
                   12544:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      12545:         $file=~s:^/(res|priv)/:/:;
                   12546:         my $space=$1;
1.590     banghart 12547:         if ( !( $file =~ m:^/:) ) {
                   12548:             $location = $dir. '/'.$file;
                   12549:         } else {
1.1142    raeburn  12550:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 12551:         }
1.59      albertel 12552:     }
1.590     banghart 12553:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 12554:     while ($location=~m{/\.\./}) {
                   12555: 	if ($location =~ m{/[^/]+/\.\./}) {
                   12556: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   12557: 	} else {
                   12558: 	    $location=~ s{/\.\./}{/}g;
                   12559: 	}
                   12560:     } #remove dir/..
1.590     banghart 12561:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   12562:     return $location;
1.46      www      12563: }
1.36      albertel 12564: 
1.46      www      12565: sub hreflocation {
                   12566:     my ($dir,$file)=@_;
1.980     raeburn  12567:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 12568: 	$file=filelocation($dir,$file);
1.700     albertel 12569:     } elsif ($file=~m-^/adm/-) {
                   12570: 	$file=~s-^/adm/wrapper/-/-;
                   12571: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 12572:     }
                   12573:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   12574: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   12575:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  12576: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   12577: 	        {/uploaded/$1/$2/}x;
1.46      www      12578:     }
1.913     albertel 12579:     if ($file=~ m{^/userfiles/}) {
                   12580: 	$file =~ s{^/userfiles/}{/uploaded/};
                   12581:     }
1.462     albertel 12582:     return $file;
1.465     albertel 12583: }
                   12584: 
1.1139    www      12585: 
                   12586: 
                   12587: 
                   12588: 
1.465     albertel 12589: sub current_machine_domains {
1.853     albertel 12590:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   12591: }
                   12592: 
                   12593: sub machine_domains {
                   12594:     my ($hostname) = @_;
1.465     albertel 12595:     my @domains;
1.838     albertel 12596:     my %hostname = &all_hostnames();
1.465     albertel 12597:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  12598: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 12599: 	if ($hostname eq $name) {
1.844     albertel 12600: 	    push(@domains,&host_domain($id));
1.465     albertel 12601: 	}
                   12602:     }
                   12603:     return @domains;
                   12604: }
                   12605: 
                   12606: sub current_machine_ids {
1.853     albertel 12607:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   12608: }
                   12609: 
                   12610: sub machine_ids {
                   12611:     my ($hostname) = @_;
                   12612:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 12613:     my @ids;
1.888     albertel 12614:     my %name_to_host = &all_names();
1.889     albertel 12615:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   12616: 	return @{ $name_to_host{$hostname} };
                   12617:     }
                   12618:     return;
1.31      www      12619: }
                   12620: 
1.824     raeburn  12621: sub additional_machine_domains {
                   12622:     my @domains;
1.1172.2.96  raeburn  12623:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  12624:     while( my $line = <$fh>) {
                   12625:         $line =~ s/\s//g;
                   12626:         push(@domains,$line);
                   12627:     }
                   12628:     return @domains;
                   12629: }
                   12630: 
                   12631: sub default_login_domain {
                   12632:     my $domain = $perlvar{'lonDefDomain'};
                   12633:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   12634:     foreach my $posdom (&current_machine_domains(),
                   12635:                         &additional_machine_domains()) {
                   12636:         if (lc($posdom) eq lc($testdomain)) {
                   12637:             $domain=$posdom;
                   12638:             last;
                   12639:         }
                   12640:     }
                   12641:     return $domain;
                   12642: }
                   12643: 
1.31      www      12644: # ------------------------------------------------------------- Declutters URLs
                   12645: 
                   12646: sub declutter {
                   12647:     my $thisfn=shift;
1.569     albertel 12648:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  12649:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   12650:         $thisfn=~s{^/home/httpd/html}{};
                   12651:     }
1.31      www      12652:     $thisfn=~s/^\///;
1.697     albertel 12653:     $thisfn=~s|^adm/wrapper/||;
                   12654:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      12655:     $thisfn=~s/^res\///;
1.1172    bisitz   12656:     $thisfn=~s/^priv\///;
1.1032    raeburn  12657:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   12658:         $thisfn=~s/\?.+$//;
                   12659:     }
1.268     www      12660:     return $thisfn;
                   12661: }
                   12662: 
                   12663: # ------------------------------------------------------------- Clutter up URLs
                   12664: 
                   12665: sub clutter {
                   12666:     my $thisfn='/'.&declutter(shift);
1.887     albertel 12667:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 12668: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      12669:        $thisfn='/res'.$thisfn; 
                   12670:     }
1.1031    raeburn  12671:     if ($thisfn !~m|^/adm|) {
                   12672: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 12673: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 12674: 	} else {
                   12675: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   12676: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 12677: 	    if ($embstyle eq 'ssi'
                   12678: 		|| ($embstyle eq 'hdn')
                   12679: 		|| ($embstyle eq 'rat')
                   12680: 		|| ($embstyle eq 'prv')
                   12681: 		|| ($embstyle eq 'ign')) {
                   12682: 		#do nothing with these
                   12683: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 12684: 		|| ($embstyle eq 'emb')
                   12685: 		|| ($embstyle eq 'wrp')) {
                   12686: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 12687: 	    } elsif ($embstyle eq 'unk'
                   12688: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 12689: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 12690: 	    } else {
1.718     www      12691: #		&logthis("Got a blank emb style");
1.695     albertel 12692: 	    }
1.694     albertel 12693: 	}
                   12694:     }
1.31      www      12695:     return $thisfn;
1.12      www      12696: }
                   12697: 
1.787     albertel 12698: sub clutter_with_no_wrapper {
                   12699:     my $uri = &clutter(shift);
                   12700:     if ($uri =~ m-^/adm/-) {
                   12701: 	$uri =~ s-^/adm/wrapper/-/-;
                   12702: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   12703:     }
                   12704:     return $uri;
                   12705: }
                   12706: 
1.557     albertel 12707: sub freeze_escape {
                   12708:     my ($value)=@_;
                   12709:     if (ref($value)) {
                   12710: 	$value=&nfreeze($value);
                   12711: 	return '__FROZEN__'.&escape($value);
                   12712:     }
                   12713:     return &escape($value);
                   12714: }
                   12715: 
1.11      www      12716: 
1.557     albertel 12717: sub thaw_unescape {
                   12718:     my ($value)=@_;
                   12719:     if ($value =~ /^__FROZEN__/) {
                   12720: 	substr($value,0,10,undef);
                   12721: 	$value=&unescape($value);
                   12722: 	return &thaw($value);
                   12723:     }
                   12724:     return &unescape($value);
                   12725: }
                   12726: 
1.436     albertel 12727: sub correct_line_ends {
                   12728:     my ($result)=@_;
                   12729:     $$result =~s/\r\n/\n/mg;
                   12730:     $$result =~s/\r/\n/mg;
1.415     albertel 12731: }
1.1       albertel 12732: # ================================================================ Main Program
                   12733: 
1.184     www      12734: sub goodbye {
1.204     albertel 12735:    &logthis("Starting Shut down");
1.443     albertel 12736: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 12737:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 12738: #converted
1.599     albertel 12739: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 12740:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   12741: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   12742: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 12743: #1.1 only
1.870     albertel 12744: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   12745: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   12746: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   12747: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   12748:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 12749:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   12750:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      12751:    &flushcourselogs();
                   12752:    &logthis("Shutting down");
                   12753: }
                   12754: 
1.852     albertel 12755: sub get_dns {
1.1172.2.17  raeburn  12756:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 12757:     if (!$ignore_cache) {
                   12758: 	my ($content,$cached)=
                   12759: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   12760: 	if ($cached) {
1.1172.2.17  raeburn  12761: 	    &$func($content,$hashref);
1.869     albertel 12762: 	    return;
                   12763: 	}
                   12764:     }
                   12765: 
                   12766:     my %alldns;
1.1172.2.96  raeburn  12767:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   12768:         foreach my $dns (<$config>) {
                   12769: 	    next if ($dns !~ /^\^(\S*)/x);
                   12770:             my $line = $1;
                   12771:             my ($host,$protocol) = split(/:/,$line);
                   12772:             if ($protocol ne 'https') {
                   12773:                 $protocol = 'http';
                   12774:             }
                   12775: 	    $alldns{$host} = $protocol;
1.979     raeburn  12776:         }
1.1172.2.96  raeburn  12777:         close($config);
1.869     albertel 12778:     }
                   12779:     while (%alldns) {
1.1172.2.52  raeburn  12780: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 12781: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  12782:         $ua->timeout(30);
1.979     raeburn  12783: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 12784: 	my $response=$ua->request($request);
1.979     raeburn  12785:         delete($alldns{$dns});
1.852     albertel 12786: 	next if ($response->is_error());
                   12787: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  12788:         unless ($nocache) {
1.1172.2.23  raeburn  12789: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  12790:         }
                   12791: 	&$func(\@content,$hashref);
1.869     albertel 12792: 	return;
1.852     albertel 12793:     }
                   12794:     close($config);
1.871     albertel 12795:     my $which = (split('/',$url))[3];
                   12796:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.96  raeburn  12797:     open($config,"<","$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 12798:     my @content = <$config>;
1.1172.2.17  raeburn  12799:     &$func(\@content,$hashref);
                   12800:     return;
                   12801: }
                   12802: 
                   12803: # ------------------------------------------------------Get DNS checksums file
                   12804: sub parse_dns_checksums_tab {
                   12805:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  12806:     my $lonhost = $perlvar{'lonHostID'};
                   12807:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  12808:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  12809:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   12810:     my $webconfdir = '/etc/httpd/conf';
                   12811:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   12812:         $webconfdir = '/etc/apache2';
                   12813:     } elsif ($distro =~ /^sles(\d+)$/) {
                   12814:         if ($1 >= 10) {
                   12815:             $webconfdir = '/etc/apache2';
                   12816:         }
                   12817:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   12818:         if ($1 >= 10.0) {
                   12819:             $webconfdir = '/etc/apache2';
                   12820:         }
                   12821:     }
1.1172.2.17  raeburn  12822:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12823:     my (%chksum,%revnum);
                   12824:     if (ref($lines) eq 'ARRAY') {
                   12825:         chomp(@{$lines});
1.1172.2.34  raeburn  12826:         my $version = shift(@{$lines});
                   12827:         if ($version eq $release) {
1.1172.2.17  raeburn  12828:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  12829:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  12830:                 if ($file =~ m{^/etc/httpd/conf}) {
                   12831:                     if ($webconfdir eq '/etc/apache2') {
                   12832:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   12833:                     }
                   12834:                 }
1.1172.2.34  raeburn  12835:                 $chksum{$file} = $shasum;
                   12836:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  12837:             }
                   12838:             if (ref($hashref) eq 'HASH') {
                   12839:                 %{$hashref} = (
                   12840:                                 sums     => \%chksum,
                   12841:                                 versions => \%revnum,
                   12842:                               );
                   12843:             }
                   12844:         }
                   12845:     }
1.869     albertel 12846:     return;
1.852     albertel 12847: }
1.1172.2.17  raeburn  12848: 
                   12849: sub fetch_dns_checksums {
                   12850:     my %checksums;
1.1172.2.34  raeburn  12851:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  12852:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  12853:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12854:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  12855:              \%checksums);
                   12856:     return \%checksums;
                   12857: }
                   12858: 
1.327     albertel 12859: # ------------------------------------------------------------ Read domain file
                   12860: {
1.852     albertel 12861:     my $loaded;
1.846     albertel 12862:     my %domain;
                   12863: 
1.852     albertel 12864:     sub parse_domain_tab {
                   12865: 	my ($lines) = @_;
                   12866: 	foreach my $line (@$lines) {
                   12867: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      12868: 
1.846     albertel 12869: 	    chomp($line);
1.852     albertel 12870: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 12871: 	    my %this_domain;
                   12872: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   12873: 			       'lang_def', 'city', 'longi', 'lati',
                   12874: 			       'primary') {
                   12875: 		$this_domain{$field} = shift(@elements);
                   12876: 	    }
                   12877: 	    $domain{$name} = \%this_domain;
1.852     albertel 12878: 	}
                   12879:     }
1.864     albertel 12880: 
                   12881:     sub reset_domain_info {
                   12882: 	undef($loaded);
                   12883: 	undef(%domain);
                   12884:     }
                   12885: 
1.852     albertel 12886:     sub load_domain_tab {
1.1172.2.70  raeburn  12887: 	my ($ignore_cache,$nocache) = @_;
                   12888: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 12889: 	my $fh;
1.1172.2.96  raeburn  12890: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 12891: 	    my @lines = <$fh>;
                   12892: 	    &parse_domain_tab(\@lines);
1.448     albertel 12893: 	}
1.852     albertel 12894: 	close($fh);
                   12895: 	$loaded = 1;
1.327     albertel 12896:     }
1.846     albertel 12897: 
                   12898:     sub domain {
1.852     albertel 12899: 	&load_domain_tab() if (!$loaded);
                   12900: 
1.846     albertel 12901: 	my ($name,$what) = @_;
                   12902: 	return if ( !exists($domain{$name}) );
                   12903: 
                   12904: 	if (!$what) {
                   12905: 	    return $domain{$name}{'description'};
                   12906: 	}
                   12907: 	return $domain{$name}{$what};
                   12908:     }
1.974     raeburn  12909: 
                   12910:     sub domain_info {
                   12911:         &load_domain_tab() if (!$loaded);
                   12912:         return %domain;
                   12913:     }
                   12914: 
1.327     albertel 12915: }
                   12916: 
                   12917: 
1.1       albertel 12918: # ------------------------------------------------------------- Read hosts file
                   12919: {
1.838     albertel 12920:     my %hostname;
1.844     albertel 12921:     my %hostdom;
1.845     albertel 12922:     my %libserv;
1.852     albertel 12923:     my $loaded;
1.888     albertel 12924:     my %name_to_host;
1.1074    raeburn  12925:     my %internetdom;
1.1107    raeburn  12926:     my %LC_dns_serv;
1.852     albertel 12927: 
                   12928:     sub parse_hosts_tab {
                   12929: 	my ($file) = @_;
                   12930: 	foreach my $configline (@$file) {
                   12931: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  12932:             chomp($configline);
                   12933: 	    if ($configline =~ /^\^/) {
                   12934:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   12935:                     $LC_dns_serv{$1} = 1;
                   12936:                 }
                   12937:                 next;
                   12938:             }
1.1074    raeburn  12939: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 12940: 	    $name=~s/\s//g;
                   12941: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  12942:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   12943:                     my $curr = $hostname{$id};
                   12944:                     my $skip;
                   12945:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   12946:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   12947:                             $skip = 1;
                   12948:                         } else {
                   12949:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   12950:                         }
                   12951:                     }
                   12952:                     unless ($skip) {
                   12953:                         push(@{$name_to_host{$name}},$id);
                   12954:                     }
                   12955:                 } else {
                   12956:                     push(@{$name_to_host{$name}},$id);
                   12957:                 }
1.852     albertel 12958: 		$hostname{$id}=$name;
                   12959: 		$hostdom{$id}=$domain;
                   12960: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  12961:                 if (defined($protocol)) {
                   12962:                     if ($protocol eq 'https') {
                   12963:                         $protocol{$id} = $protocol;
                   12964:                     } else {
                   12965:                         $protocol{$id} = 'http'; 
                   12966:                     }
1.968     raeburn  12967:                 } else {
1.969     raeburn  12968:                     $protocol{$id} = 'http';
1.968     raeburn  12969:                 }
1.1074    raeburn  12970:                 if (defined($intdom)) {
                   12971:                     $internetdom{$id} = $intdom;
                   12972:                 }
1.852     albertel 12973: 	    }
                   12974: 	}
                   12975:     }
1.864     albertel 12976:     
                   12977:     sub reset_hosts_info {
1.897     albertel 12978: 	&purge_remembered();
1.864     albertel 12979: 	&reset_domain_info();
                   12980: 	&reset_hosts_ip_info();
1.892     albertel 12981: 	undef(%name_to_host);
1.864     albertel 12982: 	undef(%hostname);
                   12983: 	undef(%hostdom);
                   12984: 	undef(%libserv);
                   12985: 	undef($loaded);
                   12986:     }
1.1       albertel 12987: 
1.852     albertel 12988:     sub load_hosts_tab {
1.1172.2.70  raeburn  12989: 	my ($ignore_cache,$nocache) = @_;
                   12990: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  12991: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 12992: 	my @config = <$config>;
                   12993: 	&parse_hosts_tab(\@config);
                   12994: 	close($config);
                   12995: 	$loaded=1;
1.1       albertel 12996:     }
1.852     albertel 12997: 
1.838     albertel 12998:     sub hostname {
1.852     albertel 12999: 	&load_hosts_tab() if (!$loaded);
                   13000: 
1.838     albertel 13001: 	my ($lonid) = @_;
                   13002: 	return $hostname{$lonid};
                   13003:     }
1.845     albertel 13004: 
1.838     albertel 13005:     sub all_hostnames {
1.852     albertel 13006: 	&load_hosts_tab() if (!$loaded);
                   13007: 
1.838     albertel 13008: 	return %hostname;
                   13009:     }
1.845     albertel 13010: 
1.888     albertel 13011:     sub all_names {
1.1172.2.70  raeburn  13012:         my ($ignore_cache,$nocache) = @_;
                   13013: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13014: 
                   13015: 	return %name_to_host;
                   13016:     }
                   13017: 
1.974     raeburn  13018:     sub all_host_domain {
                   13019:         &load_hosts_tab() if (!$loaded);
                   13020:         return %hostdom;
                   13021:     }
                   13022: 
1.845     albertel 13023:     sub is_library {
1.852     albertel 13024: 	&load_hosts_tab() if (!$loaded);
                   13025: 
1.845     albertel 13026: 	return exists($libserv{$_[0]});
                   13027:     }
                   13028: 
                   13029:     sub all_library {
1.852     albertel 13030: 	&load_hosts_tab() if (!$loaded);
                   13031: 
1.845     albertel 13032: 	return %libserv;
                   13033:     }
                   13034: 
1.1062    droeschl 13035:     sub unique_library {
                   13036: 	#2x reverse removes all hostnames that appear more than once
                   13037:         my %unique = reverse &all_library();
                   13038:         return reverse %unique;
                   13039:     }
                   13040: 
1.841     albertel 13041:     sub get_servers {
1.852     albertel 13042: 	&load_hosts_tab() if (!$loaded);
                   13043: 
1.841     albertel 13044: 	my ($domain,$type) = @_;
                   13045: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13046: 	                                          : %hostname;
                   13047: 	my %result;
1.842     albertel 13048: 	if (ref($domain) eq 'ARRAY') {
                   13049: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13050: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13051: 		    $result{$host} = $hostname;
                   13052: 		}
                   13053: 	    }
                   13054: 	} else {
                   13055: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13056: 		if ($hostdom{$host} eq $domain) {
                   13057: 		    $result{$host} = $hostname;
                   13058: 		}
1.841     albertel 13059: 	    }
                   13060: 	}
                   13061: 	return %result;
                   13062:     }
1.845     albertel 13063: 
1.1062    droeschl 13064:     sub get_unique_servers {
                   13065:         my %unique = reverse &get_servers(@_);
                   13066: 	return reverse %unique;
                   13067:     }
                   13068: 
1.844     albertel 13069:     sub host_domain {
1.852     albertel 13070: 	&load_hosts_tab() if (!$loaded);
                   13071: 
1.844     albertel 13072: 	my ($lonid) = @_;
                   13073: 	return $hostdom{$lonid};
                   13074:     }
                   13075: 
1.841     albertel 13076:     sub all_domains {
1.852     albertel 13077: 	&load_hosts_tab() if (!$loaded);
                   13078: 
1.841     albertel 13079: 	my %seen;
                   13080: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13081: 	return @uniq;
                   13082:     }
1.1074    raeburn  13083: 
                   13084:     sub internet_dom {
                   13085:         &load_hosts_tab() if (!$loaded);
                   13086: 
                   13087:         my ($lonid) = @_;
                   13088:         return $internetdom{$lonid};
                   13089:     }
1.1107    raeburn  13090: 
                   13091:     sub is_LC_dns {
                   13092:         &load_hosts_tab() if (!$loaded);
                   13093: 
                   13094:         my ($hostname) = @_;
                   13095:         return exists($LC_dns_serv{$hostname});
                   13096:     }
                   13097: 
1.1       albertel 13098: }
                   13099: 
1.847     albertel 13100: { 
                   13101:     my %iphost;
1.856     albertel 13102:     my %name_to_ip;
                   13103:     my %lonid_to_ip;
1.869     albertel 13104: 
1.847     albertel 13105:     sub get_hosts_from_ip {
                   13106: 	my ($ip) = @_;
                   13107: 	my %iphosts = &get_iphost();
                   13108: 	if (ref($iphosts{$ip})) {
                   13109: 	    return @{$iphosts{$ip}};
                   13110: 	}
                   13111: 	return;
1.839     albertel 13112:     }
1.864     albertel 13113:     
                   13114:     sub reset_hosts_ip_info {
                   13115: 	undef(%iphost);
                   13116: 	undef(%name_to_ip);
                   13117: 	undef(%lonid_to_ip);
                   13118:     }
1.856     albertel 13119: 
                   13120:     sub get_host_ip {
                   13121: 	my ($lonid) = @_;
                   13122: 	if (exists($lonid_to_ip{$lonid})) {
                   13123: 	    return $lonid_to_ip{$lonid};
                   13124: 	}
                   13125: 	my $name=&hostname($lonid);
                   13126:    	my $ip = gethostbyname($name);
                   13127: 	return if (!$ip || length($ip) ne 4);
                   13128: 	$ip=inet_ntoa($ip);
                   13129: 	$name_to_ip{$name}   = $ip;
                   13130: 	$lonid_to_ip{$lonid} = $ip;
                   13131: 	return $ip;
                   13132:     }
1.847     albertel 13133:     
                   13134:     sub get_iphost {
1.1172.2.70  raeburn  13135: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13136: 
1.869     albertel 13137: 	if (!$ignore_cache) {
                   13138: 	    if (%iphost) {
                   13139: 		return %iphost;
                   13140: 	    }
                   13141: 	    my ($ip_info,$cached)=
                   13142: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13143: 	    if ($cached) {
                   13144: 		%iphost      = %{$ip_info->[0]};
                   13145: 		%name_to_ip  = %{$ip_info->[1]};
                   13146: 		%lonid_to_ip = %{$ip_info->[2]};
                   13147: 		return %iphost;
                   13148: 	    }
                   13149: 	}
1.894     albertel 13150: 
                   13151: 	# get yesterday's info for fallback
                   13152: 	my %old_name_to_ip;
                   13153: 	my ($ip_info,$cached)=
                   13154: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13155: 	if ($cached) {
                   13156: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13157: 	}
                   13158: 
1.1172.2.70  raeburn  13159: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13160: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13161: 	    my $ip;
                   13162: 	    if (!exists($name_to_ip{$name})) {
                   13163: 		$ip = gethostbyname($name);
                   13164: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13165: 		    if (defined($old_name_to_ip{$name})) {
                   13166: 			$ip = $old_name_to_ip{$name};
                   13167: 			&logthis("Can't find $name defaulting to old $ip");
                   13168: 		    } else {
                   13169: 			&logthis("Name $name no IP found");
                   13170: 			next;
                   13171: 		    }
                   13172: 		} else {
                   13173: 		    $ip=inet_ntoa($ip);
1.847     albertel 13174: 		}
                   13175: 		$name_to_ip{$name} = $ip;
                   13176: 	    } else {
                   13177: 		$ip = $name_to_ip{$name};
1.653     albertel 13178: 	    }
1.888     albertel 13179: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13180: 		$lonid_to_ip{$id} = $ip;
                   13181: 	    }
                   13182: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13183: 	}
1.1172.2.70  raeburn  13184:         unless ($nocache) {
                   13185: 	    &do_cache_new('iphost','iphost',
                   13186: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   13187: 		          48*60*60);
                   13188:         }
1.869     albertel 13189: 
1.847     albertel 13190: 	return %iphost;
1.598     albertel 13191:     }
                   13192: 
1.992     raeburn  13193:     #
                   13194:     #  Given a DNS returns the loncapa host name for that DNS 
                   13195:     # 
                   13196:     sub host_from_dns {
                   13197:         my ($dns) = @_;
                   13198:         my @hosts;
                   13199:         my $ip;
                   13200: 
1.993     raeburn  13201:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  13202:             $ip = $name_to_ip{$dns};
                   13203:         }
                   13204:         if (!$ip) {
                   13205:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   13206:             if (length($ip) == 4) { 
                   13207: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   13208:             }
                   13209:         }
                   13210:         if ($ip) {
                   13211: 	    @hosts = get_hosts_from_ip($ip);
                   13212: 	    return $hosts[0];
                   13213:         }
                   13214:         return undef;
1.986     foxr     13215:     }
1.992     raeburn  13216: 
1.1074    raeburn  13217:     sub get_internet_names {
                   13218:         my ($lonid) = @_;
                   13219:         return if ($lonid eq '');
                   13220:         my ($idnref,$cached)=
                   13221:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   13222:         if ($cached) {
                   13223:             return $idnref;
                   13224:         }
                   13225:         my $ip = &get_host_ip($lonid);
                   13226:         my @hosts = &get_hosts_from_ip($ip);
                   13227:         my %iphost = &get_iphost();
                   13228:         my (@idns,%seen);
                   13229:         foreach my $id (@hosts) {
                   13230:             my $dom = &host_domain($id);
                   13231:             my $prim_id = &domain($dom,'primary');
                   13232:             my $prim_ip = &get_host_ip($prim_id);
                   13233:             next if ($seen{$prim_ip});
                   13234:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   13235:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   13236:                     my $intdom = &internet_dom($id);
                   13237:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   13238:                         push(@idns,$intdom);
                   13239:                     }
                   13240:                 }
                   13241:             }
                   13242:             $seen{$prim_ip} = 1;
                   13243:         }
1.1172.2.23  raeburn  13244:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  13245:     }
                   13246: 
1.986     foxr     13247: }
                   13248: 
1.1079    raeburn  13249: sub all_loncaparevs {
1.1172.2.39  raeburn  13250:     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  13251: }
                   13252: 
1.1172.2.27  raeburn  13253: # ------------------------------------------------------- Read loncaparev table
                   13254: {
                   13255:     sub load_loncaparevs {
                   13256:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  13257:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  13258:                 while (my $configline=<$config>) {
                   13259:                     chomp($configline);
                   13260:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   13261:                     $loncaparevs{$hostid}=$loncaparev;
                   13262:                 }
                   13263:                 close($config);
                   13264:             }
                   13265:         }
                   13266:     }
                   13267: }
                   13268: 
                   13269: # ----------------------------------------------------- Read serverhostID table
                   13270: {
                   13271:     sub load_serverhomeIDs {
                   13272:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  13273:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  13274:                 while (my $configline=<$config>) {
                   13275:                     chomp($configline);
                   13276:                     my ($name,$id)=split(/:/,$configline);
                   13277:                     $serverhomeIDs{$name}=$id;
                   13278:                 }
                   13279:                 close($config);
                   13280:             }
                   13281:         }
                   13282:     }
                   13283: }
                   13284: 
                   13285: 
1.862     albertel 13286: BEGIN {
                   13287: 
                   13288: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   13289:     unless ($readit) {
                   13290: {
                   13291:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   13292:     %perlvar = (%perlvar,%{$configvars});
                   13293: }
                   13294: 
                   13295: 
1.1       albertel 13296: # ------------------------------------------------------ Read spare server file
                   13297: {
1.1172.2.96  raeburn  13298:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 13299: 
                   13300:     while (my $configline=<$config>) {
                   13301:        chomp($configline);
1.284     matthew  13302:        if ($configline) {
1.784     albertel 13303: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 13304: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 13305: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 13306:        }
                   13307:     }
1.448     albertel 13308:     close($config);
1.1       albertel 13309: }
1.11      www      13310: # ------------------------------------------------------------ Read permissions
                   13311: {
1.1172.2.96  raeburn  13312:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      13313: 
                   13314:     while (my $configline=<$config>) {
1.448     albertel 13315: 	chomp($configline);
                   13316: 	if ($configline) {
                   13317: 	    my ($role,$perm)=split(/ /,$configline);
                   13318: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   13319: 	}
1.11      www      13320:     }
1.448     albertel 13321:     close($config);
1.11      www      13322: }
                   13323: 
                   13324: # -------------------------------------------- Read plain texts for permissions
                   13325: {
1.1172.2.96  raeburn  13326:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      13327: 
                   13328:     while (my $configline=<$config>) {
1.448     albertel 13329: 	chomp($configline);
                   13330: 	if ($configline) {
1.742     raeburn  13331: 	    my ($short,@plain)=split(/:/,$configline);
                   13332:             %{$prp{$short}} = ();
                   13333: 	    if (@plain > 0) {
                   13334:                 $prp{$short}{'std'} = $plain[0];
                   13335:                 for (my $i=1; $i<@plain; $i++) {
                   13336:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   13337:                 }
                   13338:             }
1.448     albertel 13339: 	}
1.135     www      13340:     }
1.448     albertel 13341:     close($config);
1.135     www      13342: }
                   13343: 
                   13344: # ---------------------------------------------------------- Read package table
                   13345: {
1.1172.2.96  raeburn  13346:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      13347: 
                   13348:     while (my $configline=<$config>) {
1.483     albertel 13349: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 13350: 	chomp($configline);
                   13351: 	my ($short,$plain)=split(/:/,$configline);
                   13352: 	my ($pack,$name)=split(/\&/,$short);
                   13353: 	if ($plain ne '') {
                   13354: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   13355: 	    $packagetab{$short}=$plain; 
                   13356: 	}
1.11      www      13357:     }
1.448     albertel 13358:     close($config);
1.329     matthew  13359: }
                   13360: 
1.1172.2.27  raeburn  13361: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  13362: 
1.1172.2.27  raeburn  13363: &load_loncaparevs();
                   13364: 
                   13365: # ------------------------------------------------------- Read serverhostID table
                   13366: 
                   13367: &load_serverhomeIDs();
1.1074    raeburn  13368: 
1.1172.2.27  raeburn  13369: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  13370: {
                   13371:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   13372:     if (-e $file) {
                   13373:         my $parser = HTML::LCParser->new($file);
                   13374:         while (my $token = $parser->get_token()) {
                   13375:             if ($token->[0] eq 'S') {
                   13376:                 my $item = $token->[1];
                   13377:                 my $name = $token->[2]{'name'};
                   13378:                 my $value = $token->[2]{'value'};
                   13379:                 if ($item ne '' && $name ne '' && $value ne '') {
                   13380:                     my $release = $parser->get_text();
                   13381:                     $release =~ s/(^\s*|\s*$ )//gx;
                   13382:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   13383:                 }
                   13384:             }
                   13385:         }
                   13386:     }
1.1073    raeburn  13387: }
                   13388: 
1.1138    raeburn  13389: # ---------------------------------------------------------- Read managers table
                   13390: {
                   13391:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  13392:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  13393:             while (my $configline=<$config>) {
                   13394:                 chomp($configline);
                   13395:                 next if ($configline =~ /^\#/);
                   13396:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   13397:                     $managerstab{$configline} = 1;
                   13398:                 }
                   13399:             }
                   13400:             close($config);
                   13401:         }
                   13402:     }
                   13403: }
                   13404: 
1.329     matthew  13405: # ------------- set up temporary directory
                   13406: {
1.1117    foxr     13407:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  13408: 
1.11      www      13409: }
                   13410: 
1.794     albertel 13411: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   13412: 				'compress_threshold'=> 20_000,
                   13413:  			        });
1.185     www      13414: 
1.281     www      13415: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      13416: $dumpcount=0;
1.958     www      13417: $locknum=0;
1.22      www      13418: 
1.163     harris41 13419: &logtouch();
1.672     albertel 13420: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      13421: $readit=1;
1.564     albertel 13422:     {
                   13423: 	use integer;
                   13424: 	my $test=(2**32)+1;
1.568     albertel 13425: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 13426: 	&logthis(" Detected 64bit platform ($_64bit)");
                   13427:     }
1.195     www      13428: }
1.1       albertel 13429: }
1.179     www      13430: 
1.1       albertel 13431: 1;
1.191     harris41 13432: __END__
                   13433: 
1.243     albertel 13434: =pod
                   13435: 
1.191     harris41 13436: =head1 NAME
                   13437: 
1.243     albertel 13438: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 13439: 
                   13440: =head1 SYNOPSIS
                   13441: 
1.243     albertel 13442: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 13443: 
                   13444:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   13445: 
1.243     albertel 13446: Common parameters:
                   13447: 
                   13448: =over 4
                   13449: 
                   13450: =item *
                   13451: 
                   13452: $uname : an internal username (if $cname expecting a course Id specifically)
                   13453: 
                   13454: =item *
                   13455: 
                   13456: $udom : a domain (if $cdom expecting a course's domain specifically)
                   13457: 
                   13458: =item *
                   13459: 
                   13460: $symb : a resource instance identifier
                   13461: 
                   13462: =item *
                   13463: 
                   13464: $namespace : the name of a .db file that contains the data needed or
                   13465: being set.
                   13466: 
                   13467: =back
                   13468: 
1.394     bowersj2 13469: =head1 OVERVIEW
1.191     harris41 13470: 
1.394     bowersj2 13471: lonnet provides subroutines which interact with the
                   13472: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   13473: about classes, users, and resources.
1.243     albertel 13474: 
                   13475: For many of these objects you can also use this to store data about
                   13476: them or modify them in various ways.
1.191     harris41 13477: 
1.394     bowersj2 13478: =head2 Symbs
1.191     harris41 13479: 
1.394     bowersj2 13480: To identify a specific instance of a resource, LON-CAPA uses symbols
                   13481: or "symbs"X<symb>. These identifiers are built from the URL of the
                   13482: map, the resource number of the resource in the map, and the URL of
                   13483: the resource itself. The latter is somewhat redundant, but might help
                   13484: if maps change.
                   13485: 
                   13486: An example is
                   13487: 
                   13488:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   13489: 
                   13490: The respective map entry is
                   13491: 
                   13492:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   13493:   title="Problem 2">
                   13494:  </resource>
                   13495: 
                   13496: Symbs are used by the random number generator, as well as to store and
                   13497: restore data specific to a certain instance of for example a problem.
                   13498: 
                   13499: =head2 Storing And Retrieving Data
                   13500: 
                   13501: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   13502: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   13503: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   13504: is is the non-critical message twin of cstore. These functions are for
                   13505: handlers to store a perl hash to a user's permanent data space in an
                   13506: easy manner, and to retrieve it again on another call. It is expected
                   13507: that a handler would use this once at the beginning to retrieve data,
                   13508: and then again once at the end to send only the new data back.
                   13509: 
                   13510: The data is stored in the user's data directory on the user's
                   13511: homeserver under the ID of the course.
                   13512: 
                   13513: The hash that is returned by restore will have all of the previous
                   13514: value for all of the elements of the hash.
                   13515: 
                   13516: Example:
                   13517: 
                   13518:  #creating a hash
                   13519:  my %hash;
                   13520:  $hash{'foo'}='bar';
                   13521: 
                   13522:  #storing it
                   13523:  &Apache::lonnet::cstore(\%hash);
                   13524: 
                   13525:  #changing a value
                   13526:  $hash{'foo'}='notbar';
                   13527: 
                   13528:  #adding a new value
                   13529:  $hash{'bar'}='foo';
                   13530:  &Apache::lonnet::cstore(\%hash);
                   13531: 
                   13532:  #retrieving the hash
                   13533:  my %history=&Apache::lonnet::restore();
                   13534: 
                   13535:  #print the hash
                   13536:  foreach my $key (sort(keys(%history))) {
                   13537:    print("\%history{$key} = $history{$key}");
                   13538:  }
                   13539: 
                   13540: Will print out:
1.191     harris41 13541: 
1.394     bowersj2 13542:  %history{1:foo} = bar
                   13543:  %history{1:keys} = foo:timestamp
                   13544:  %history{1:timestamp} = 990455579
                   13545:  %history{2:bar} = foo
                   13546:  %history{2:foo} = notbar
                   13547:  %history{2:keys} = foo:bar:timestamp
                   13548:  %history{2:timestamp} = 990455580
                   13549:  %history{bar} = foo
                   13550:  %history{foo} = notbar
                   13551:  %history{timestamp} = 990455580
                   13552:  %history{version} = 2
                   13553: 
                   13554: Note that the special hash entries C<keys>, C<version> and
                   13555: C<timestamp> were added to the hash. C<version> will be equal to the
                   13556: total number of versions of the data that have been stored. The
                   13557: C<timestamp> attribute will be the UNIX time the hash was
                   13558: stored. C<keys> is available in every historical section to list which
                   13559: keys were added or changed at a specific historical revision of a
                   13560: hash.
                   13561: 
                   13562: B<Warning>: do not store the hash that restore returns directly. This
                   13563: will cause a mess since it will restore the historical keys as if the
                   13564: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 13565: 
1.394     bowersj2 13566: Calling convention:
1.191     harris41 13567: 
1.1172.2.27  raeburn  13568:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  13569:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 13570: 
1.394     bowersj2 13571: For more detailed information, see lonnet specific documentation.
1.191     harris41 13572: 
1.394     bowersj2 13573: =head1 RETURN MESSAGES
1.191     harris41 13574: 
1.394     bowersj2 13575: =over 4
1.191     harris41 13576: 
1.394     bowersj2 13577: =item * B<con_lost>: unable to contact remote host
1.191     harris41 13578: 
1.394     bowersj2 13579: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   13580: when the connection is brought back up
1.191     harris41 13581: 
1.394     bowersj2 13582: =item * B<con_failed>: unable to contact remote host and unable to save message
                   13583: for later delivery
1.191     harris41 13584: 
1.967     bisitz   13585: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 13586: 
1.394     bowersj2 13587: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 13588: that was requested
1.191     harris41 13589: 
1.243     albertel 13590: =back
1.191     harris41 13591: 
1.243     albertel 13592: =head1 PUBLIC SUBROUTINES
1.191     harris41 13593: 
1.243     albertel 13594: =head2 Session Environment Functions
1.191     harris41 13595: 
1.243     albertel 13596: =over 4
1.191     harris41 13597: 
1.394     bowersj2 13598: =item * 
                   13599: X<appenv()>
1.949     raeburn  13600: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 13601: the user envirnoment file, and will be restored for each access this
1.620     albertel 13602: user makes during this session, also modifies the %env for the current
1.949     raeburn  13603: process. Optional rolesarrayref - if defined contains a reference to an array
                   13604: of roles which are exempt from the restriction on modifying user.role entries 
                   13605: in the user's environment.db and in %env.    
1.191     harris41 13606: 
                   13607: =item *
1.394     bowersj2 13608: X<delenv()>
1.987     raeburn  13609: B<delenv($delthis,$regexp)>: removes all items from the session
                   13610: environment file that begin with $delthis. If the 
                   13611: optional second arg - $regexp - is true, $delthis is treated as a 
                   13612: regular expression, otherwise \Q$delthis\E is used. 
                   13613: The values are also deleted from the current processes %env.
1.191     harris41 13614: 
1.795     albertel 13615: =item * get_env_multiple($name) 
                   13616: 
                   13617: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   13618: values may be defined and end up as an array ref.
                   13619: 
                   13620: returns an array of values
                   13621: 
1.243     albertel 13622: =back
                   13623: 
                   13624: =head2 User Information
1.191     harris41 13625: 
1.243     albertel 13626: =over 4
1.191     harris41 13627: 
                   13628: =item *
1.394     bowersj2 13629: X<queryauthenticate()>
                   13630: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 13631: authentication scheme
                   13632: 
                   13633: =item *
1.394     bowersj2 13634: X<authenticate()>
1.1073    raeburn  13635: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 13636: authenticate user from domain's lib servers (first use the current
                   13637: one). C<$upass> should be the users password.
1.1073    raeburn  13638: $checkdefauth is optional (value is 1 if a check should be made to
                   13639:    authenticate user using default authentication method, and allow
                   13640:    account creation if username does not have account in the domain).
                   13641: $clientcancheckhost is optional (value is 1 if checking whether the
                   13642:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 13643: 
                   13644: =item *
1.394     bowersj2 13645: X<homeserver()>
                   13646: B<homeserver($uname,$udom)>: find the server which has
                   13647: the user's directory and files (there must be only one), this caches
                   13648: the answer, and also caches if there is a borken connection.
1.191     harris41 13649: 
                   13650: =item *
1.394     bowersj2 13651: X<idget()>
                   13652: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   13653: (IDs are a unique resource in a domain, there must be only 1 ID per
                   13654: username, and only 1 username per ID in a specific domain) (returns
                   13655: hash: id=>name,id=>name)
1.191     harris41 13656: 
                   13657: =item *
1.394     bowersj2 13658: X<idrget()>
                   13659: B<idrget($udom,@unames)>: find the IDs behind a list of
                   13660: usernames (returns hash: name=>id,name=>id)
1.191     harris41 13661: 
                   13662: =item *
1.394     bowersj2 13663: X<idput()>
                   13664: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 13665: 
                   13666: =item *
1.394     bowersj2 13667: X<rolesinit()>
1.1169    droeschl 13668: B<rolesinit($udom,$username)>: get user privileges.
                   13669: returns user role, first access and timer interval hashes
1.243     albertel 13670: 
                   13671: =item *
1.1171    droeschl 13672: X<privileged()>
                   13673: B<privileged($username,$domain)>: returns a true if user has a
                   13674: privileged and active role (i.e. su or dc), false otherwise.
                   13675: 
                   13676: =item *
1.551     albertel 13677: X<getsection()>
                   13678: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 13679: course $cname, return section name/number or '' for "not in course"
                   13680: and '-1' for "no section"
                   13681: 
                   13682: =item *
1.394     bowersj2 13683: X<userenvironment()>
                   13684: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 13685: passed in @what from the requested user's environment, returns a hash
                   13686: 
1.858     raeburn  13687: =item * 
                   13688: X<userlog_query()>
1.859     albertel 13689: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   13690: activity.log file. %filters defines filters applied when parsing the
                   13691: log file. These can be start or end timestamps, or the type of action
                   13692: - log to look for Login or Logout events, check for Checkin or
                   13693: Checkout, role for role selection. The response is in the form
                   13694: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   13695: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  13696: 
1.243     albertel 13697: =back
                   13698: 
                   13699: =head2 User Roles
                   13700: 
                   13701: =over 4
                   13702: 
                   13703: =item *
                   13704: 
1.1172.2.65  raeburn  13705: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   13706: returns codes for allowed actions.
                   13707: 
                   13708: The first argument is required, all others are optional.
                   13709: 
                   13710: $priv is the privilege being checked.
                   13711: $uri contains additional information about what is being checked for access (e.g.,
                   13712: URL, course ID etc.).
                   13713: $symb is the unique resource instance identifier in a course; if needed,
                   13714: but not provided, it will be retrieved via a call to &symbread().
                   13715: $role is the role for which a priv is being checked (only used if priv is evb).
                   13716: $clientip is the user's IP address (only used when checking for access to portfolio
                   13717: files).
                   13718: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   13719: prevents recursive calls to &allowed.
                   13720: 
1.243     albertel 13721:  F: full access
                   13722:  U,I,K: authentication modes (cxx only)
                   13723:  '': forbidden
                   13724:  1: user needs to choose course
                   13725:  2: browse allowed
1.766     albertel 13726:  A: passphrase authentication needed
1.1172.2.65  raeburn  13727:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 13728: 
                   13729: =item *
                   13730: 
1.1172.2.13  raeburn  13731: constructaccess($url,$setpriv) : check for access to construction space URL
                   13732: 
                   13733: See if the owner domain and name in the URL match those in the
                   13734: expected environment.  If so, return three element list
                   13735: ($ownername,$ownerdomain,$ownerhome).
                   13736: 
                   13737: Otherwise return the null string.
                   13738: 
                   13739: If second argument 'setpriv' is true, it assigns the privileges,
                   13740: and returns the same three element list, unless the owner has
                   13741: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   13742: in which case the null string is returned.
                   13743: 
                   13744: =item *
                   13745: 
1.1172.2.84  raeburn  13746: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   13747: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   13748: for system, domain, and course level. $uname and $udom are optional (current
                   13749: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 13750: 
                   13751: =item *
                   13752: 
1.988     raeburn  13753: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   13754: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  13755: $type is Course (default) or Community.
1.988     raeburn  13756: If $forcedefault evaluates to true, text returned will be default 
                   13757: text for $type. Otherwise, if this is a course, the text returned 
                   13758: will be a custom name for the role (if defined in the course's 
                   13759: environment).  If no custom name is defined the default is returned.
                   13760:    
1.832     raeburn  13761: =item *
                   13762: 
1.1172.2.23  raeburn  13763: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  13764: All arguments are optional. Returns a hash of a roles, either for
                   13765: co-author/assistant author roles for a user's Construction Space
1.906     albertel 13766: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  13767: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   13768: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   13769: For each key, value is set to colon-separated start and end times for
                   13770: the role.  If no username and domain are specified, will default to
1.934     raeburn  13771: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  13772: of role statuses (active, future or previous), roles 
                   13773: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   13774: to restrict the list of roles reported. If no array ref is 
                   13775: provided for types, will default to return only active roles.
1.834     albertel 13776: 
1.1172.2.13  raeburn  13777: =item *
                   13778: 
                   13779: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   13780: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   13781: 
                   13782: Additional optional arguments are: $type (if role checking is to be restricted
                   13783: to certain user status types -- previous (expired roles), active (currently
                   13784: available roles) or future (roles available in the future), and
                   13785: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  13786: have active Domain Coordinator role in course's domain or in additional
                   13787: domains (specified in 'Domains to check for privileged users' in course
                   13788: environment -- set via:  Course Settings -> Classlists and staff listing).
                   13789: 
                   13790: =item *
                   13791: 
                   13792: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   13793: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   13794: $possdomains and $possroles are optional array refs -- to domains to check and
                   13795: roles to check.  If $possdomains is not specified, a dump will be done of the
                   13796: users' roles.db to check for a dc or su role in any domain. This can be
                   13797: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   13798: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   13799: this then allows &privileged_by_domain() to be used, which caches the identity
                   13800: of privileged users, eliminating the need for repeated calls to &dump().
                   13801: 
                   13802: =item *
                   13803: 
                   13804: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   13805: where the outer hash keys are domains specified in the $possdomains array ref,
                   13806: next inner hash keys are privileged roles specified in the $roles array ref,
                   13807: and the innermost hash contains key = value pairs for username:domain = end:start
                   13808: for active or future "privileged" users with that role in that domain. To avoid
                   13809: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   13810: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  13811: 
1.243     albertel 13812: =back
                   13813: 
                   13814: =head2 User Modification
                   13815: 
                   13816: =over 4
                   13817: 
                   13818: =item *
                   13819: 
1.957     raeburn  13820: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 13821: user for the level given by URL.  Optional start and end dates (leave empty
                   13822: string or zero for "no date")
1.191     harris41 13823: 
                   13824: =item *
                   13825: 
1.243     albertel 13826: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   13827: change a users, password, possible return values are: ok,
                   13828: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   13829: refused
1.191     harris41 13830: 
                   13831: =item *
                   13832: 
1.243     albertel 13833: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 13834: 
                   13835: =item *
                   13836: 
1.1058    raeburn  13837: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   13838:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   13839: 
                   13840: will update user information (firstname,middlename,lastname,generation,
                   13841: permanentemail), and if forceid is true, student/employee ID also.
                   13842: A user's institutional affiliation(s) can also be updated.
                   13843: User information fields will not be overwritten with empty entries 
                   13844: unless the field is included in the $candelete array reference.
                   13845: This array is included when a single user is modified via "Manage Users",
                   13846: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 13847: 
                   13848: =item *
                   13849: 
1.286     matthew  13850: modifystudent
                   13851: 
1.957     raeburn  13852: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  13853: The course id is resolved based on the current user's environment.  
                   13854: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  13855: associated with a course.
                   13856: 
1.297     matthew  13857: This call is essentially a wrapper for lonnet::modifyuser and
                   13858: lonnet::modify_student_enrollment
1.286     matthew  13859: 
                   13860: Inputs: 
                   13861: 
                   13862: =over 4
                   13863: 
1.957     raeburn  13864: =item B<$udom> Student's loncapa domain
1.286     matthew  13865: 
1.957     raeburn  13866: =item B<$uname> Student's loncapa login name
1.286     matthew  13867: 
1.964     bisitz   13868: =item B<$uid> Student/Employee ID
1.286     matthew  13869: 
1.957     raeburn  13870: =item B<$umode> Student's authentication mode
1.286     matthew  13871: 
1.957     raeburn  13872: =item B<$upass> Student's password
1.286     matthew  13873: 
1.957     raeburn  13874: =item B<$first> Student's first name
1.286     matthew  13875: 
1.957     raeburn  13876: =item B<$middle> Student's middle name
1.286     matthew  13877: 
1.957     raeburn  13878: =item B<$last> Student's last name
1.286     matthew  13879: 
1.957     raeburn  13880: =item B<$gene> Student's generation
1.286     matthew  13881: 
1.957     raeburn  13882: =item B<$usec> Student's section in course
1.286     matthew  13883: 
                   13884: =item B<$end> Unix time of the roles expiration
                   13885: 
                   13886: =item B<$start> Unix time of the roles start date
                   13887: 
                   13888: =item B<$forceid> If defined, allow $uid to be changed
                   13889: 
                   13890: =item B<$desiredhome> server to use as home server for student
                   13891: 
1.957     raeburn  13892: =item B<$email> Student's permanent e-mail address
                   13893: 
                   13894: =item B<$type> Type of enrollment (auto or manual)
                   13895: 
1.963     raeburn  13896: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   13897: 
                   13898: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  13899: 
1.963     raeburn  13900: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  13901: 
1.963     raeburn  13902: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  13903: 
1.1172.2.19  raeburn  13904: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   13905: 
                   13906: =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  13907: 
1.286     matthew  13908: =back
1.297     matthew  13909: 
                   13910: =item *
                   13911: 
                   13912: modify_student_enrollment
                   13913: 
1.1172.2.31  raeburn  13914: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  13915: 'role.request.course' must be defined for this function to proceed.
                   13916: 
                   13917: Inputs:
                   13918: 
                   13919: =over 4
                   13920: 
1.1172.2.31  raeburn  13921: =item $udom, student's domain
1.297     matthew  13922: 
1.1172.2.31  raeburn  13923: =item $uname, student's name
1.297     matthew  13924: 
1.1172.2.31  raeburn  13925: =item $uid, student's user id
1.297     matthew  13926: 
1.1172.2.31  raeburn  13927: =item $first, student's first name
1.297     matthew  13928: 
                   13929: =item $middle
                   13930: 
                   13931: =item $last
                   13932: 
                   13933: =item $gene
                   13934: 
                   13935: =item $usec
                   13936: 
                   13937: =item $end
                   13938: 
                   13939: =item $start
                   13940: 
1.957     raeburn  13941: =item $type
                   13942: 
                   13943: =item $locktype
                   13944: 
                   13945: =item $cid
                   13946: 
                   13947: =item $selfenroll
                   13948: 
                   13949: =item $context
                   13950: 
1.1172.2.19  raeburn  13951: =item $credits, number of credits student will earn from this class
                   13952: 
1.1172.2.76  raeburn  13953: =item $instsec, institutional course section code for student
                   13954: 
1.297     matthew  13955: =back
                   13956: 
1.191     harris41 13957: 
                   13958: =item *
                   13959: 
1.243     albertel 13960: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   13961: custom role; give a custom role to a user for the level given by URL.  Specify
                   13962: name and domain of role author, and role name
1.191     harris41 13963: 
                   13964: =item *
                   13965: 
1.243     albertel 13966: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 13967: 
                   13968: =item *
                   13969: 
1.243     albertel 13970: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   13971: 
                   13972: =back
                   13973: 
                   13974: =head2 Course Infomation
                   13975: 
                   13976: =over 4
1.191     harris41 13977: 
                   13978: =item *
                   13979: 
1.1118    foxr     13980: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 13981: specified course id, including all environment settings for the
                   13982: course, the description of the course will be in the hash under the
                   13983: key 'description'
1.191     harris41 13984: 
1.1118    foxr     13985: $options is an optional parameter that if supplied is a hash reference that controls
                   13986: what how this function works.  It has the following key/values:
                   13987: 
                   13988: =over 4
                   13989: 
                   13990: =item freshen_cache
                   13991: 
                   13992: If defined, and the environment cache for the course is valid, it is 
                   13993: returned in the returned hash.
                   13994: 
                   13995: =item one_time
                   13996: 
                   13997: If defined, the last cache time is set to _now_
                   13998: 
                   13999: =item user
                   14000: 
                   14001: If defined, the supplied username is used instead of the current user.
                   14002: 
                   14003: 
                   14004: =back
                   14005: 
1.191     harris41 14006: =item *
                   14007: 
1.624     albertel 14008: resdata($name,$domain,$type,@which) : request for current parameter
                   14009: setting for a specific $type, where $type is either 'course' or 'user',
                   14010: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  14011: answers for 10 minutes.
1.243     albertel 14012: 
1.877     foxr     14013: =item *
                   14014: 
                   14015: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14016: data base, returning a hash that is keyed by the resource name and has
                   14017: values that are the resource value.  I believe that the timestamps and
                   14018: versions are also returned.
                   14019: 
1.1172.2.31  raeburn  14020: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14021: supplemental content area. This routine caches the number of files for
                   14022: 10 minutes.
                   14023: 
1.243     albertel 14024: =back
                   14025: 
                   14026: =head2 Course Modification
                   14027: 
                   14028: =over 4
1.191     harris41 14029: 
                   14030: =item *
                   14031: 
1.243     albertel 14032: writecoursepref($courseid,%prefs) : write preferences (environment
                   14033: database) for a course
1.191     harris41 14034: 
                   14035: =item *
                   14036: 
1.1011    raeburn  14037: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14038: 
                   14039: =item *
                   14040: 
1.1038    raeburn  14041: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14042: 
1.1167    droeschl 14043: =item *
                   14044: 
                   14045: is_course($courseid), is_course($cdom, $cnum)
                   14046: 
                   14047: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14048: two component version $cdom, $cnum. It checks if the specified course exists.
                   14049: 
                   14050: Returns:
                   14051:     undef if the course doesn't exist, otherwise
                   14052:     in scalar context the combined courseid.
                   14053:     in list context the two components of the course identifier, domain and 
                   14054:     courseid.    
                   14055: 
1.243     albertel 14056: =back
                   14057: 
                   14058: =head2 Resource Subroutines
                   14059: 
                   14060: =over 4
1.191     harris41 14061: 
                   14062: =item *
                   14063: 
1.243     albertel 14064: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 14065: 
                   14066: =item *
                   14067: 
1.243     albertel 14068: repcopy($filename) : subscribes to the requested file, and attempts to
                   14069: replicate from the owning library server, Might return
1.607     raeburn  14070: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   14071: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 14072: resource. Expects the local filesystem pathname
                   14073: (/home/httpd/html/res/....)
                   14074: 
                   14075: =back
                   14076: 
                   14077: =head2 Resource Information
                   14078: 
                   14079: =over 4
1.191     harris41 14080: 
                   14081: =item *
                   14082: 
1.1172.2.28  raeburn  14083: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   14084: and returns the value of a variety of different possible values,
                   14085: $varname should be a request string, and the other parameters can be
                   14086: used to specify who and what one is asking about. Ordinarily, $cid 
                   14087: does not need to be specified, as it is retrived from 
                   14088: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14089: within lonuserstate::loadmap() when initializing a course, before
                   14090: $env{'request.course.id'} has been set, so it needs to be provided
                   14091: in that one case.
1.243     albertel 14092: 
                   14093: Possible values for $varname are environment.lastname (or other item
                   14094: from the envirnment hash), user.name (or someother aspect about the
                   14095: user), resource.0.maxtries (or some other part and parameter of a
                   14096: resource)
1.204     albertel 14097: 
                   14098: =item *
                   14099: 
1.243     albertel 14100: directcondval($number) : get current value of a condition; reads from a state
                   14101: string
1.204     albertel 14102: 
                   14103: =item *
                   14104: 
1.243     albertel 14105: condval($condidx) : value of condition index based on state
1.204     albertel 14106: 
                   14107: =item *
                   14108: 
1.243     albertel 14109: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   14110: resource's metadata, $what should be either a specific key, or either
                   14111: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   14112: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   14113: 
                   14114: this function automatically caches all requests
1.191     harris41 14115: 
                   14116: =item *
                   14117: 
1.243     albertel 14118: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   14119: network of library servers; returns file handle of where SQL and regex results
                   14120: will be stored for query
1.191     harris41 14121: 
                   14122: =item *
                   14123: 
1.1172.2.66  raeburn  14124: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   14125: return symbolic list entry (all arguments optional).
                   14126: 
                   14127: Args: filename is the filename (including path) for the file for which a symb
                   14128: is required; donotrecurse, if true will prevent calls to allowed() being made
                   14129: to check access status if more than one resource was found in the bighash
                   14130: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   14131: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   14132: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   14133: cause possible symbs to be checked to determine if they are subject to content
                   14134: blocking, if so they will not be included as possible symbs; possibles is a
                   14135: ref to a hash, which, as a side effect, will be populated with all possible
                   14136: symbs (content blocking not tested).
                   14137: 
1.243     albertel 14138: returns the data handle
1.191     harris41 14139: 
                   14140: =item *
                   14141: 
1.1172.2.17  raeburn  14142: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  14143: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 14144: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  14145: on failure, user must be in a course, as it assumes the existence of
                   14146: the course initial hash, and uses $env('request.course.id'}.  The third
                   14147: arg is an optional reference to a scalar.  If this arg is passed in the
                   14148: call to symbverify, it will be set to 1 if the symb has been set to be 
                   14149: encrypted; otherwise it will be null.
1.243     albertel 14150: 
1.191     harris41 14151: =item *
                   14152: 
1.243     albertel 14153: symbclean($symb) : removes versions numbers from a symb, returns the
                   14154: cleaned symb
1.191     harris41 14155: 
                   14156: =item *
                   14157: 
1.243     albertel 14158: is_on_map($uri) : checks if the $uri is somewhere on the current
                   14159: course map, user must be in a course for it to work.
1.191     harris41 14160: 
                   14161: =item *
                   14162: 
1.243     albertel 14163: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 14164: 
                   14165: =item *
                   14166: 
1.243     albertel 14167: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   14168: a random seed, all arguments are optional, if they aren't sent it uses the
                   14169: environment to derive them. Note: if symb isn't sent and it can't get one
                   14170: from &symbread it will use the current time as its return value
1.191     harris41 14171: 
                   14172: =item *
                   14173: 
1.243     albertel 14174: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   14175: unfakeable, receipt
1.191     harris41 14176: 
                   14177: =item *
                   14178: 
1.620     albertel 14179: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 14180: 
                   14181: =item *
                   14182: 
1.243     albertel 14183: countacc($url) : count the number of accesses to a given URL
1.191     harris41 14184: 
                   14185: =item *
                   14186: 
1.243     albertel 14187: 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 14188: 
                   14189: =item *
                   14190: 
1.243     albertel 14191: 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 14192: 
                   14193: =item *
                   14194: 
1.243     albertel 14195: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 14196: 
                   14197: =item *
                   14198: 
1.243     albertel 14199: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   14200: forcing spreadsheet to reevaluate the resource scores next time.
                   14201: 
1.1172.2.13  raeburn  14202: =item *
                   14203: 
                   14204: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   14205: when viewing in course context.
                   14206: 
                   14207:  input: six args -- filename (decluttered), course number, course domain,
                   14208:                     url, symb (if registered) and group (if this is a
                   14209:                     group item -- e.g., bulletin board, group page etc.).
                   14210: 
                   14211:  output: array of five scalars --
                   14212:          $cfile -- url for file editing if editable on current server
                   14213:          $home -- homeserver of resource (i.e., for author if published,
                   14214:                                           or course if uploaded.).
                   14215:          $switchserver --  1 if server switch will be needed.
                   14216:          $forceedit -- 1 if icon/link should be to go to edit mode
                   14217:          $forceview -- 1 if icon/link should be to go to view mode
                   14218: 
                   14219: =item *
                   14220: 
                   14221: is_course_upload($file,$cnum,$cdom)
                   14222: 
                   14223: Used in course context to determine if current file was uploaded to
                   14224: the course (i.e., would be found in /userfiles/docs on the course's
                   14225: homeserver.
                   14226: 
                   14227:   input: 3 args -- filename (decluttered), course number and course domain.
                   14228:   output: boolean -- 1 if file was uploaded.
                   14229: 
1.243     albertel 14230: =back
                   14231: 
                   14232: =head2 Storing/Retreiving Data
                   14233: 
                   14234: =over 4
1.191     harris41 14235: 
                   14236: =item *
                   14237: 
1.1172.2.64  raeburn  14238: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   14239: permanently for this url; hashref needs to be given and should be a \%hashname;
                   14240: the remaining args aren't required and if they aren't passed or are '' they will
                   14241: be derived from the env (with the exception of $laststore, which is an
                   14242: optional arg used when a user's submission is stored in grading).
                   14243: $laststore is $version=$timestamp, where $version is the most recent version
                   14244: number retrieved for the corresponding $symb in the $namespace db file, and
                   14245: $timestamp is the timestamp for that transaction (UNIX time).
                   14246: $laststore is currently only passed when cstore() is called by
                   14247: structuretags::finalize_storage().
1.191     harris41 14248: 
                   14249: =item *
                   14250: 
1.1172.2.64  raeburn  14251: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   14252: but uses critical subroutine
1.191     harris41 14253: 
                   14254: =item *
                   14255: 
1.243     albertel 14256: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   14257: all args are optional
1.191     harris41 14258: 
                   14259: =item *
                   14260: 
1.717     albertel 14261: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   14262: dumps the complete (or key matching regexp) namespace into a hash
                   14263: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   14264: normally &store()ed into
                   14265: 
                   14266: $range should be either an integer '100' (give me the first 100
                   14267:                                            matching records)
                   14268:               or be  two integers sperated by a - with no spaces
                   14269:                  '30-50' (give me the 30th through the 50th matching
                   14270:                           records)
                   14271: 
                   14272: 
                   14273: =item *
                   14274: 
1.1172.2.59  raeburn  14275: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 14276: replaces a &store() version of data with a replacement set of data
                   14277: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  14278: reference. If $tolog is true, the transaction is logged in the courselog
                   14279: with an action=PUTSTORE.
1.717     albertel 14280: 
                   14281: =item *
                   14282: 
1.243     albertel 14283: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   14284: works very similar to store/cstore, but all data is stored in a
                   14285: temporary location and can be reset using tmpreset, $storehash should
                   14286: be a hash reference, returns nothing on success
1.191     harris41 14287: 
                   14288: =item *
                   14289: 
1.243     albertel 14290: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   14291: similar to restore, but all data is stored in a temporary location and
                   14292: can be reset using tmpreset. Returns a hash of values on success,
                   14293: error string otherwise.
1.191     harris41 14294: 
                   14295: =item *
                   14296: 
1.243     albertel 14297: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   14298: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 14299: 
                   14300: =item *
                   14301: 
1.243     albertel 14302: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14303: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 14304: 
                   14305: =item *
                   14306: 
1.243     albertel 14307: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   14308: namesp ($udom and $uname are optional)
1.191     harris41 14309: 
                   14310: =item *
                   14311: 
1.702     albertel 14312: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 14313: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 14314: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  14315: 
1.702     albertel 14316: $range should be either an integer '100' (give me the first 100
                   14317:                                            matching records)
                   14318:               or be  two integers sperated by a - with no spaces
                   14319:                  '30-50' (give me the 30th through the 50th matching
                   14320:                           records)
1.449     matthew  14321: =item *
                   14322: 
                   14323: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   14324: $store can be a scalar, an array reference, or if the amount to be 
                   14325: incremented is > 1, a hash reference.
                   14326: 
                   14327: ($udom and $uname are optional)
1.191     harris41 14328: 
                   14329: =item *
                   14330: 
1.243     albertel 14331: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   14332: ($udom and $uname are optional)
1.191     harris41 14333: 
                   14334: =item *
                   14335: 
1.243     albertel 14336: cput($namespace,$storehash,$udom,$uname) : critical put
                   14337: ($udom and $uname are optional)
1.191     harris41 14338: 
                   14339: =item *
                   14340: 
1.748     albertel 14341: newput($namespace,$storehash,$udom,$uname) :
                   14342: 
                   14343: Attempts to store the items in the $storehash, but only if they don't
                   14344: currently exist, if this succeeds you can be certain that you have 
                   14345: successfully created a new key value pair in the $namespace db.
                   14346: 
                   14347: 
                   14348: Args:
                   14349:  $namespace: name of database to store values to
                   14350:  $storehash: hashref to store to the db
                   14351:  $udom: (optional) domain of user containing the db
                   14352:  $uname: (optional) name of user caontaining the db
                   14353: 
                   14354: Returns:
                   14355:  'ok' -> succeeded in storing all keys of $storehash
                   14356:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   14357:                         least <key> already existed in the db (other
                   14358:                         requested keys may also already exist)
1.967     bisitz   14359:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 14360:  'con_lost' -> unable to contact request server
                   14361:  'refused' -> action was not allowed by remote machine
                   14362: 
                   14363: 
                   14364: =item *
                   14365: 
1.243     albertel 14366: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14367: reference filled in from namesp (encrypts the return communication)
                   14368: ($udom and $uname are optional)
1.191     harris41 14369: 
                   14370: =item *
                   14371: 
1.243     albertel 14372: log($udom,$name,$home,$message) : write to permanent log for user; use
                   14373: critical subroutine
                   14374: 
1.806     raeburn  14375: =item *
                   14376: 
1.860     raeburn  14377: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   14378: array reference filled in from namespace found in domain level on either
                   14379: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  14380: 
                   14381: =item *
                   14382: 
1.860     raeburn  14383: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   14384: domain level either on specified domain server ($uhome) or primary domain 
                   14385: server ($udom and $uhome are optional)
1.806     raeburn  14386: 
1.943     raeburn  14387: =item * 
                   14388: 
1.1172.2.35  raeburn  14389: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   14390: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   14391: the target domain.
                   14392: 
                   14393: May also include additional key => value pairs for the following groups:
                   14394: 
                   14395: =over
                   14396: 
                   14397: =item
                   14398: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   14399: 
                   14400: =over
                   14401: 
                   14402: =item defaultquota, authorquota
                   14403: 
                   14404: =back
                   14405: 
                   14406: =item
                   14407: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   14408: portfolio for users).
                   14409: 
                   14410: =over
                   14411: 
                   14412: =item
                   14413: aboutme, blog, webdav, portfolio
                   14414: 
                   14415: =back
                   14416: 
                   14417: =item
                   14418: requestcourses: ability to request courses, and how requests are processed.
                   14419: 
                   14420: =over
                   14421: 
                   14422: =item
1.1172.2.37  raeburn  14423: official, unofficial, community, textbook
1.1172.2.35  raeburn  14424: 
                   14425: =back
                   14426: 
                   14427: =item
                   14428: inststatus: types of institutional affiliation, and order in which they are displayed.
                   14429: 
                   14430: =over
                   14431: 
                   14432: =item
1.1172.2.44  raeburn  14433: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  14434: 
                   14435: =back
                   14436: 
                   14437: =item
                   14438: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   14439: for course's uploaded content.
                   14440: 
                   14441: =over
                   14442: 
                   14443: =item
1.1172.2.68  raeburn  14444: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   14445: communityquota, textbookquota
1.1172.2.35  raeburn  14446: 
                   14447: =back
                   14448: 
                   14449: =item
                   14450: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   14451: on your servers.
                   14452: 
                   14453: =over
                   14454: 
                   14455: =item
                   14456: remotesessions, hostedsessions
                   14457: 
                   14458: =back
                   14459: 
                   14460: =back
                   14461: 
                   14462: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   14463: utility to create a configuration.db file on a domain's primary library server
                   14464: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   14465: -- corresponding values are authentication type (internal, krb4, krb5,
                   14466: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   14467: will be available. Values are retrieved from cache (if current), unless the
                   14468: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   14469: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   14470: 
                   14471: Typical usage:
1.943     raeburn  14472: 
1.1172.2.35  raeburn  14473: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  14474: 
1.243     albertel 14475: =back
                   14476: 
                   14477: =head2 Network Status Functions
                   14478: 
                   14479: =over 4
1.191     harris41 14480: 
                   14481: =item *
                   14482: 
1.1137    raeburn  14483: dirlist() : return directory list based on URI (first arg).
                   14484: 
                   14485: Inputs: 1 required, 5 optional.
                   14486: 
                   14487: =over
                   14488: 
                   14489: =item 
                   14490: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   14491: 
                   14492: =item
                   14493: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   14494: 
                   14495: =item
                   14496: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   14497: 
                   14498: =item
                   14499: $getpropath - boolean: 1 if prepend path using &propath(). 
                   14500: 
                   14501: =item
                   14502: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   14503: 
                   14504: =item 
                   14505: $alternateRoot - path to prepend in place of path from $uri.
                   14506: 
                   14507: =back
                   14508: 
                   14509: Returns: Array of up to two items.
                   14510: 
                   14511: =over
                   14512: 
                   14513: a reference to an array of files/subdirectories
                   14514: 
                   14515: =over
                   14516: 
                   14517: Each element in the array of files/subdirectories is a & separated list of
                   14518: item name and the result of running stat on the item.  If dirlist was requested
                   14519: for a file instead of a directory, the item name will be ''. For a directory 
                   14520: listing, if the item is a metadata file, the element will end &N&M 
                   14521: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   14522: default copyright set (1).  
                   14523: 
                   14524: =back
                   14525: 
                   14526: a scalar containing error condition (if encountered).
                   14527: 
                   14528: =over
                   14529: 
                   14530: =item 
                   14531: no_host (no homeserver identified for $username:$domain).
                   14532: 
                   14533: =item 
                   14534: no_such_host (server contacted for listing not identified as valid host).
                   14535: 
                   14536: =item 
                   14537: con_lost (connection to remote server failed).
                   14538: 
                   14539: =item 
                   14540: refused (invalid $username:$domain received on lond side).
                   14541: 
                   14542: =item 
                   14543: no_such_dir (directory at specified path on lond side does not exist). 
                   14544: 
                   14545: =item 
                   14546: empty (directory at specified path on lond side is empty).
                   14547: 
                   14548: =over
                   14549: 
                   14550: This is currently not encountered because the &ls3, &ls2, 
                   14551: &ls (_handler) routines on the lond side do not filter out
                   14552: . and .. from a directory listing. 
                   14553: 
                   14554: =back
                   14555: 
                   14556: =back
                   14557: 
                   14558: =back
1.191     harris41 14559: 
                   14560: =item *
                   14561: 
1.243     albertel 14562: spareserver() : find server with least workload from spare.tab
                   14563: 
1.986     foxr     14564: 
                   14565: =item *
                   14566: 
                   14567: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   14568: if there is no corresponding loncapa host.
                   14569: 
1.243     albertel 14570: =back
                   14571: 
1.986     foxr     14572: 
1.243     albertel 14573: =head2 Apache Request
                   14574: 
                   14575: =over 4
1.191     harris41 14576: 
                   14577: =item *
                   14578: 
1.243     albertel 14579: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   14580: localhost, posts hash
                   14581: 
                   14582: =back
                   14583: 
                   14584: =head2 Data to String to Data
                   14585: 
                   14586: =over 4
1.191     harris41 14587: 
                   14588: =item *
                   14589: 
1.243     albertel 14590: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   14591: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 14592: 
                   14593: =item *
                   14594: 
1.243     albertel 14595: hashref2str($hashref) : convert a hashref into a string complete with
                   14596: escaping and '=' and '&' separators, supports elements that are
                   14597: arrayrefs and hashrefs
1.191     harris41 14598: 
                   14599: =item *
                   14600: 
1.243     albertel 14601: arrayref2str($arrayref) : convert an arrayref into a string complete
                   14602: with escaping and '&' separators, supports elements that are arrayrefs
                   14603: and hashrefs
1.191     harris41 14604: 
                   14605: =item *
                   14606: 
1.243     albertel 14607: str2hash($string) : convert string to hash using unescaping and
                   14608: splitting on '=' and '&', supports elements that are arrayrefs and
                   14609: hashrefs
1.191     harris41 14610: 
                   14611: =item *
                   14612: 
1.243     albertel 14613: str2array($string) : convert string to hash using unescaping and
                   14614: splitting on '&', supports elements that are arrayrefs and hashrefs
                   14615: 
                   14616: =back
                   14617: 
                   14618: =head2 Logging Routines
                   14619: 
                   14620: 
                   14621: These routines allow one to make log messages in the lonnet.log and
                   14622: lonnet.perm logfiles.
1.191     harris41 14623: 
1.1119    foxr     14624: =over 4
                   14625: 
1.191     harris41 14626: =item *
                   14627: 
1.243     albertel 14628: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 14629: 
                   14630: =item *
                   14631: 
1.243     albertel 14632: logthis() : append message to the normal lonnet.log file, it gets
                   14633: preiodically rolled over and deleted.
1.191     harris41 14634: 
                   14635: =item *
                   14636: 
1.243     albertel 14637: logperm() : append a permanent message to lonnet.perm.log, this log
                   14638: file never gets deleted by any automated portion of the system, only
                   14639: messages of critical importance should go in here.
                   14640: 
1.1119    foxr     14641: 
1.243     albertel 14642: =back
                   14643: 
                   14644: =head2 General File Helper Routines
                   14645: 
                   14646: =over 4
1.191     harris41 14647: 
                   14648: =item *
                   14649: 
1.481     raeburn  14650: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   14651: (a) files in /uploaded
                   14652:   (i) If a local copy of the file exists - 
                   14653:       compares modification date of local copy with last-modified date for 
                   14654:       definitive version stored on home server for course. If local copy is 
                   14655:       stale, requests a new version from the home server and stores it. 
                   14656:       If the original has been removed from the home server, then local copy 
                   14657:       is unlinked.
                   14658:   (ii) If local copy does not exist -
                   14659:       requests the file from the home server and stores it. 
                   14660:   
                   14661:   If $caller is 'uploadrep':  
                   14662:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   14663:     for request for files originally uploaded via DOCS. 
                   14664:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   14665:   
                   14666:   Otherwise:
                   14667:      This indicates a call from the content generation phase of the request.
                   14668:      -  returns the entire contents of the file or -1.
                   14669:      
                   14670: (b) files in /res
                   14671:    - returns the entire contents of a file or -1; 
                   14672:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 14673: 
1.712     albertel 14674: 
                   14675: =item *
                   14676: 
                   14677: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   14678:                   reference
                   14679: 
                   14680: returns either a stat() list of data about the file or an empty list
                   14681: if the file doesn't exist or couldn't find out about it (connection
                   14682: problems or user unknown)
                   14683: 
1.191     harris41 14684: =item *
                   14685: 
1.243     albertel 14686: filelocation($dir,$file) : returns file system location of a file
                   14687: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   14688: directory that relative $file lookups are to looked in ($dir of /a/dir
                   14689: and a file of ../bob will become /a/bob)
1.191     harris41 14690: 
                   14691: =item *
                   14692: 
                   14693: hreflocation($dir,$file) : returns file system location or a URL; same as
                   14694: filelocation except for hrefs
                   14695: 
                   14696: =item *
                   14697: 
1.1172.2.49  raeburn  14698: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   14699: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 14700: 
1.243     albertel 14701: =back
                   14702: 
1.608     albertel 14703: =head2 Usererfile file routines (/uploaded*)
                   14704: 
                   14705: =over 4
                   14706: 
                   14707: =item *
                   14708: 
                   14709: userfileupload(): main rotine for putting a file in a user or course's
                   14710:                   filespace, arguments are,
                   14711: 
1.620     albertel 14712:  formname - required - this is the name of the element in $env where the
1.608     albertel 14713:            filename, and the contents of the file to create/modifed exist
1.620     albertel 14714:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   14715:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  14716:  context - if coursedoc, store the file in the course of the active role
                   14717:              of the current user; 
                   14718:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   14719:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 14720:  subdir - required - subdirectory to put the file in under ../userfiles/
                   14721:          if undefined, it will be placed in "unknown"
                   14722: 
                   14723:  (This routine calls clean_filename() to remove any dangerous
                   14724:  characters from the filename, and then calls finuserfileupload() to
                   14725:  complete the transaction)
                   14726: 
                   14727:  returns either the url of the uploaded file (/uploaded/....) if successful
                   14728:  and /adm/notfound.html if unsuccessful
                   14729: 
                   14730: =item *
                   14731: 
                   14732: clean_filename(): routine for cleaing a filename up for storage in
                   14733:                  userfile space, argument is:
                   14734: 
                   14735:  filename - proposed filename
                   14736: 
                   14737: returns: the new clean filename
                   14738: 
                   14739: =item *
                   14740: 
1.1090    raeburn  14741: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 14742: userspace, probably shouldn't be called directly
                   14743: 
                   14744:   docuname: username or courseid of destination for the file
                   14745:   docudom: domain of user/course of destination for the file
                   14746:   formname: same as for userfileupload()
1.1090    raeburn  14747:   fname: filename (including subdirectories) for the file
                   14748:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   14749:   allfiles: reference to hash used to store objects found by parser
                   14750:   codebase: reference to hash used for codebases of java objects found by parser
                   14751:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   14752:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   14753:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   14754:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   14755:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   14756:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  14757:   mimetype: reference to scalar to accommodate mime type determined
                   14758:             from File::MMagic if $parser = parse.
1.608     albertel 14759: 
                   14760:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  14761:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   14762:  was 'overwrite').
                   14763:  
1.608     albertel 14764: 
                   14765: =item *
                   14766: 
                   14767: renameuserfile(): renames an existing userfile to a new name
                   14768: 
                   14769:   Args:
                   14770:    docuname: username or courseid of destination for the file
                   14771:    docudom: domain of user/course of destination for the file
                   14772:    old: current file name (including any subdirs under userfiles)
                   14773:    new: desired file name (including any subdirs under userfiles)
                   14774: 
                   14775: =item *
                   14776: 
                   14777: mkdiruserfile(): creates a directory is a userfiles dir
                   14778: 
                   14779:   Args:
                   14780:    docuname: username or courseid of destination for the file
                   14781:    docudom: domain of user/course of destination for the file
                   14782:    dir: dir to create (including any subdirs under userfiles)
                   14783: 
                   14784: =item *
                   14785: 
                   14786: removeuserfile(): removes a file that exists in userfiles
                   14787: 
                   14788:   Args:
                   14789:    docuname: username or courseid of destination for the file
                   14790:    docudom: domain of user/course of destination for the file
                   14791:    fname: filname to delete (including any subdirs under userfiles)
                   14792: 
                   14793: =item *
                   14794: 
                   14795: removeuploadedurl(): convience function for removeuserfile()
                   14796: 
                   14797:   Args:
                   14798:    url:  a full /uploaded/... url to delete
                   14799: 
1.747     albertel 14800: =item * 
                   14801: 
                   14802: get_portfile_permissions():
                   14803:   Args:
                   14804:     domain: domain of user or course contain the portfolio files
                   14805:     user: name of user or num of course contain the portfolio files
                   14806:   Returns:
                   14807:     hashref of a dump of the proper file_permissions.db
                   14808:    
                   14809: 
                   14810: =item * 
                   14811: 
                   14812: get_access_controls():
                   14813: 
                   14814: Args:
                   14815:   current_permissions: the hash ref returned from get_portfile_permissions()
                   14816:   group: (optional) the group you want the files associated with
                   14817:   file: (optional) the file you want access info on
                   14818: 
                   14819: Returns:
1.749     raeburn  14820:     a hash (keys are file names) of hashes containing
                   14821:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   14822:         values are XML containing access control settings (see below) 
1.747     albertel 14823: 
                   14824: Internal notes:
                   14825: 
1.749     raeburn  14826:  access controls are stored in file_permissions.db as key=value pairs.
                   14827:     key -> path to file/file_name\0uniqueID:scope_end_start
                   14828:         where scope -> public,guest,course,group,domains or users.
                   14829:               end -> UNIX time for end of access (0 -> no end date)
                   14830:               start -> UNIX time for start of access
                   14831: 
                   14832:     value -> XML description of access control
                   14833:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   14834:             <start></start>
                   14835:             <end></end>
                   14836: 
                   14837:             <password></password>  for scope type = guest
                   14838: 
                   14839:             <domain></domain>     for scope type = course or group
                   14840:             <number></number>
                   14841:             <roles id="">
                   14842:              <role></role>
                   14843:              <access></access>
                   14844:              <section></section>
                   14845:              <group></group>
                   14846:             </roles>
                   14847: 
                   14848:             <dom></dom>         for scope type = domains
                   14849: 
                   14850:             <users>             for scope type = users
                   14851:              <user>
                   14852:               <uname></uname>
                   14853:               <udom></udom>
                   14854:              </user>
                   14855:             </users>
                   14856:            </scope> 
                   14857:               
                   14858:  Access data is also aggregated for each file in an additional key=value pair:
                   14859:  key -> path to file/file_name\0accesscontrol 
                   14860:  value -> reference to hash
                   14861:           hash contains key = value pairs
                   14862:           where key = uniqueID:scope_end_start
                   14863:                 value = UNIX time record was last updated
                   14864: 
                   14865:           Used to improve speed of look-ups of access controls for each file.  
                   14866:  
                   14867:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   14868: 
1.1172.2.13  raeburn  14869: =item *
                   14870: 
1.749     raeburn  14871: modify_access_controls():
                   14872: 
                   14873: Modifies access controls for a portfolio file
                   14874: Args
                   14875: 1. file name
                   14876: 2. reference to hash of required changes,
                   14877: 3. domain
                   14878: 4. username
                   14879:   where domain,username are the domain of the portfolio owner 
                   14880:   (either a user or a course) 
                   14881: 
                   14882: Returns:
                   14883: 1. result of additions or updates ('ok' or 'error', with error message). 
                   14884: 2. result of deletions ('ok' or 'error', with error message).
                   14885: 3. reference to hash of any new or updated access controls.
                   14886: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   14887:    key = integer (inbound ID)
1.1172.2.13  raeburn  14888:    value = uniqueID
                   14889: 
                   14890: =item *
                   14891: 
                   14892: get_timebased_id():
                   14893: 
                   14894: Attempts to get a unique timestamp-based suffix for use with items added to a
                   14895: course via the Course Editor (e.g., folders, composite pages,
                   14896: group bulletin boards).
                   14897: 
                   14898: Args: (first three required; six others optional)
                   14899: 
                   14900: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   14901:    docssequence, or name of group
                   14902: 
                   14903: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   14904:    e.g., num, boardids
                   14905: 
                   14906: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   14907:    file will be named nohist_namespace.db
                   14908: 
                   14909: 4. cdom: domain of course; default is current course domain from %env
                   14910: 
                   14911: 5. cnum: course number; default is current course number from %env
                   14912: 
                   14913: 6. idtype: set to concat if an additional digit is to be appended to the
                   14914:    unix timestamp to form the suffix, if the plain timestamp is already
                   14915:    in use.  Default is to not do this, but simply increment the unix
                   14916:    timestamp by 1 until a unique key is obtained.
                   14917: 
                   14918: 7. who: holder of locking key; defaults to user:domain for user.
                   14919: 
                   14920: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   14921:    retrying); default is 3.
                   14922: 
                   14923: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   14924: 
                   14925: Returns:
                   14926: 
                   14927: 1. suffix obtained (numeric)
                   14928: 
                   14929: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   14930: 
                   14931: 3. error: contains (localized) error message if an error occurred.
                   14932: 
1.747     albertel 14933: 
1.608     albertel 14934: =back
                   14935: 
1.243     albertel 14936: =head2 HTTP Helper Routines
                   14937: 
                   14938: =over 4
                   14939: 
1.191     harris41 14940: =item *
                   14941: 
                   14942: escape() : unpack non-word characters into CGI-compatible hex codes
                   14943: 
                   14944: =item *
                   14945: 
                   14946: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   14947: 
1.243     albertel 14948: =back
                   14949: 
                   14950: =head1 PRIVATE SUBROUTINES
                   14951: 
                   14952: =head2 Underlying communication routines (Shouldn't call)
                   14953: 
                   14954: =over 4
                   14955: 
                   14956: =item *
                   14957: 
                   14958: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   14959: 
                   14960: =item *
                   14961: 
                   14962: reply() : uses subreply to send a message to remote machine, logs all failures
                   14963: 
                   14964: =item *
                   14965: 
                   14966: critical() : passes a critical message to another server; if cannot
                   14967: get through then place message in connection buffer directory and
                   14968: returns con_delayed, if incapable of saving message, returns
                   14969: con_failed
                   14970: 
                   14971: =item *
                   14972: 
                   14973: reconlonc() : tries to reconnect lonc client processes.
                   14974: 
                   14975: =back
                   14976: 
                   14977: =head2 Resource Access Logging
                   14978: 
                   14979: =over 4
                   14980: 
                   14981: =item *
                   14982: 
                   14983: flushcourselogs() : flush (save) buffer logs and access logs
                   14984: 
                   14985: =item *
                   14986: 
                   14987: courselog($what) : save message for course in hash
                   14988: 
                   14989: =item *
                   14990: 
                   14991: courseacclog($what) : save message for course using &courselog().  Perform
                   14992: special processing for specific resource types (problems, exams, quizzes, etc).
                   14993: 
1.191     harris41 14994: =item *
                   14995: 
                   14996: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   14997: as a PerlChildExitHandler
1.243     albertel 14998: 
                   14999: =back
                   15000: 
                   15001: =head2 Other
                   15002: 
                   15003: =over 4
                   15004: 
                   15005: =item *
                   15006: 
                   15007: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15008: 
                   15009: =back
                   15010: 
                   15011: =cut
1.877     foxr     15012: 

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