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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.102! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.101 2018/09/22 03:11:40 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.1172.2.102! raeburn  4896:     if ($firstaccess) {
        !          4897:         &logthis("First access time already set ($firstaccess) when attempting ".
        !          4898:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
        !          4899:                  "in $courseid");
        !          4900:         return 'already_set';
        !          4901:     } else {
1.1162    raeburn  4902:         my $start = time;
                   4903: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4904:                           $udom,$uname);
                   4905:         if ($putres eq 'ok') {
                   4906:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4907:                  $udom,$uname); 
                   4908:             &appenv(
                   4909:                      {
                   4910:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4911:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4912:                      }
                   4913:                   );
1.1172.2.97  raeburn  4914:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   4915:                 $cachedtimes{"$courseid\0$res"} = $start;
                   4916:             }
1.1172.2.102! raeburn  4917:         } elsif ($putres ne 'refused') {
        !          4918:             &logthis("Result: $putres when attempting to set first access time ".
        !          4919:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  4920:         }
                   4921:         return $putres;
1.505     albertel 4922:     }
                   4923:     return 'already_set';
1.504     albertel 4924: }
1.1153    www      4925: }
1.1172.2.32  raeburn  4926: 
                   4927: sub checkout {
                   4928:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   4929:     my $now=time;
                   4930:     my $lonhost=$perlvar{'lonHostID'};
                   4931:     my $infostr=&escape(
                   4932:                  'CHECKOUTTOKEN&'.
                   4933:                  $tuname.'&'.
                   4934:                  $tudom.'&'.
                   4935:                  $tcrsid.'&'.
                   4936:                  $symb.'&'.
                   4937:                  $now.'&'.$ENV{'REMOTE_ADDR'});
                   4938:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   4939:     if ($token=~/^error\:/) {
                   4940:         &logthis("<font color=\"blue\">WARNING: ".
                   4941:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4942:                  "</font>");
                   4943:         return '';
                   4944:     }
                   4945: 
                   4946:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   4947:     $token=~tr/a-z/A-Z/;
                   4948: 
                   4949:     my %infohash=('resource.0.outtoken' => $token,
                   4950:                   'resource.0.checkouttime' => $now,
                   4951:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
                   4952: 
                   4953:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   4954:        return '';
                   4955:     } else {
                   4956:         &logthis("<font color=\"blue\">WARNING: ".
                   4957:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4958:                  "</font>");
                   4959:     }
                   4960: 
                   4961:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   4962:                          &escape('Checkout '.$infostr.' - '.
                   4963:                                                  $token)) ne 'ok') {
                   4964:         return '';
                   4965:     } else {
                   4966:         &logthis("<font color=\"blue\">WARNING: ".
                   4967:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4968:                  "</font>");
                   4969:     }
                   4970:     return $token;
                   4971: }
                   4972: 
                   4973: # ------------------------------------------------------------ Check in an item
                   4974: 
                   4975: sub checkin {
                   4976:     my $token=shift;
                   4977:     my $now=time;
                   4978:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   4979:     $lonhost=~tr/A-Z/a-z/;
                   4980:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   4981:     $dtoken=~s/\W/\_/g;
                   4982:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   4983:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   4984: 
                   4985:     unless (($tuname) && ($tudom)) {
                   4986:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   4987:         return '';
                   4988:     }
                   4989: 
                   4990:     unless (&allowed('mgr',$tcrsid)) {
                   4991:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   4992:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   4993:         return '';
                   4994:     }
                   4995: 
                   4996:     my %infohash=('resource.0.intoken' => $token,
                   4997:                   'resource.0.checkintime' => $now,
                   4998:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
                   4999: 
                   5000:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5001:        return '';
                   5002:     }
                   5003: 
                   5004:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5005:                          &escape('Checkin - '.$token)) ne 'ok') {
                   5006:         return '';
                   5007:     }
                   5008: 
                   5009:     return ($symb,$tuname,$tudom,$tcrsid);
                   5010: }
                   5011: 
1.110     www      5012: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5013: 
                   5014: sub expirespread {
                   5015:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5016:     my $cid=$env{'request.course.id'}; 
1.110     www      5017:     if ($cid) {
                   5018:        my $now=time;
                   5019:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5020:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5021:                             $env{'course.'.$cid.'.num'}.
1.110     www      5022: 	        	    ':nohist_expirationdates:'.
                   5023:                             &escape($key).'='.$now,
1.620     albertel 5024:                             $env{'course.'.$cid.'.home'})
1.110     www      5025:     }
                   5026:     return 'ok';
1.14      www      5027: }
                   5028: 
1.109     www      5029: # ----------------------------------------------------- Devalidate Spreadsheets
                   5030: 
                   5031: sub devalidate {
1.325     www      5032:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5033:     my $cid=$env{'request.course.id'}; 
1.109     www      5034:     if ($cid) {
1.391     matthew  5035:         # delete the stored spreadsheets for
                   5036:         # - the student level sheet of this user in course's homespace
                   5037:         # - the assessment level sheet for this resource 
                   5038:         #   for this user in user's homespace
1.553     albertel 5039: 	# - current conditional state info
1.325     www      5040: 	my $key=$uname.':'.$udom.':';
1.109     www      5041:         my $status=
1.299     matthew  5042: 	    &del('nohist_calculatedsheets',
1.391     matthew  5043: 		 [$key.'studentcalc:'],
1.620     albertel 5044: 		 $env{'course.'.$cid.'.domain'},
                   5045: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5046: 		.' '.
                   5047: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5048: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5049:         unless ($status eq 'ok ok') {
                   5050:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5051:                     $uname.' at '.$udom.' for '.
1.109     www      5052: 		    $symb.': '.$status);
1.133     albertel 5053:         }
1.553     albertel 5054: 	&delenv('user.state.'.$cid);
1.109     www      5055:     }
                   5056: }
                   5057: 
1.265     albertel 5058: sub get_scalar {
                   5059:     my ($string,$end) = @_;
                   5060:     my $value;
                   5061:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5062: 	$value = $1;
                   5063:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5064: 	$value = $1;
                   5065:     }
                   5066:     return &unescape($value);
                   5067: }
                   5068: 
                   5069: sub array2str {
                   5070:   my (@array) = @_;
                   5071:   my $result=&arrayref2str(\@array);
                   5072:   $result=~s/^__ARRAY_REF__//;
                   5073:   $result=~s/__END_ARRAY_REF__$//;
                   5074:   return $result;
                   5075: }
                   5076: 
1.204     albertel 5077: sub arrayref2str {
                   5078:   my ($arrayref) = @_;
1.265     albertel 5079:   my $result='__ARRAY_REF__';
1.204     albertel 5080:   foreach my $elem (@$arrayref) {
1.265     albertel 5081:     if(ref($elem) eq 'ARRAY') {
                   5082:       $result.=&arrayref2str($elem).'&';
                   5083:     } elsif(ref($elem) eq 'HASH') {
                   5084:       $result.=&hashref2str($elem).'&';
                   5085:     } elsif(ref($elem)) {
                   5086:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5087:     } else {
                   5088:       $result.=&escape($elem).'&';
                   5089:     }
                   5090:   }
                   5091:   $result=~s/\&$//;
1.265     albertel 5092:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5093:   return $result;
                   5094: }
                   5095: 
1.168     albertel 5096: sub hash2str {
1.204     albertel 5097:   my (%hash) = @_;
                   5098:   my $result=&hashref2str(\%hash);
1.265     albertel 5099:   $result=~s/^__HASH_REF__//;
                   5100:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5101:   return $result;
                   5102: }
                   5103: 
                   5104: sub hashref2str {
                   5105:   my ($hashref)=@_;
1.265     albertel 5106:   my $result='__HASH_REF__';
1.800     albertel 5107:   foreach my $key (sort(keys(%$hashref))) {
                   5108:     if (ref($key) eq 'ARRAY') {
                   5109:       $result.=&arrayref2str($key).'=';
                   5110:     } elsif (ref($key) eq 'HASH') {
                   5111:       $result.=&hashref2str($key).'=';
                   5112:     } elsif (ref($key)) {
1.265     albertel 5113:       $result.='=';
1.800     albertel 5114:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5115:     } else {
1.1132    raeburn  5116: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5117:     }
                   5118: 
1.800     albertel 5119:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5120:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5121:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5122:       $result.=&hashref2str($hashref->{$key}).'&';
                   5123:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5124:        $result.='&';
1.800     albertel 5125:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5126:     } else {
1.800     albertel 5127:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5128:     }
                   5129:   }
1.168     albertel 5130:   $result=~s/\&$//;
1.265     albertel 5131:   $result .= '__END_HASH_REF__';
1.168     albertel 5132:   return $result;
                   5133: }
                   5134: 
                   5135: sub str2hash {
1.265     albertel 5136:     my ($string)=@_;
                   5137:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5138:     return %$hash;
                   5139: }
                   5140: 
                   5141: sub str2hashref {
1.168     albertel 5142:   my ($string) = @_;
1.265     albertel 5143: 
                   5144:   my %hash;
                   5145: 
                   5146:   if($string !~ /^__HASH_REF__/) {
                   5147:       if (! ($string eq '' || !defined($string))) {
                   5148: 	  $hash{'error'}='Not hash reference';
                   5149:       }
                   5150:       return (\%hash, $string);
                   5151:   }
                   5152: 
                   5153:   $string =~ s/^__HASH_REF__//;
                   5154: 
                   5155:   while($string !~ /^__END_HASH_REF__/) {
                   5156:       #key
                   5157:       my $key='';
                   5158:       if($string =~ /^__HASH_REF__/) {
                   5159:           ($key, $string)=&str2hashref($string);
                   5160:           if(defined($key->{'error'})) {
                   5161:               $hash{'error'}='Bad data';
                   5162:               return (\%hash, $string);
                   5163:           }
                   5164:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5165:           ($key, $string)=&str2arrayref($string);
                   5166:           if($key->[0] eq 'Array reference error') {
                   5167:               $hash{'error'}='Bad data';
                   5168:               return (\%hash, $string);
                   5169:           }
                   5170:       } else {
                   5171:           $string =~ s/^(.*?)=//;
1.267     albertel 5172: 	  $key=&unescape($1);
1.265     albertel 5173:       }
                   5174:       $string =~ s/^=//;
                   5175: 
                   5176:       #value
                   5177:       my $value='';
                   5178:       if($string =~ /^__HASH_REF__/) {
                   5179:           ($value, $string)=&str2hashref($string);
                   5180:           if(defined($value->{'error'})) {
                   5181:               $hash{'error'}='Bad data';
                   5182:               return (\%hash, $string);
                   5183:           }
                   5184:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5185:           ($value, $string)=&str2arrayref($string);
                   5186:           if($value->[0] eq 'Array reference error') {
                   5187:               $hash{'error'}='Bad data';
                   5188:               return (\%hash, $string);
                   5189:           }
                   5190:       } else {
                   5191: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5192:       }
                   5193:       $string =~ s/^&//;
                   5194: 
                   5195:       $hash{$key}=$value;
1.204     albertel 5196:   }
1.265     albertel 5197: 
                   5198:   $string =~ s/^__END_HASH_REF__//;
                   5199: 
                   5200:   return (\%hash, $string);
1.204     albertel 5201: }
                   5202: 
                   5203: sub str2array {
1.265     albertel 5204:     my ($string)=@_;
                   5205:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5206:     return @$array;
                   5207: }
                   5208: 
                   5209: sub str2arrayref {
1.204     albertel 5210:   my ($string) = @_;
1.265     albertel 5211:   my @array;
                   5212: 
                   5213:   if($string !~ /^__ARRAY_REF__/) {
                   5214:       if (! ($string eq '' || !defined($string))) {
                   5215: 	  $array[0]='Array reference error';
                   5216:       }
                   5217:       return (\@array, $string);
                   5218:   }
                   5219: 
                   5220:   $string =~ s/^__ARRAY_REF__//;
                   5221: 
                   5222:   while($string !~ /^__END_ARRAY_REF__/) {
                   5223:       my $value='';
                   5224:       if($string =~ /^__HASH_REF__/) {
                   5225:           ($value, $string)=&str2hashref($string);
                   5226:           if(defined($value->{'error'})) {
                   5227:               $array[0] ='Array reference error';
                   5228:               return (\@array, $string);
                   5229:           }
                   5230:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5231:           ($value, $string)=&str2arrayref($string);
                   5232:           if($value->[0] eq 'Array reference error') {
                   5233:               $array[0] ='Array reference error';
                   5234:               return (\@array, $string);
                   5235:           }
                   5236:       } else {
                   5237: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5238:       }
                   5239:       $string =~ s/^&//;
                   5240: 
                   5241:       push(@array, $value);
1.191     harris41 5242:   }
1.265     albertel 5243: 
                   5244:   $string =~ s/^__END_ARRAY_REF__//;
                   5245: 
                   5246:   return (\@array, $string);
1.168     albertel 5247: }
                   5248: 
1.167     albertel 5249: # -------------------------------------------------------------------Temp Store
                   5250: 
1.168     albertel 5251: sub tmpreset {
                   5252:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5253:   if (!$symb) {
                   5254:     $symb=&symbread();
1.620     albertel 5255:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5256:   }
                   5257:   $symb=escape($symb);
                   5258: 
1.620     albertel 5259:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5260:   $namespace=~s/\//\_/g;
                   5261:   $namespace=~s/\W//g;
                   5262: 
1.620     albertel 5263:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5264:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5265:   if ($domain eq 'public' && $stuname eq 'public') {
                   5266:       $stuname=$ENV{'REMOTE_ADDR'};
                   5267:   }
1.1117    foxr     5268:   my $path=LONCAPA::tempdir();
1.168     albertel 5269:   my %hash;
                   5270:   if (tie(%hash,'GDBM_File',
                   5271: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5272: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5273:     foreach my $key (keys(%hash)) {
1.180     albertel 5274:       if ($key=~ /:$symb/) {
1.168     albertel 5275: 	delete($hash{$key});
                   5276:       }
                   5277:     }
                   5278:   }
                   5279: }
                   5280: 
1.167     albertel 5281: sub tmpstore {
1.168     albertel 5282:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5283: 
                   5284:   if (!$symb) {
                   5285:     $symb=&symbread();
1.620     albertel 5286:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5287:   }
                   5288:   $symb=escape($symb);
                   5289: 
                   5290:   if (!$namespace) {
                   5291:     # I don't think we would ever want to store this for a course.
                   5292:     # it seems this will only be used if we don't have a course.
1.620     albertel 5293:     #$namespace=$env{'request.course.id'};
1.168     albertel 5294:     #if (!$namespace) {
1.620     albertel 5295:       $namespace=$env{'request.state'};
1.168     albertel 5296:     #}
                   5297:   }
                   5298:   $namespace=~s/\//\_/g;
                   5299:   $namespace=~s/\W//g;
1.620     albertel 5300:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5301:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5302:   if ($domain eq 'public' && $stuname eq 'public') {
                   5303:       $stuname=$ENV{'REMOTE_ADDR'};
                   5304:   }
1.168     albertel 5305:   my $now=time;
                   5306:   my %hash;
1.1117    foxr     5307:   my $path=LONCAPA::tempdir();
1.168     albertel 5308:   if (tie(%hash,'GDBM_File',
                   5309: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5310: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5311:     $hash{"version:$symb"}++;
                   5312:     my $version=$hash{"version:$symb"};
                   5313:     my $allkeys=''; 
                   5314:     foreach my $key (keys(%$storehash)) {
                   5315:       $allkeys.=$key.':';
1.591     albertel 5316:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5317:     }
                   5318:     $hash{"$version:$symb:timestamp"}=$now;
                   5319:     $allkeys.='timestamp';
                   5320:     $hash{"$version:keys:$symb"}=$allkeys;
                   5321:     if (untie(%hash)) {
                   5322:       return 'ok';
                   5323:     } else {
                   5324:       return "error:$!";
                   5325:     }
                   5326:   } else {
                   5327:     return "error:$!";
                   5328:   }
                   5329: }
1.167     albertel 5330: 
1.168     albertel 5331: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5332: 
1.168     albertel 5333: sub tmprestore {
                   5334:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5335: 
1.168     albertel 5336:   if (!$symb) {
                   5337:     $symb=&symbread();
1.620     albertel 5338:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5339:   }
                   5340:   $symb=escape($symb);
                   5341: 
1.620     albertel 5342:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5343: 
1.620     albertel 5344:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5345:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5346:   if ($domain eq 'public' && $stuname eq 'public') {
                   5347:       $stuname=$ENV{'REMOTE_ADDR'};
                   5348:   }
1.168     albertel 5349:   my %returnhash;
                   5350:   $namespace=~s/\//\_/g;
                   5351:   $namespace=~s/\W//g;
                   5352:   my %hash;
1.1117    foxr     5353:   my $path=LONCAPA::tempdir();
1.168     albertel 5354:   if (tie(%hash,'GDBM_File',
                   5355: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5356: 	  &GDBM_READER(),0640)) {
1.168     albertel 5357:     my $version=$hash{"version:$symb"};
                   5358:     $returnhash{'version'}=$version;
                   5359:     my $scope;
                   5360:     for ($scope=1;$scope<=$version;$scope++) {
                   5361:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5362:       my @keys=split(/:/,$vkeys);
                   5363:       my $key;
                   5364:       $returnhash{"$scope:keys"}=$vkeys;
                   5365:       foreach $key (@keys) {
1.591     albertel 5366: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5367: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5368:       }
                   5369:     }
1.168     albertel 5370:     if (!(untie(%hash))) {
                   5371:       return "error:$!";
                   5372:     }
                   5373:   } else {
                   5374:     return "error:$!";
                   5375:   }
                   5376:   return %returnhash;
1.167     albertel 5377: }
                   5378: 
1.9       www      5379: # ----------------------------------------------------------------------- Store
                   5380: 
                   5381: sub store {
1.1172.2.64  raeburn  5382:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5383:     my $home='';
                   5384: 
1.168     albertel 5385:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5386: 
1.213     www      5387:     $symb=&symbclean($symb);
1.122     albertel 5388:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5389: 
1.620     albertel 5390:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5391:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5392: 
                   5393:     &devalidate($symb,$stuname,$domain);
1.109     www      5394: 
                   5395:     $symb=escape($symb);
1.187     www      5396:     if (!$namespace) { 
1.620     albertel 5397:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5398:           return ''; 
                   5399:        } 
                   5400:     }
1.620     albertel 5401:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5402: 
                   5403:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5404:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5405: 
1.12      www      5406:     my $namevalue='';
1.800     albertel 5407:     foreach my $key (keys(%$storehash)) {
                   5408:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5409:     }
1.12      www      5410:     $namevalue=~s/\&$//;
1.187     www      5411:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  5412:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5413: }
                   5414: 
1.47      www      5415: # -------------------------------------------------------------- Critical Store
                   5416: 
                   5417: sub cstore {
1.1172.2.64  raeburn  5418:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5419:     my $home='';
                   5420: 
1.168     albertel 5421:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5422: 
1.213     www      5423:     $symb=&symbclean($symb);
1.122     albertel 5424:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5425: 
1.620     albertel 5426:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5427:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5428: 
                   5429:     &devalidate($symb,$stuname,$domain);
1.109     www      5430: 
                   5431:     $symb=escape($symb);
1.187     www      5432:     if (!$namespace) { 
1.620     albertel 5433:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5434:           return ''; 
                   5435:        } 
                   5436:     }
1.620     albertel 5437:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5438: 
                   5439:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5440:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5441: 
1.47      www      5442:     my $namevalue='';
1.800     albertel 5443:     foreach my $key (keys(%$storehash)) {
                   5444:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5445:     }
1.47      www      5446:     $namevalue=~s/\&$//;
1.187     www      5447:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5448:     return critical
1.1172.2.64  raeburn  5449:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5450: }
                   5451: 
1.9       www      5452: # --------------------------------------------------------------------- Restore
                   5453: 
                   5454: sub restore {
1.124     www      5455:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5456:     my $home='';
                   5457: 
1.168     albertel 5458:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5459: 
1.122     albertel 5460:     if (!$symb) {
1.1172.2.26  raeburn  5461:         return if ($namespace eq 'courserequests');
                   5462:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5463:     } else {
1.1172.2.26  raeburn  5464:         unless ($namespace eq 'courserequests') {
                   5465:             $symb=&escape(&symbclean($symb));
                   5466:         }
1.122     albertel 5467:     }
1.188     www      5468:     if (!$namespace) { 
1.620     albertel 5469:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5470:           return ''; 
                   5471:        } 
                   5472:     }
1.620     albertel 5473:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5474:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5475:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5476:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5477: 
1.12      www      5478:     my %returnhash=();
1.800     albertel 5479:     foreach my $line (split(/\&/,$answer)) {
                   5480: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5481:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5482:     }
1.75      www      5483:     my $version;
                   5484:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5485:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5486:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5487:        }
1.75      www      5488:     }
1.13      www      5489:     return %returnhash;
1.34      www      5490: }
                   5491: 
                   5492: # ---------------------------------------------------------- Course Description
1.1118    foxr     5493: #
                   5494: #  
1.34      www      5495: 
                   5496: sub coursedescription {
1.731     albertel 5497:     my ($courseid,$args)=@_;
1.34      www      5498:     $courseid=~s/^\///;
1.49      www      5499:     $courseid=~s/\_/\//g;
1.34      www      5500:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5501:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5502:     my $normalid=$cdomain.'_'.$cnum;
                   5503:     # need to always cache even if we get errors otherwise we keep 
                   5504:     # trying and trying and trying to get the course description.
                   5505:     my %envhash=();
                   5506:     my %returnhash=();
1.731     albertel 5507:     
                   5508:     my $expiretime=600;
                   5509:     if ($env{'request.course.id'} eq $normalid) {
                   5510: 	$expiretime=120;
                   5511:     }
                   5512: 
                   5513:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5514:     if (!$args->{'freshen_cache'}
                   5515: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5516: 	foreach my $key (keys(%env)) {
                   5517: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5518: 	    my ($setting) = $1;
                   5519: 	    $returnhash{$setting} = $env{$key};
                   5520: 	}
                   5521: 	return %returnhash;
                   5522:     }
                   5523: 
1.1118    foxr     5524:     # get the data again
                   5525: 
1.731     albertel 5526:     if (!$args->{'one_time'}) {
                   5527: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5528:     }
1.811     albertel 5529: 
1.34      www      5530:     if ($chome ne 'no_host') {
1.302     albertel 5531:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5532:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5533: 	   my $username = $env{'user.name'}; # Defult username
                   5534: 	   if(defined $args->{'user'}) {
                   5535: 	       $username = $args->{'user'};
                   5536: 	   }
1.129     albertel 5537:            $returnhash{'home'}= $chome;
                   5538: 	   $returnhash{'domain'} = $cdomain;
                   5539: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5540:            if (!defined($returnhash{'type'})) {
                   5541:                $returnhash{'type'} = 'Course';
                   5542:            }
1.130     albertel 5543:            while (my ($name,$value) = each %returnhash) {
1.53      www      5544:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5545:            }
1.270     www      5546:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5547:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5548: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5549:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5550:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5551:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5552:        }
                   5553:     }
1.731     albertel 5554:     if (!$args->{'one_time'}) {
1.949     raeburn  5555: 	&appenv(\%envhash);
1.731     albertel 5556:     }
1.302     albertel 5557:     return %returnhash;
1.461     www      5558: }
                   5559: 
1.1080    raeburn  5560: sub update_released_required {
                   5561:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5562:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5563:         $cid = $env{'request.course.id'};
                   5564:         $cdom = $env{'course.'.$cid.'.domain'};
                   5565:         $cnum = $env{'course.'.$cid.'.num'};
                   5566:         $chome = $env{'course.'.$cid.'.home'};
                   5567:     }
                   5568:     if ($needsrelease) {
                   5569:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5570:         my $needsupdate;
                   5571:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5572:             $needsupdate = 1;
                   5573:         } else {
                   5574:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5575:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5576:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5577:                 $needsupdate = 1;
                   5578:             }
                   5579:         }
                   5580:         if ($needsupdate) {
                   5581:             my %needshash = (
                   5582:                              'internal.releaserequired' => $needsrelease,
                   5583:                             );
                   5584:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5585:             if ($putresult eq 'ok') {
                   5586:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5587:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5588:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5589:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5590:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5591:                 }
                   5592:             }
                   5593:         }
                   5594:     }
                   5595:     return;
                   5596: }
                   5597: 
1.461     www      5598: # -------------------------------------------------See if a user is privileged
                   5599: 
                   5600: sub privileged {
1.1172.2.23  raeburn  5601:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5602:     my $now = time;
1.1172.2.23  raeburn  5603:     my $roles;
                   5604:     if (ref($possroles) eq 'ARRAY') {
                   5605:         $roles = $possroles;
                   5606:     } else {
                   5607:         $roles = ['dc','su'];
                   5608:     }
                   5609:     if (ref($possdomains) eq 'ARRAY') {
                   5610:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5611:         foreach my $dom (@{$possdomains}) {
                   5612:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5613:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5614:                 foreach my $role (@{$roles}) {
                   5615:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5616:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5617:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5618:                             return 1 unless (($end && $end < $now) ||
                   5619:                                              ($start && $start > $now));
                   5620:                         }
                   5621:                     }
                   5622:                 }
                   5623:             }
                   5624:         }
                   5625:     } else {
                   5626:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5627:         my $now = time;
1.1170    droeschl 5628: 
1.1172.2.58  raeburn  5629:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5630:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  5631:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   5632:                 return 1 unless ($tend && $tend < $now)
                   5633:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5634:             }
1.1172.2.23  raeburn  5635:         }
                   5636:     }
1.461     www      5637:     return 0;
1.9       www      5638: }
1.1       albertel 5639: 
1.1172.2.23  raeburn  5640: sub privileged_by_domain {
                   5641:     my ($domains,$roles) = @_;
                   5642:     my %privileged = ();
                   5643:     my $cachetime = 60*60*24;
                   5644:     my $now = time;
                   5645:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5646:         return %privileged;
                   5647:     }
                   5648:     foreach my $dom (@{$domains}) {
                   5649:         next if (ref($privileged{$dom}) eq 'HASH');
                   5650:         my $needroles;
                   5651:         foreach my $role (@{$roles}) {
                   5652:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5653:             if (defined($cached)) {
                   5654:                 if (ref($result) eq 'HASH') {
                   5655:                     $privileged{$dom}{$role} = $result;
                   5656:                 }
                   5657:             } else {
                   5658:                 $needroles = 1;
                   5659:             }
                   5660:         }
                   5661:         if ($needroles) {
                   5662:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5663:             $privileged{$dom} = {};
                   5664:             foreach my $server (keys(%dompersonnel)) {
                   5665:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5666:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5667:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5668:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5669:                         next if ($end && $end < $now);
                   5670:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   5671:                             $dompersonnel{$server}{$item};
                   5672:                     }
                   5673:                 }
                   5674:             }
                   5675:             if (ref($privileged{$dom}) eq 'HASH') {
                   5676:                 foreach my $role (@{$roles}) {
                   5677:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5678:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5679:                     } else {
                   5680:                         my %hash = ();
                   5681:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5682:                     }
                   5683:                 }
                   5684:             }
                   5685:         }
                   5686:     }
                   5687:     return %privileged;
                   5688: }
                   5689: 
1.103     harris41 5690: # -------------------------------------------------------- Get user privileges
1.11      www      5691: 
                   5692: sub rolesinit {
1.1169    droeschl 5693:     my ($domain, $username) = @_;
                   5694:     my %userroles = ('user.login.time' => time);
                   5695:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5696: 
                   5697:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5698:     # also, blocking can be triggered by an activating timer
                   5699:     # it's saved in the user's %env.
                   5700:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5701:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5702:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5703:         %timerintchk, %timerintenv);
                   5704: 
1.1162    raeburn  5705:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5706:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5707:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5708:     }
1.1169    droeschl 5709: 
1.1162    raeburn  5710:     foreach my $key (keys(%timerinterval)) {
                   5711:         my ($cid,$rest) = split(/\0/,$key);
                   5712:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5713:     }
1.1169    droeschl 5714: 
1.11      www      5715:     my %allroles=();
1.1162    raeburn  5716:     my %allgroups=();
1.11      www      5717: 
1.1172.2.58  raeburn  5718:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5719:         my $role = $rolesdump{$area};
                   5720:         $area =~ s/\_\w\w$//;
                   5721: 
                   5722:         my ($trole, $tend, $tstart, $group_privs);
                   5723: 
                   5724:         if ($role =~ /^cr/) {
                   5725:         # Custom role, defined by a user 
                   5726:         # e.g., user.role.cr/msu/smith/mynewrole
                   5727:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5728:                 $trole = $1;
                   5729:                 ($tend, $tstart) = split('_', $2);
                   5730:             } else {
                   5731:                 $trole = $role;
                   5732:             }
                   5733:         } elsif ($role =~ m|^gr/|) {
                   5734:         # Role of member in a group, defined within a course/community
                   5735:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5736:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5737:             next if $tstart eq '-1';
                   5738:             ($trole, $group_privs) = split(/\//, $trole);
                   5739:             $group_privs = &unescape($group_privs);
                   5740:         } else {
                   5741:         # Just a normal role, defined in roles.tab
                   5742:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5743:         }
                   5744: 
                   5745:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5746:                  $username);
                   5747:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5748: 
                   5749:         # role expired or not available yet?
                   5750:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5751:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5752: 
                   5753:         next if $area eq '' or $trole eq '';
                   5754: 
                   5755:         my $spec = "$trole.$area";
                   5756:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5757: 
                   5758:         if ($trole =~ /^cr\//) {
                   5759:         # Custom role, defined by a user
                   5760:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5761:         } elsif ($trole eq 'gr') {
                   5762:         # Role of a member in a group, defined within a course/community
                   5763:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5764:             next;
                   5765:         } else {
                   5766:         # Normal role, defined in roles.tab
                   5767:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5768:         }
                   5769: 
                   5770:         my $cid = $tdomain.'_'.$trest;
                   5771:         unless ($firstaccchk{$cid}) {
                   5772:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5773:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5774:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5775:                         $coursetimerstarts{$cid}{$item}; 
                   5776:                 }
                   5777:             }
                   5778:             $firstaccchk{$cid} = 1;
                   5779:         }
                   5780:         unless ($timerintchk{$cid}) {
                   5781:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5782:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5783:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5784:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5785:                 }
1.12      www      5786:             }
1.1169    droeschl 5787:             $timerintchk{$cid} = 1;
1.191     harris41 5788:         }
1.11      www      5789:     }
1.1169    droeschl 5790: 
1.1172.2.91  raeburn  5791:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   5792:                                                           \%allroles, \%allgroups);
1.1169    droeschl 5793:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  5794:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 5795: 
1.1162    raeburn  5796:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5797: }
                   5798: 
1.567     raeburn  5799: sub set_arearole {
1.1172.2.19  raeburn  5800:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5801:     unless ($nolog) {
1.567     raeburn  5802: # log the associated role with the area
1.1172.2.19  raeburn  5803:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5804:     }
1.743     albertel 5805:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5806: }
                   5807: 
                   5808: sub custom_roleprivs {
                   5809:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5810:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  5811:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5812:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5813:         my ($rdummy,$roledef)=
                   5814:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5815:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5816:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5817:             if (defined($syspriv)) {
1.1043    raeburn  5818:                 if ($trest =~ /^$match_community$/) {
                   5819:                     $syspriv =~ s/bre\&S//; 
                   5820:                 }
1.567     raeburn  5821:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5822:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5823:             }
                   5824:             if ($tdomain ne '') {
                   5825:                 if (defined($dompriv)) {
                   5826:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5827:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5828:                 }
                   5829:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  5830:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   5831:                         my $rolename = $1;
                   5832:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   5833:                     }
1.567     raeburn  5834:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5835:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5836:                 }
                   5837:             }
                   5838:         }
                   5839:     }
                   5840: }
                   5841: 
1.1172.2.89  raeburn  5842: sub course_adhocrole_privs {
                   5843:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   5844:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   5845:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   5846:         my (%currprivs,%storeprivs);
                   5847:         foreach my $item (split(/:/,$coursepriv)) {
                   5848:             my ($priv,$restrict) = split(/\&/,$item);
                   5849:             $currprivs{$priv} = $restrict;
                   5850:         }
                   5851:         my (%possadd,%possremove,%full);
                   5852:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   5853:             my ($priv,$restrict)=split(/\&/,$item);
                   5854:             $full{$priv} = $restrict;
                   5855:         }
                   5856:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   5857:              next if ($item eq '');
                   5858:              my ($rule,$rest) = split(/=/,$item);
                   5859:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   5860:              foreach my $priv (split(/:/,$rest)) {
                   5861:                  if ($priv ne '') {
                   5862:                      if ($rule eq 'off') {
                   5863:                          $possremove{$priv} = 1;
                   5864:                      } else {
                   5865:                          $possadd{$priv} = 1;
                   5866:                      }
                   5867:                  }
                   5868:              }
                   5869:          }
                   5870:          foreach my $priv (sort(keys(%full))) {
                   5871:              if (exists($currprivs{$priv})) {
                   5872:                  unless (exists($possremove{$priv})) {
                   5873:                      $storeprivs{$priv} = $currprivs{$priv};
                   5874:                  }
                   5875:              } elsif (exists($possadd{$priv})) {
                   5876:                  $storeprivs{$priv} = $full{$priv};
                   5877:              }
                   5878:          }
                   5879:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   5880:      }
                   5881:      return $coursepriv;
                   5882: }
                   5883: 
1.678     raeburn  5884: sub group_roleprivs {
                   5885:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5886:     my $access = 1;
                   5887:     my $now = time;
                   5888:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5889:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5890:     if ($access) {
1.811     albertel 5891:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5892:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5893:     }
                   5894: }
1.567     raeburn  5895: 
                   5896: sub standard_roleprivs {
                   5897:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5898:     if (defined($pr{$trole.':s'})) {
                   5899:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5900:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5901:     }
                   5902:     if ($tdomain ne '') {
                   5903:         if (defined($pr{$trole.':d'})) {
                   5904:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5905:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5906:         }
                   5907:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5908:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5909:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5910:         }
                   5911:     }
                   5912: }
                   5913: 
                   5914: sub set_userprivs {
1.1064    raeburn  5915:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5916:     my $author=0;
                   5917:     my $adv=0;
1.1172.2.91  raeburn  5918:     my $rar=0;
1.678     raeburn  5919:     my %grouproles = ();
                   5920:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5921:         my @groupkeys; 
1.1000    raeburn  5922:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5923:             push(@groupkeys,$role);
                   5924:         }
                   5925:         if (ref($groups_roles) eq 'HASH') {
                   5926:             foreach my $key (keys(%{$groups_roles})) {
                   5927:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5928:                     push(@groupkeys,$key);
                   5929:                 }
                   5930:             }
                   5931:         }
                   5932:         if (@groupkeys > 0) {
                   5933:             foreach my $role (@groupkeys) {
                   5934:                 my ($trole,$area,$sec,$extendedarea);
                   5935:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5936:                     $trole = $1;
                   5937:                     $area = $2;
                   5938:                     $sec = $3;
                   5939:                     $extendedarea = $area.$sec;
                   5940:                     if (exists($$allgroups{$area})) {
                   5941:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5942:                             my $spec = $trole.'.'.$extendedarea;
                   5943:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5944:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5945:                         }
1.678     raeburn  5946:                     }
                   5947:                 }
                   5948:             }
                   5949:         }
                   5950:     }
1.800     albertel 5951:     foreach my $group (keys(%grouproles)) {
                   5952:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5953:     }
1.800     albertel 5954:     foreach my $role (keys(%{$allroles})) {
                   5955:         my %thesepriv;
1.941     raeburn  5956:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5957:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5958:             if ($item ne '') {
                   5959:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5960:                 if ($restrictions eq '') {
                   5961:                     $thesepriv{$privilege}='F';
                   5962:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5963:                     $thesepriv{$privilege}.=$restrictions;
                   5964:                 }
                   5965:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  5966:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  5967:             }
                   5968:         }
                   5969:         my $thesestr='';
1.1104    raeburn  5970:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5971: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5972: 	}
                   5973:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5974:     }
1.1172.2.91  raeburn  5975:     return ($author,$adv,$rar);
1.567     raeburn  5976: }
                   5977: 
1.994     raeburn  5978: sub role_status {
1.1104    raeburn  5979:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5980:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  5981:         my ($one,$two) = split(m{\./},$rolekey,2);
                   5982:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  5983:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  5984:             $$where = '/'.$two;
1.994     raeburn  5985:             $$trolecode=$$role.'.'.$$where;
                   5986:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5987:             $$tstatus='is';
1.1104    raeburn  5988:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5989:                 $$tstatus='future';
1.1034    raeburn  5990:                 if ($$tstart<$now) {
                   5991:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5992:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5993:                             my (%allroles,%allgroups,$group_privs,
                   5994:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5995:                             my %userroles = (
                   5996:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5997:                             );
1.1064    raeburn  5998:                             @rolecodes = ('cm'); 
1.1002    raeburn  5999:                             my $spec=$$role.'.'.$$where;
                   6000:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6001:                             if ($$role =~ /^cr\//) {
                   6002:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6003:                                 push(@rolecodes,'cr');
1.1002    raeburn  6004:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6005:                                 push(@rolecodes,$$role);
1.1002    raeburn  6006:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6007:                                                     $env{'user.name'});
1.1064    raeburn  6008:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6009:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6010:                                 $group_privs = &unescape($group_privs);
                   6011:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6012:                                 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  6013:                                 &get_groups_roles($tdomain,$trest,
                   6014:                                                   \%course_roles,\@rolecodes,
                   6015:                                                   \%groups_roles);
1.1002    raeburn  6016:                             } else {
1.1064    raeburn  6017:                                 push(@rolecodes,$$role);
1.1002    raeburn  6018:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6019:                             }
1.1172.2.91  raeburn  6020:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6021:                                                                    \%groups_roles);
1.1064    raeburn  6022:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  6023:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6024:                         }
                   6025:                     }
1.1034    raeburn  6026:                     $$tstatus = 'is';
1.1002    raeburn  6027:                 }
1.994     raeburn  6028:             }
                   6029:             if ($$tend) {
1.1104    raeburn  6030:                 if ($$tend<$update) {
1.994     raeburn  6031:                     $$tstatus='expired';
                   6032:                 } elsif ($$tend<$now) {
                   6033:                     $$tstatus='will_not';
                   6034:                 }
                   6035:             }
                   6036:         }
                   6037:     }
                   6038: }
                   6039: 
1.1104    raeburn  6040: sub get_groups_roles {
                   6041:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6042:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6043:                   (ref($rolecodes) eq 'ARRAY') && 
                   6044:                   (ref($groups_roles) eq 'HASH')); 
                   6045:     if (keys(%{$cdom_courseroles}) > 0) {
                   6046:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6047:         if ($cdom ne '' && $cnum ne '') {
                   6048:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6049:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6050:                     my $crsrole = $1;
                   6051:                     my $crssec = $2;
                   6052:                     if ($crsrole =~ /^cr/) {
                   6053:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6054:                             push(@{$rolecodes},'cr');
                   6055:                         }
                   6056:                     } else {
                   6057:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6058:                             push(@{$rolecodes},$crsrole);
                   6059:                         }
                   6060:                     }
                   6061:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6062:                     if ($crssec ne '') {
                   6063:                         $rolekey .= "/$crssec";
                   6064:                     }
                   6065:                     $rolekey .= './';
                   6066:                     $groups_roles->{$rolekey} = $rolecodes;
                   6067:                 }
                   6068:             }
                   6069:         }
                   6070:     }
                   6071:     return;
                   6072: }
                   6073: 
                   6074: sub delete_env_groupprivs {
                   6075:     my ($where,$courseroles,$possroles) = @_;
                   6076:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6077:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6078:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6079:         %{$courseroles->{$udom}} =
                   6080:             &get_my_roles('','','userroles',['active'],
                   6081:                           $possroles,[$udom],1);
                   6082:     }
                   6083:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6084:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6085:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6086:             my $area = '/'.$cdom.'/'.$cnum;
                   6087:             my $privkey = "user.priv.$crsrole.$area";
                   6088:             if ($crssec ne '') {
                   6089:                 $privkey .= '/'.$crssec;
                   6090:             }
                   6091:             $privkey .= ".$area/$group";
                   6092:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6093:         }
                   6094:     }
                   6095:     return;
                   6096: }
                   6097: 
1.994     raeburn  6098: sub check_adhoc_privs {
1.1172.2.86  raeburn  6099:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6100:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6101:     if ($sec) {
                   6102:         $cckey .= '/'.$sec;
                   6103:     }
1.1172.2.9  raeburn  6104:     my $setprivs;
1.994     raeburn  6105:     if ($env{$cckey}) {
                   6106:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6107:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6108:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6109:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6110:             $setprivs = 1;
1.994     raeburn  6111:         }
                   6112:     } else {
1.1172.2.87  raeburn  6113:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6114:         $setprivs = 1;
1.994     raeburn  6115:     }
1.1172.2.9  raeburn  6116:     return $setprivs;
1.994     raeburn  6117: }
                   6118: 
                   6119: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6120: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6121:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6122:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6123:     if ($sec ne '') {
                   6124:         $area .= '/'.$sec;
                   6125:     }
1.994     raeburn  6126:     my $spec = $role.'.'.$area;
                   6127:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6128:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6129:     my %rolehash = ();
1.1172.2.89  raeburn  6130:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6131:         my $rolename = $1;
1.1172.2.84  raeburn  6132:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6133:         my %domdef = &get_domain_defaults($dcdom);
                   6134:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6135:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6136:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6137:             }
                   6138:         }
1.1172.2.84  raeburn  6139:     } else {
                   6140:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6141:     }
1.1172.2.91  raeburn  6142:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6143:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6144:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6145:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6146:         &appenv( {'request.role'        => $spec,
                   6147:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6148:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6149:                  }
                   6150:                );
                   6151:         my $tadv=0;
                   6152:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6153:         &appenv({'request.role.adv'    => $tadv});
                   6154:     }
1.994     raeburn  6155: }
                   6156: 
1.12      www      6157: # --------------------------------------------------------------- get interface
                   6158: 
                   6159: sub get {
1.131     albertel 6160:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6161:    my $items='';
1.800     albertel 6162:    foreach my $item (@$storearr) {
                   6163:        $items.=&escape($item).'&';
1.191     harris41 6164:    }
1.12      www      6165:    $items=~s/\&$//;
1.620     albertel 6166:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6167:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6168:    my $uhome=&homeserver($uname,$udomain);
                   6169: 
1.133     albertel 6170:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6171:    my @pairs=split(/\&/,$rep);
1.273     albertel 6172:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6173:      return @pairs;
                   6174:    }
1.15      www      6175:    my %returnhash=();
1.42      www      6176:    my $i=0;
1.800     albertel 6177:    foreach my $item (@$storearr) {
                   6178:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6179:       $i++;
1.191     harris41 6180:    }
1.15      www      6181:    return %returnhash;
1.27      www      6182: }
                   6183: 
                   6184: # --------------------------------------------------------------- del interface
                   6185: 
                   6186: sub del {
1.133     albertel 6187:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6188:    my $items='';
1.800     albertel 6189:    foreach my $item (@$storearr) {
                   6190:        $items.=&escape($item).'&';
1.191     harris41 6191:    }
1.984     neumanie 6192: 
1.27      www      6193:    $items=~s/\&$//;
1.620     albertel 6194:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6195:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6196:    my $uhome=&homeserver($uname,$udomain);
                   6197:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6198: }
                   6199: 
                   6200: # -------------------------------------------------------------- dump interface
                   6201: 
1.1172.2.22  raeburn  6202: sub unserialize {
                   6203:     my ($rep, $escapedkeys) = @_;
                   6204: 
                   6205:     return {} if $rep =~ /^error/;
                   6206: 
                   6207:     my %returnhash=();
                   6208:     foreach my $item (split(/\&/,$rep)) {
                   6209:         my ($key, $value) = split(/=/, $item, 2);
                   6210:         $key = unescape($key) unless $escapedkeys;
                   6211:         next if $key =~ /^error: 2 /;
                   6212:         $returnhash{$key} = &thaw_unescape($value);
                   6213:     }
                   6214:     return \%returnhash;
                   6215: }
                   6216: 
                   6217: # see Lond::dump_with_regexp
                   6218: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6219: sub dump {
1.1172.2.22  raeburn  6220:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6221:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6222:     if (!$uname) { $uname=$env{'user.name'}; }
                   6223:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6224: 
1.1172.2.55  raeburn  6225:     if ($regexp) {
                   6226:         $regexp=&escape($regexp);
                   6227:     } else {
                   6228:         $regexp='.';
                   6229:     }
1.1172.2.22  raeburn  6230:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   6231:         # user is hosted on this machine
1.1172.2.55  raeburn  6232:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  6233:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  6234:         return %{&unserialize($reply, $escapedkeys)};
                   6235:     }
1.1166    raeburn  6236:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6237:     my @pairs=split(/\&/,$rep);
                   6238:     my %returnhash=();
1.1098    foxr     6239:     if (!($rep =~ /^error/ )) {
                   6240: 	foreach my $item (@pairs) {
                   6241: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  6242:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     6243: 	    next if ($key =~ /^error: 2 /);
                   6244: 	    $returnhash{$key}=&thaw_unescape($value);
                   6245: 	}
1.755     albertel 6246:     }
                   6247:     return %returnhash;
1.407     www      6248: }
                   6249: 
1.1098    foxr     6250: 
1.717     albertel 6251: # --------------------------------------------------------- dumpstore interface
                   6252: 
                   6253: sub dumpstore {
                   6254:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  6255:    # same as dump but keys must be escaped. They may contain colon separated
                   6256:    # lists of values that may themself contain colons (e.g. symbs).
                   6257:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6258: }
                   6259: 
1.407     www      6260: # -------------------------------------------------------------- keys interface
                   6261: 
                   6262: sub getkeys {
                   6263:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6264:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6265:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6266:    my $uhome=&homeserver($uname,$udomain);
                   6267:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6268:    my @keyarray=();
1.800     albertel 6269:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6270:       next if ($key =~ /^error: 2 /);
1.800     albertel 6271:       push(@keyarray,&unescape($key));
1.407     www      6272:    }
                   6273:    return @keyarray;
1.318     matthew  6274: }
                   6275: 
1.319     matthew  6276: # --------------------------------------------------------------- currentdump
                   6277: sub currentdump {
1.328     matthew  6278:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6279:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6280:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6281:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6282:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  6283:    my $rep;
                   6284: 
                   6285:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6286:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   6287:                    $courseid)));
                   6288:    } else {
                   6289:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6290:    }
                   6291: 
1.318     matthew  6292:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6293:    #
1.318     matthew  6294:    my %returnhash=();
1.319     matthew  6295:    #
                   6296:    if ($rep eq "unknown_cmd") { 
                   6297:        # an old lond will not know currentdump
                   6298:        # Do a dump and make it look like a currentdump
1.822     albertel 6299:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6300:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6301:        my %hash = @tmp;
                   6302:        @tmp=();
1.424     matthew  6303:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6304:    } else {
                   6305:        my @pairs=split(/\&/,$rep);
1.800     albertel 6306:        foreach my $pair (@pairs) {
                   6307:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6308:            my ($symb,$param) = split(/:/,$key);
                   6309:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6310:                                                         &thaw_unescape($value);
1.319     matthew  6311:        }
1.191     harris41 6312:    }
1.12      www      6313:    return %returnhash;
1.424     matthew  6314: }
                   6315: 
                   6316: sub convert_dump_to_currentdump{
                   6317:     my %hash = %{shift()};
                   6318:     my %returnhash;
                   6319:     # Code ripped from lond, essentially.  The only difference
                   6320:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6321:     # we might run in to problems with parameter names =~ /^v\./
                   6322:     while (my ($key,$value) = each(%hash)) {
                   6323:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6324: 	$symb  = &unescape($symb);
                   6325: 	$param = &unescape($param);
1.424     matthew  6326:         next if ($v eq 'version' || $symb eq 'keys');
                   6327:         next if (exists($returnhash{$symb}) &&
                   6328:                  exists($returnhash{$symb}->{$param}) &&
                   6329:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6330:         $returnhash{$symb}->{$param}=$value;
                   6331:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6332:     }
                   6333:     #
                   6334:     # Remove all of the keys in the hashes which keep track of
                   6335:     # the version of the parameter.
                   6336:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6337:         # use a foreach because we are going to delete from the hash.
                   6338:         foreach my $key (keys(%$param_hash)) {
                   6339:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6340:         }
                   6341:     }
                   6342:     return \%returnhash;
1.12      www      6343: }
                   6344: 
1.627     albertel 6345: # ------------------------------------------------------ critical inc interface
                   6346: 
                   6347: sub cinc {
                   6348:     return &inc(@_,'critical');
                   6349: }
                   6350: 
1.449     matthew  6351: # --------------------------------------------------------------- inc interface
                   6352: 
                   6353: sub inc {
1.627     albertel 6354:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6355:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6356:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6357:     my $uhome=&homeserver($uname,$udomain);
                   6358:     my $items='';
                   6359:     if (! ref($store)) {
                   6360:         # got a single value, so use that instead
                   6361:         $items = &escape($store).'=&';
                   6362:     } elsif (ref($store) eq 'SCALAR') {
                   6363:         $items = &escape($$store).'=&';        
                   6364:     } elsif (ref($store) eq 'ARRAY') {
                   6365:         $items = join('=&',map {&escape($_);} @{$store});
                   6366:     } elsif (ref($store) eq 'HASH') {
                   6367:         while (my($key,$value) = each(%{$store})) {
                   6368:             $items.= &escape($key).'='.&escape($value).'&';
                   6369:         }
                   6370:     }
                   6371:     $items=~s/\&$//;
1.627     albertel 6372:     if ($critical) {
                   6373: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6374:     } else {
                   6375: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6376:     }
1.449     matthew  6377: }
                   6378: 
1.12      www      6379: # --------------------------------------------------------------- put interface
                   6380: 
                   6381: sub put {
1.134     albertel 6382:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6383:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6384:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6385:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6386:    my $items='';
1.800     albertel 6387:    foreach my $item (keys(%$storehash)) {
                   6388:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6389:    }
1.12      www      6390:    $items=~s/\&$//;
1.134     albertel 6391:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6392: }
                   6393: 
1.631     albertel 6394: # ------------------------------------------------------------ newput interface
                   6395: 
                   6396: sub newput {
                   6397:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6398:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6399:    if (!$uname) { $uname=$env{'user.name'}; }
                   6400:    my $uhome=&homeserver($uname,$udomain);
                   6401:    my $items='';
                   6402:    foreach my $key (keys(%$storehash)) {
                   6403:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6404:    }
                   6405:    $items=~s/\&$//;
                   6406:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6407: }
                   6408: 
                   6409: # ---------------------------------------------------------  putstore interface
                   6410: 
1.524     raeburn  6411: sub putstore {
1.1172.2.59  raeburn  6412:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6413:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6414:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6415:    my $uhome=&homeserver($uname,$udomain);
                   6416:    my $items='';
1.715     albertel 6417:    foreach my $key (keys(%$storehash)) {
                   6418:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6419:    }
1.715     albertel 6420:    $items=~s/\&$//;
1.716     albertel 6421:    my $esc_symb=&escape($symb);
                   6422:    my $esc_v=&escape($version);
1.715     albertel 6423:    my $reply =
1.716     albertel 6424:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6425: 	      $uhome);
1.1172.2.59  raeburn  6426:    if (($tolog) && ($reply eq 'ok')) {
                   6427:        my $namevalue='';
                   6428:        foreach my $key (keys(%{$storehash})) {
                   6429:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6430:        }
                   6431:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6432:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6433:                      '&version='.$esc_v.
                   6434:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6435:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6436:    }
1.715     albertel 6437:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6438:        # gfall back to way things use to be done
1.715     albertel 6439:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6440: 			    $uname);
1.524     raeburn  6441:    }
1.715     albertel 6442:    return $reply;
                   6443: }
                   6444: 
                   6445: sub old_putstore {
1.716     albertel 6446:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6447:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6448:     if (!$uname) { $uname=$env{'user.name'}; }
                   6449:     my $uhome=&homeserver($uname,$udomain);
                   6450:     my %newstorehash;
1.800     albertel 6451:     foreach my $item (keys(%$storehash)) {
                   6452: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6453: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6454:     }
                   6455:     my $items='';
                   6456:     my %allitems = ();
1.800     albertel 6457:     foreach my $item (keys(%newstorehash)) {
                   6458: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6459: 	    my $key = $1.':keys:'.$2;
                   6460: 	    $allitems{$key} .= $3.':';
                   6461: 	}
1.800     albertel 6462: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6463:     }
1.800     albertel 6464:     foreach my $item (keys(%allitems)) {
                   6465: 	$allitems{$item} =~ s/\:$//;
                   6466: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6467:     }
                   6468:     $items=~s/\&$//;
                   6469:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6470: }
                   6471: 
1.47      www      6472: # ------------------------------------------------------ critical put interface
                   6473: 
                   6474: sub cput {
1.134     albertel 6475:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6476:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6477:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6478:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6479:    my $items='';
1.800     albertel 6480:    foreach my $item (keys(%$storehash)) {
                   6481:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6482:    }
1.47      www      6483:    $items=~s/\&$//;
1.134     albertel 6484:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6485: }
                   6486: 
                   6487: # -------------------------------------------------------------- eget interface
                   6488: 
                   6489: sub eget {
1.133     albertel 6490:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6491:    my $items='';
1.800     albertel 6492:    foreach my $item (@$storearr) {
                   6493:        $items.=&escape($item).'&';
1.191     harris41 6494:    }
1.12      www      6495:    $items=~s/\&$//;
1.620     albertel 6496:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6497:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6498:    my $uhome=&homeserver($uname,$udomain);
                   6499:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6500:    my @pairs=split(/\&/,$rep);
                   6501:    my %returnhash=();
1.42      www      6502:    my $i=0;
1.800     albertel 6503:    foreach my $item (@$storearr) {
                   6504:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6505:       $i++;
1.191     harris41 6506:    }
1.12      www      6507:    return %returnhash;
                   6508: }
                   6509: 
1.667     albertel 6510: # ------------------------------------------------------------ tmpput interface
                   6511: sub tmpput {
1.802     raeburn  6512:     my ($storehash,$server,$context)=@_;
1.667     albertel 6513:     my $items='';
1.800     albertel 6514:     foreach my $item (keys(%$storehash)) {
                   6515: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6516:     }
                   6517:     $items=~s/\&$//;
1.802     raeburn  6518:     if (defined($context)) {
                   6519:         $items .= ':'.&escape($context);
                   6520:     }
1.667     albertel 6521:     return &reply("tmpput:$items",$server);
                   6522: }
                   6523: 
                   6524: # ------------------------------------------------------------ tmpget interface
                   6525: sub tmpget {
1.688     albertel 6526:     my ($token,$server)=@_;
                   6527:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6528:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6529:     my %returnhash;
1.1172.2.85  raeburn  6530:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   6531:         return %returnhash;
                   6532:     }
1.667     albertel 6533:     foreach my $item (split(/\&/,$rep)) {
                   6534: 	my ($key,$value)=split(/=/,$item);
                   6535: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6536:     }
                   6537:     return %returnhash;
                   6538: }
                   6539: 
1.1113    raeburn  6540: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6541: sub tmpdel {
                   6542:     my ($token,$server)=@_;
                   6543:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6544:     return &reply("tmpdel:$token",$server);
                   6545: }
                   6546: 
1.1172.2.13  raeburn  6547: # ------------------------------------------------------------ get_timebased_id
                   6548: 
                   6549: sub get_timebased_id {
                   6550:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6551:         $maxtries) = @_;
                   6552:     my ($newid,$error,$dellock);
                   6553:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   6554:         return ('','ok','invalid call to get suffix');
                   6555:     }
                   6556: 
                   6557: # set defaults for any optional args for which values were not supplied
                   6558:     if ($who eq '') {
                   6559:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6560:     }
                   6561:     if (!$locktries) {
                   6562:         $locktries = 3;
                   6563:     }
                   6564:     if (!$maxtries) {
                   6565:         $maxtries = 10;
                   6566:     }
                   6567: 
                   6568:     if (($cdom eq '') || ($cnum eq '')) {
                   6569:         if ($env{'request.course.id'}) {
                   6570:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6571:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6572:         }
                   6573:         if (($cdom eq '') || ($cnum eq '')) {
                   6574:             return ('','ok','call to get suffix not in course context');
                   6575:         }
                   6576:     }
                   6577: 
                   6578: # construct locking item
                   6579:     my $lockhash = {
                   6580:                       $prefix."\0".'locked_'.$keyid => $who,
                   6581:                    };
                   6582:     my $tries = 0;
                   6583: 
                   6584: # attempt to get lock on nohist_$namespace file
                   6585:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6586:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6587:         $tries ++;
                   6588:         sleep 1;
                   6589:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6590:     }
                   6591: 
                   6592: # attempt to get unique identifier, based on current timestamp
                   6593:     if ($gotlock eq 'ok') {
                   6594:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6595:         my $id = time;
                   6596:         $newid = $id;
1.1172.2.56  raeburn  6597:         if ($idtype eq 'addcode') {
                   6598:             $newid .= &sixnum_code();
                   6599:         }
1.1172.2.13  raeburn  6600:         my $idtries = 0;
                   6601:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6602:             if ($idtype eq 'concat') {
                   6603:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  6604:             } elsif ($idtype eq 'addcode') {
                   6605:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  6606:             } else {
                   6607:                 $newid ++;
                   6608:             }
                   6609:             $idtries ++;
                   6610:         }
                   6611:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6612:             my %new_item =  (
                   6613:                               $prefix."\0".$newid => $who,
                   6614:                             );
                   6615:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6616:                                                  $cdom,$cnum);
                   6617:             if ($putresult ne 'ok') {
                   6618:                 undef($newid);
                   6619:                 $error = 'error saving new item: '.$putresult;
                   6620:             }
                   6621:         } else {
1.1172.2.56  raeburn  6622:              undef($newid);
1.1172.2.13  raeburn  6623:              $error = ('error: no unique suffix available for the new item ');
                   6624:         }
                   6625: #  remove lock
                   6626:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6627:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6628:     } else {
                   6629:         $error = "error: could not obtain lockfile\n";
                   6630:         $dellock = 'ok';
1.1172.2.58  raeburn  6631:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6632:             $dellock = 'nolock';
                   6633:         }
1.1172.2.13  raeburn  6634:     }
                   6635:     return ($newid,$dellock,$error);
                   6636: }
                   6637: 
1.1172.2.56  raeburn  6638: sub sixnum_code {
                   6639:     my $code;
                   6640:     for (0..6) {
                   6641:         $code .= int( rand(9) );
                   6642:     }
                   6643:     return $code;
                   6644: }
                   6645: 
1.765     albertel 6646: # -------------------------------------------------- portfolio access checking
                   6647: 
                   6648: sub portfolio_access {
1.1172.2.77  raeburn  6649:     my ($requrl,$clientip) = @_;
1.765     albertel 6650:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  6651:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6652:     if ($result) {
                   6653:         my %setters;
                   6654:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6655:             my ($startblock,$endblock) =
                   6656:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6657:             if ($startblock && $endblock) {
                   6658:                 return 'B';
                   6659:             }
                   6660:         } else {
                   6661:             my ($startblock,$endblock) =
                   6662:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6663:             if ($startblock && $endblock) {
                   6664:                 return 'B';
                   6665:             }
                   6666:         }
                   6667:     }
1.765     albertel 6668:     if ($result eq 'ok') {
1.766     albertel 6669:        return 'F';
1.765     albertel 6670:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6671:        return 'A';
1.765     albertel 6672:     }
1.766     albertel 6673:     return '';
1.765     albertel 6674: }
                   6675: 
                   6676: sub get_portfolio_access {
1.1172.2.77  raeburn  6677:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 6678: 
                   6679:     if (!ref($access_hash)) {
                   6680: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6681: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6682: 						   $file_name);
                   6683: 	$access_hash = $access_controls{$file_name};
                   6684:     }
                   6685: 
1.1172.2.77  raeburn  6686:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 6687:     my $now = time;
                   6688:     if (ref($access_hash) eq 'HASH') {
                   6689:         foreach my $key (keys(%{$access_hash})) {
                   6690:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6691:             if ($start > $now) {
                   6692:                 next;
                   6693:             }
                   6694:             if ($end && $end<$now) {
                   6695:                 next;
                   6696:             }
                   6697:             if ($scope eq 'public') {
                   6698:                 $public = $key;
                   6699:                 last;
                   6700:             } elsif ($scope eq 'guest') {
                   6701:                 $guest = $key;
                   6702:             } elsif ($scope eq 'domains') {
                   6703:                 push(@domains,$key);
                   6704:             } elsif ($scope eq 'users') {
                   6705:                 push(@users,$key);
                   6706:             } elsif ($scope eq 'course') {
                   6707:                 push(@courses,$key);
                   6708:             } elsif ($scope eq 'group') {
                   6709:                 push(@groups,$key);
1.1172.2.77  raeburn  6710:             } elsif ($scope eq 'ip') {
                   6711:                 push(@ips,$key);
1.765     albertel 6712:             }
                   6713:         }
                   6714:         if ($public) {
                   6715:             return 'ok';
1.1172.2.77  raeburn  6716:         } elsif (@ips > 0) {
                   6717:             my $allowed;
                   6718:             foreach my $ipkey (@ips) {
                   6719:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   6720:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   6721:                         $allowed = 1;
                   6722:                         last;
                   6723:                     }
                   6724:                 }
                   6725:             }
                   6726:             if ($allowed) {
                   6727:                 return 'ok';
                   6728:             }
1.765     albertel 6729:         }
                   6730:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6731:             if ($guest) {
                   6732:                 return $guest;
                   6733:             }
                   6734:         } else {
                   6735:             if (@domains > 0) {
                   6736:                 foreach my $domkey (@domains) {
                   6737:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6738:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6739:                             return 'ok';
                   6740:                         }
                   6741:                     }
                   6742:                 }
                   6743:             }
                   6744:             if (@users > 0) {
                   6745:                 foreach my $userkey (@users) {
1.865     raeburn  6746:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6747:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6748:                             if (ref($item) eq 'HASH') {
                   6749:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6750:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6751:                                     return 'ok';
                   6752:                                 }
                   6753:                             }
                   6754:                         }
                   6755:                     } 
1.765     albertel 6756:                 }
                   6757:             }
                   6758:             my %roleshash;
                   6759:             my @courses_and_groups = @courses;
                   6760:             push(@courses_and_groups,@groups); 
                   6761:             if (@courses_and_groups > 0) {
                   6762:                 my (%allgroups,%allroles); 
                   6763:                 my ($start,$end,$role,$sec,$group);
                   6764:                 foreach my $envkey (%env) {
1.1060    raeburn  6765:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6766:                         my $cid = $2.'_'.$3; 
                   6767:                         if ($1 eq 'gr') {
                   6768:                             $group = $4;
                   6769:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6770:                         } else {
                   6771:                             if ($4 eq '') {
                   6772:                                 $sec = 'none';
                   6773:                             } else {
                   6774:                                 $sec = $4;
                   6775:                             }
                   6776:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6777:                         }
1.811     albertel 6778:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6779:                         my $cid = $2.'_'.$3;
                   6780:                         if ($4 eq '') {
                   6781:                             $sec = 'none';
                   6782:                         } else {
                   6783:                             $sec = $4;
                   6784:                         }
                   6785:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6786:                     }
                   6787:                 }
                   6788:                 if (keys(%allroles) == 0) {
                   6789:                     return;
                   6790:                 }
                   6791:                 foreach my $key (@courses_and_groups) {
                   6792:                     my %content = %{$$access_hash{$key}};
                   6793:                     my $cnum = $content{'number'};
                   6794:                     my $cdom = $content{'domain'};
                   6795:                     my $cid = $cdom.'_'.$cnum;
                   6796:                     if (!exists($allroles{$cid})) {
                   6797:                         next;
                   6798:                     }    
                   6799:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6800:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6801:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6802:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6803:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6804:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6805:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6806:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6807:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6808:                                         if (grep/^all$/,@sections) {
                   6809:                                             return 'ok';
                   6810:                                         } else {
                   6811:                                             if (grep/^$sec$/,@sections) {
                   6812:                                                 return 'ok';
                   6813:                                             }
                   6814:                                         }
                   6815:                                     }
                   6816:                                 }
                   6817:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6818:                                     if (grep/^none$/,@groups) {
                   6819:                                         return 'ok';
                   6820:                                     }
                   6821:                                 } else {
                   6822:                                     if (grep/^all$/,@groups) {
                   6823:                                         return 'ok';
                   6824:                                     } 
                   6825:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6826:                                         if (grep/^$group$/,@groups) {
                   6827:                                             return 'ok';
                   6828:                                         }
                   6829:                                     }
                   6830:                                 } 
                   6831:                             }
                   6832:                         }
                   6833:                     }
                   6834:                 }
                   6835:             }
                   6836:             if ($guest) {
                   6837:                 return $guest;
                   6838:             }
                   6839:         }
                   6840:     }
                   6841:     return;
                   6842: }
                   6843: 
                   6844: sub course_group_datechecker {
                   6845:     my ($dates,$now,$status) = @_;
                   6846:     my ($start,$end) = split(/\./,$dates);
                   6847:     if (!$start && !$end) {
                   6848:         return 'ok';
                   6849:     }
                   6850:     if (grep/^active$/,@{$status}) {
                   6851:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6852:             return 'ok';
                   6853:         }
                   6854:     }
                   6855:     if (grep/^previous$/,@{$status}) {
                   6856:         if ($end > $now ) {
                   6857:             return 'ok';
                   6858:         }
                   6859:     }
                   6860:     if (grep/^future$/,@{$status}) {
                   6861:         if ($start > $now) {
                   6862:             return 'ok';
                   6863:         }
                   6864:     }
                   6865:     return; 
                   6866: }
                   6867: 
                   6868: sub parse_portfolio_url {
                   6869:     my ($url) = @_;
                   6870: 
                   6871:     my ($type,$udom,$unum,$group,$file_name);
                   6872:     
1.823     albertel 6873:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6874: 	$type = 1;
                   6875:         $udom = $1;
                   6876:         $unum = $2;
                   6877:         $file_name = $3;
1.823     albertel 6878:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6879: 	$type = 2;
                   6880:         $udom = $1;
                   6881:         $unum = $2;
                   6882:         $group = $3;
                   6883:         $file_name = $3.'/'.$4;
                   6884:     }
                   6885:     if (wantarray) {
                   6886: 	return ($type,$udom,$unum,$file_name,$group);
                   6887:     }
                   6888:     return $type;
                   6889: }
                   6890: 
                   6891: sub is_portfolio_url {
                   6892:     my ($url) = @_;
                   6893:     return scalar(&parse_portfolio_url($url));
                   6894: }
                   6895: 
1.798     raeburn  6896: sub is_portfolio_file {
                   6897:     my ($file) = @_;
1.820     raeburn  6898:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6899:         return 1;
                   6900:     }
                   6901:     return;
                   6902: }
                   6903: 
1.976     raeburn  6904: sub usertools_access {
1.1084    raeburn  6905:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6906:     my ($access,%tools);
                   6907:     if ($context eq '') {
                   6908:         $context = 'tools';
                   6909:     }
                   6910:     if ($context eq 'requestcourses') {
                   6911:         %tools = (
                   6912:                       official   => 1,
                   6913:                       unofficial => 1,
1.1006    raeburn  6914:                       community  => 1,
1.1172.2.37  raeburn  6915:                       textbook   => 1,
1.985     raeburn  6916:                  );
1.1172.2.9  raeburn  6917:     } elsif ($context eq 'requestauthor') {
                   6918:         %tools = (
                   6919:                       requestauthor => 1,
                   6920:                  );
1.985     raeburn  6921:     } else {
                   6922:         %tools = (
                   6923:                       aboutme   => 1,
                   6924:                       blog      => 1,
1.1172.2.6  raeburn  6925:                       webdav    => 1,
1.985     raeburn  6926:                       portfolio => 1,
                   6927:                  );
                   6928:     }
1.976     raeburn  6929:     return if (!defined($tools{$tool}));
                   6930: 
1.1172.2.35  raeburn  6931:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6932:         $udom = $env{'user.domain'};
                   6933:         $uname = $env{'user.name'};
                   6934:     }
                   6935: 
1.978     raeburn  6936:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6937:         if ($action ne 'reload') {
1.985     raeburn  6938:             if ($context eq 'requestcourses') {
                   6939:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  6940:             } elsif ($context eq 'requestauthor') {
                   6941:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6942:             } else {
                   6943:                 return $env{'environment.availabletools.'.$tool};
                   6944:             }
                   6945:         }
1.976     raeburn  6946:     }
                   6947: 
1.1172.2.9  raeburn  6948:     my ($toolstatus,$inststatus,$envkey);
                   6949:     if ($context eq 'requestauthor') {
                   6950:         $envkey = $context;
                   6951:     } else {
                   6952:         $envkey = $context.'.'.$tool;
                   6953:     }
1.976     raeburn  6954: 
1.985     raeburn  6955:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6956:          ($action ne 'reload')) {
1.1172.2.9  raeburn  6957:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6958:         $inststatus = $env{'environment.inststatus'};
                   6959:     } else {
1.1084    raeburn  6960:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  6961:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6962:             $inststatus = $userenvref->{'inststatus'};
                   6963:         } else {
1.1172.2.9  raeburn  6964:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6965:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6966:             $inststatus = $userenv{'inststatus'};
                   6967:         }
1.976     raeburn  6968:     }
                   6969: 
                   6970:     if ($toolstatus ne '') {
                   6971:         if ($toolstatus) {
                   6972:             $access = 1;
                   6973:         } else {
                   6974:             $access = 0;
                   6975:         }
                   6976:         return $access;
                   6977:     }
                   6978: 
1.1084    raeburn  6979:     my ($is_adv,%domdef);
                   6980:     if (ref($is_advref) eq 'HASH') {
                   6981:         $is_adv = $is_advref->{'is_adv'};
                   6982:     } else {
                   6983:         $is_adv = &is_advanced_user($udom,$uname);
                   6984:     }
                   6985:     if (ref($domdefref) eq 'HASH') {
                   6986:         %domdef = %{$domdefref};
                   6987:     } else {
                   6988:         %domdef = &get_domain_defaults($udom);
                   6989:     }
1.976     raeburn  6990:     if (ref($domdef{$tool}) eq 'HASH') {
                   6991:         if ($is_adv) {
                   6992:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6993:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6994:                     $access = 1;
                   6995:                 } else {
                   6996:                     $access = 0;
                   6997:                 }
                   6998:                 return $access;
                   6999:             }
                   7000:         }
                   7001:         if ($inststatus ne '') {
                   7002:             my ($hasaccess,$hasnoaccess);
                   7003:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7004:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7005:                     if ($domdef{$tool}{$affiliation}) {
                   7006:                         $hasaccess = 1;
                   7007:                     } else {
                   7008:                         $hasnoaccess = 1;
                   7009:                     }
                   7010:                 }
                   7011:             }
                   7012:             if ($hasaccess || $hasnoaccess) {
                   7013:                 if ($hasaccess) {
                   7014:                     $access = 1;
                   7015:                 } elsif ($hasnoaccess) {
                   7016:                     $access = 0; 
                   7017:                 }
                   7018:                 return $access;
                   7019:             }
                   7020:         } else {
                   7021:             if ($domdef{$tool}{'default'} ne '') {
                   7022:                 if ($domdef{$tool}{'default'}) {
                   7023:                     $access = 1;
                   7024:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7025:                     $access = 0;
                   7026:                 }
                   7027:                 return $access;
                   7028:             }
                   7029:         }
                   7030:     } else {
1.1172.2.6  raeburn  7031:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7032:             $access = 1;
                   7033:         } else {
                   7034:             $access = 0;
                   7035:         }
1.976     raeburn  7036:         return $access;
                   7037:     }
                   7038: }
                   7039: 
1.1050    raeburn  7040: sub is_course_owner {
                   7041:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7042:     if (($udom eq '') || ($uname eq '')) {
                   7043:         $udom = $env{'user.domain'};
                   7044:         $uname = $env{'user.name'};
                   7045:     }
                   7046:     unless (($udom eq '') || ($uname eq '')) {
                   7047:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7048:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7049:                 return 1;
                   7050:             } else {
                   7051:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7052:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7053:                     return 1;
                   7054:                 }
                   7055:             }
                   7056:         }
                   7057:     }
                   7058:     return;
                   7059: }
                   7060: 
1.976     raeburn  7061: sub is_advanced_user {
                   7062:     my ($udom,$uname) = @_;
1.1085    raeburn  7063:     if ($udom ne '' && $uname ne '') {
                   7064:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7065:             if (wantarray) {
                   7066:                 return ($env{'user.adv'},$env{'user.author'});
                   7067:             } else {
                   7068:                 return $env{'user.adv'};
                   7069:             }
1.1085    raeburn  7070:         }
                   7071:     }
1.976     raeburn  7072:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7073:     my %allroles;
1.1128    raeburn  7074:     my ($is_adv,$is_author);
1.976     raeburn  7075:     foreach my $role (keys(%roleshash)) {
                   7076:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7077:         my $area = '/'.$tdomain.'/'.$trest;
                   7078:         if ($sec ne '') {
                   7079:             $area .= '/'.$sec;
                   7080:         }
                   7081:         if (($area ne '') && ($trole ne '')) {
                   7082:             my $spec=$trole.'.'.$area;
                   7083:             if ($trole =~ /^cr\//) {
                   7084:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7085:             } elsif ($trole ne 'gr') {
                   7086:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7087:             }
1.1128    raeburn  7088:             if ($trole eq 'au') {
                   7089:                 $is_author = 1;
                   7090:             }
1.976     raeburn  7091:         }
                   7092:     }
                   7093:     foreach my $role (keys(%allroles)) {
                   7094:         last if ($is_adv);
                   7095:         foreach my $item (split(/:/,$allroles{$role})) {
                   7096:             if ($item ne '') {
                   7097:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7098:                 if ($privilege eq 'adv') {
                   7099:                     $is_adv = 1;
                   7100:                     last;
                   7101:                 }
                   7102:             }
                   7103:         }
                   7104:     }
1.1128    raeburn  7105:     if (wantarray) {
                   7106:         return ($is_adv,$is_author);
                   7107:     }
1.976     raeburn  7108:     return $is_adv;
                   7109: }
1.798     raeburn  7110: 
1.1035    raeburn  7111: sub check_can_request {
1.1036    raeburn  7112:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7113:     my $canreq = 0;
                   7114:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7115:     my @options = ('approval','validate','autolimit');
                   7116:     my $optregex = join('|',@options);
                   7117:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7118:         foreach my $type (@{$types}) {
                   7119:             if (&usertools_access($env{'user.name'},
                   7120:                                   $env{'user.domain'},
                   7121:                                   $type,undef,'requestcourses')) {
                   7122:                 $canreq ++;
1.1036    raeburn  7123:                 if (ref($request_domains) eq 'HASH') {
                   7124:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7125:                 }
1.1035    raeburn  7126:                 if ($dom eq $env{'user.domain'}) {
                   7127:                     $can_request->{$type} = 1;
                   7128:                 }
                   7129:             }
                   7130:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7131:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7132:                 if (@curr > 0) {
1.1036    raeburn  7133:                     foreach my $item (@curr) {
                   7134:                         if (ref($request_domains) eq 'HASH') {
                   7135:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7136:                             if ($otherdom ne '') {
                   7137:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7138:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7139:                                         push(@{$request_domains->{$type}},$otherdom);
                   7140:                                     }
                   7141:                                 } else {
                   7142:                                     push(@{$request_domains->{$type}},$otherdom);
                   7143:                                 }
                   7144:                             }
                   7145:                         }
                   7146:                     }
                   7147:                     unless($dom eq $env{'user.domain'}) {
                   7148:                         $canreq ++;
1.1035    raeburn  7149:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7150:                             $can_request->{$type} = 1;
                   7151:                         }
                   7152:                     }
                   7153:                 }
                   7154:             }
                   7155:         }
                   7156:     }
                   7157:     return $canreq;
                   7158: }
                   7159: 
1.341     www      7160: # ---------------------------------------------- Custom access rule evaluation
                   7161: 
                   7162: sub customaccess {
                   7163:     my ($priv,$uri)=@_;
1.807     albertel 7164:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7165:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7166:     $udom = &LONCAPA::clean_domain($udom);
                   7167:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7168:     my $access=0;
1.800     albertel 7169:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7170: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7171: 	if ($type eq 'user') {
                   7172: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7173: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7174: 		if ($tdom) {
                   7175: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7176: 		}
1.896     albertel 7177: 		if ($tuname) {
                   7178: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7179: 		}
                   7180: 		$access=($effect eq 'allow');
                   7181: 		last;
                   7182: 	    }
                   7183: 	} else {
                   7184: 	    if ($role) {
                   7185: 		if ($role ne $urole) { next; }
                   7186: 	    }
                   7187: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7188: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7189: 		if ($tdom) {
                   7190: 		    if ($tdom ne $udom) { next; }
                   7191: 		}
                   7192: 		if ($tcrs) {
                   7193: 		    if ($tcrs ne $ucrs) { next; }
                   7194: 		}
                   7195: 		if ($tsec) {
                   7196: 		    if ($tsec ne $usec) { next; }
                   7197: 		}
                   7198: 		$access=($effect eq 'allow');
                   7199: 		last;
                   7200: 	    }
                   7201: 	    if ($realm eq '' && $role eq '') {
                   7202: 		$access=($effect eq 'allow');
                   7203: 	    }
1.402     bowersj2 7204: 	}
1.341     www      7205:     }
                   7206:     return $access;
                   7207: }
                   7208: 
1.103     harris41 7209: # ------------------------------------------------- Check for a user privilege
1.12      www      7210: 
                   7211: sub allowed {
1.1172.2.65  raeburn  7212:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7213:     my $ver_orguri=$uri;
1.439     www      7214:     $uri=&deversion($uri);
1.152     www      7215:     my $orguri=$uri;
1.52      www      7216:     $uri=&declutter($uri);
1.809     raeburn  7217: 
1.810     raeburn  7218:     if ($priv eq 'evb') {
                   7219: # Evade communication block restrictions for specified role in a course
                   7220:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7221:             return $1;
                   7222:         } else {
                   7223:             return;
                   7224:         }
                   7225:     }
                   7226: 
1.620     albertel 7227:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7228: # Free bre access to adm and meta resources
1.775     albertel 7229:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 7230: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7231: 	&& ($priv eq 'bre')) {
1.14      www      7232: 	return 'F';
1.159     www      7233:     }
                   7234: 
1.545     banghart 7235: # Free bre access to user's own portfolio contents
1.714     raeburn  7236:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7237:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7238: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7239:         my %setters;
                   7240:         my ($startblock,$endblock) = 
                   7241:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7242:         if ($startblock && $endblock) {
                   7243:             return 'B';
                   7244:         } else {
                   7245:             return 'F';
                   7246:         }
1.545     banghart 7247:     }
                   7248: 
1.762     raeburn  7249: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7250:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7251:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7252:         if (exists($env{'request.course.id'})) {
                   7253:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7254:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7255:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7256:                 my $courseprivid=$env{'request.course.id'};
                   7257:                 $courseprivid=~s/\_/\//;
                   7258:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7259:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7260:                     return $1; 
1.762     raeburn  7261:                 } else {
                   7262:                     if ($env{'request.course.sec'}) {
                   7263:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7264:                     }
                   7265:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7266:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7267:                         return $2;
                   7268:                     }
1.714     raeburn  7269:                 }
                   7270:             }
                   7271:         }
                   7272:     }
                   7273: 
1.159     www      7274: # Free bre to public access
                   7275: 
                   7276:     if ($priv eq 'bre') {
1.238     www      7277:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7278: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7279:            return 'F'; 
                   7280:         }
1.238     www      7281:         if ($copyright eq 'priv') {
                   7282:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7283: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7284: 		return '';
                   7285:             }
                   7286:         }
                   7287:         if ($copyright eq 'domain') {
                   7288:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7289: 	    unless (($env{'user.domain'} eq $1) ||
                   7290:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7291: 		return '';
                   7292:             }
1.262     matthew  7293:         }
1.620     albertel 7294:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7295:             # Library role, so allow browsing of resources in this domain.
                   7296:             return 'F';
1.238     www      7297:         }
1.341     www      7298:         if ($copyright eq 'custom') {
                   7299: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7300:         }
1.14      www      7301:     }
1.264     matthew  7302:     # Domain coordinator is trying to create a course
1.620     albertel 7303:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7304:         # uri is the requested domain in this case.
                   7305:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7306:         # a role of dc for the domain in question.
1.620     albertel 7307:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7308:     }
1.29      www      7309: 
1.52      www      7310:     my $thisallowed='';
                   7311:     my $statecond=0;
                   7312:     my $courseprivid='';
                   7313: 
1.1039    raeburn  7314:     my $ownaccess;
1.1043    raeburn  7315:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7316:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7317:         if ($uri eq '') {
                   7318:             $ownaccess = 1;
                   7319:         } else {
                   7320:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7321:                 my $udom = $env{'user.domain'};
                   7322:                 my $uname = $env{'user.name'};
                   7323:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7324:                     $ownaccess = 1;
1.1040    raeburn  7325:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7326:                     unless ($uri =~ m{\.\./}) {
                   7327:                         $ownaccess = 1;
                   7328:                     }
                   7329:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7330:                     my $now = time;
                   7331:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7332:                         my $adom = $1;
                   7333:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7334:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7335:                                 my ($start,$end) = split('.',$env{$key});
                   7336:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7337:                                     $ownaccess = 1;
                   7338:                                     last;
                   7339:                                 }
                   7340:                             }
                   7341:                         }
                   7342:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7343:                         my $adom = $1;
                   7344:                         my $aname = $2;
1.1042    raeburn  7345:                         foreach my $role ('ca','aa') { 
                   7346:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7347:                                 my ($start,$end) =
                   7348:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7349:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7350:                                     $ownaccess = 1;
                   7351:                                     last;
                   7352:                                 }
1.1039    raeburn  7353:                             }
                   7354:                         }
                   7355:                     }
                   7356:                 }
                   7357:             }
                   7358:         }
                   7359:     }
                   7360: 
1.52      www      7361: # Course
                   7362: 
1.620     albertel 7363:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7364:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7365:             $thisallowed.=$1;
                   7366:         }
1.52      www      7367:     }
1.29      www      7368: 
1.52      www      7369: # Domain
                   7370: 
1.620     albertel 7371:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7372:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7373:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7374:             $thisallowed.=$1;
                   7375:         }
1.12      www      7376:     }
1.52      www      7377: 
1.1141    raeburn  7378: # User who is not author or co-author might still be able to edit
                   7379: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7380:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7381:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7382:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7383:             $thisallowed.=$1;
                   7384:         }
                   7385:     }
                   7386: 
1.52      www      7387: # Course: uri itself is a course
1.66      www      7388:     my $courseuri=$uri;
                   7389:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7390:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7391: 
1.620     albertel 7392:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7393:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7394:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7395:             $thisallowed.=$1;
                   7396:         }
1.12      www      7397:     }
1.29      www      7398: 
1.665     albertel 7399: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7400: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7401:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7402: 	$thisallowed='';
1.671     raeburn  7403:         my ($match)=&is_on_map($uri);
                   7404:         if ($match) {
                   7405:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7406:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  7407:                 my $value = $1;
                   7408:                 if ($noblockcheck) {
                   7409:                     $thisallowed.=$value;
1.1162    raeburn  7410:                 } else {
1.1172.2.65  raeburn  7411:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7412:                     if (@blockers > 0) {
                   7413:                         $thisallowed = 'B';
                   7414:                     } else {
                   7415:                         $thisallowed.=$value;
                   7416:                     }
1.1162    raeburn  7417:                 }
1.671     raeburn  7418:             }
                   7419:         } else {
1.705     albertel 7420:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7421:             if ($refuri) {
                   7422:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7423:                     $thisallowed='F';
1.671     raeburn  7424:                 } else {
                   7425:                     $refuri=&declutter($refuri);
                   7426:                     my ($match) = &is_on_map($refuri);
                   7427:                     if ($match) {
1.1172.2.65  raeburn  7428:                         if ($noblockcheck) {
1.1162    raeburn  7429:                             $thisallowed='F';
1.1172.2.65  raeburn  7430:                         } else {
                   7431:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7432:                             if (@blockers > 0) {
                   7433:                                 $thisallowed = 'B';
                   7434:                             } else {
                   7435:                                 $thisallowed='F';
                   7436:                             }
1.1162    raeburn  7437:                         }
1.671     raeburn  7438:                     }
1.669     raeburn  7439:                 }
1.671     raeburn  7440:             }
                   7441:         }
1.314     www      7442:     }
1.492     albertel 7443: 
1.766     albertel 7444:     if ($priv eq 'bre'
                   7445: 	&& $thisallowed ne 'F' 
                   7446: 	&& $thisallowed ne '2'
                   7447: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  7448: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7449:     }
                   7450:     
1.52      www      7451: # Full access at system, domain or course-wide level? Exit.
1.29      www      7452:     if ($thisallowed=~/F/) {
                   7453: 	return 'F';
                   7454:     }
                   7455: 
1.52      www      7456: # If this is generating or modifying users, exit with special codes
1.29      www      7457: 
1.643     www      7458:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7459: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7460: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7461: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7462: 	    unless ($auname) { return $thisallowed; }
                   7463: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7464: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7465: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7466: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7467: 	}
1.52      www      7468: 	return $thisallowed;
                   7469:     }
                   7470: #
1.103     harris41 7471: # Gathered so far: system, domain and course wide privileges
1.52      www      7472: #
                   7473: # Course: See if uri or referer is an individual resource that is part of 
                   7474: # the course
                   7475: 
1.620     albertel 7476:     if ($env{'request.course.id'}) {
1.232     www      7477: 
1.620     albertel 7478:        $courseprivid=$env{'request.course.id'};
                   7479:        if ($env{'request.course.sec'}) {
                   7480:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7481:        }
                   7482:        $courseprivid=~s/\_/\//;
                   7483:        my $checkreferer=1;
1.232     www      7484:        my ($match,$cond)=&is_on_map($uri);
                   7485:        if ($match) {
                   7486:            $statecond=$cond;
1.620     albertel 7487:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7488:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7489:                my $value = $1;
                   7490:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  7491:                    if ($noblockcheck) {
1.1162    raeburn  7492:                        $thisallowed.=$value;
1.1172.2.65  raeburn  7493:                    } else {
                   7494:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7495:                        if (@blockers > 0) {
                   7496:                            $thisallowed = 'B';
                   7497:                        } else {
                   7498:                            $thisallowed.=$value;
                   7499:                        }
1.1162    raeburn  7500:                    }
                   7501:                } else {
                   7502:                    $thisallowed.=$value;
                   7503:                }
1.52      www      7504:                $checkreferer=0;
                   7505:            }
1.29      www      7506:        }
1.83      www      7507:        
1.148     www      7508:        if ($checkreferer) {
1.620     albertel 7509: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7510:             unless ($refuri) {
1.800     albertel 7511:                 foreach my $key (keys(%env)) {
                   7512: 		    if ($key=~/^httpref\..*\*/) {
                   7513: 			my $pattern=$key;
1.156     www      7514:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7515:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7516:                         $pattern=~s/\//\\\//g;
1.152     www      7517:                         if ($orguri=~/$pattern/) {
1.800     albertel 7518: 			    $refuri=$env{$key};
1.148     www      7519:                         }
                   7520:                     }
1.191     harris41 7521:                 }
1.148     www      7522:             }
1.232     www      7523: 
1.148     www      7524:          if ($refuri) { 
1.152     www      7525: 	  $refuri=&declutter($refuri);
1.232     www      7526:           my ($match,$cond)=&is_on_map($refuri);
                   7527:             if ($match) {
                   7528:               my $refstatecond=$cond;
1.620     albertel 7529:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7530:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7531:                   my $value = $1;
                   7532:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  7533:                       if ($noblockcheck) {
1.1162    raeburn  7534:                           $thisallowed.=$value;
1.1172.2.65  raeburn  7535:                       } else {
                   7536:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7537:                           if (@blockers > 0) {
                   7538:                               $thisallowed = 'B';
                   7539:                           } else {
                   7540:                               $thisallowed.=$value;
                   7541:                           }
1.1162    raeburn  7542:                       }
                   7543:                   } else {
                   7544:                       $thisallowed.=$value;
                   7545:                   }
1.53      www      7546:                   $uri=$refuri;
                   7547:                   $statecond=$refstatecond;
1.52      www      7548:               }
                   7549:           }
1.148     www      7550:         }
1.29      www      7551:        }
1.52      www      7552:    }
1.29      www      7553: 
1.52      www      7554: #
1.103     harris41 7555: # Gathered now: all privileges that could apply, and condition number
1.52      www      7556: # 
                   7557: #
                   7558: # Full or no access?
                   7559: #
1.29      www      7560: 
1.52      www      7561:     if ($thisallowed=~/F/) {
                   7562: 	return 'F';
                   7563:     }
1.29      www      7564: 
1.52      www      7565:     unless ($thisallowed) {
                   7566:         return '';
                   7567:     }
1.29      www      7568: 
1.52      www      7569: # Restrictions exist, deal with them
                   7570: #
                   7571: #   C:according to course preferences
                   7572: #   R:according to resource settings
                   7573: #   L:unless locked
                   7574: #   X:according to user session state
                   7575: #
                   7576: 
                   7577: # Possibly locked functionality, check all courses
1.54      www      7578: # Locks might take effect only after 10 minutes cache expiration for other
                   7579: # courses, and 2 minutes for current course
1.52      www      7580: 
                   7581:     my $envkey;
                   7582:     if ($thisallowed=~/L/) {
1.1000    raeburn  7583:         foreach $envkey (keys(%env)) {
1.54      www      7584:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7585:                my $courseid=$2;
                   7586:                my $roleid=$1.'.'.$2;
1.92      www      7587:                $courseid=~s/^\///;
1.54      www      7588:                my $expiretime=600;
1.620     albertel 7589:                if ($env{'request.role'} eq $roleid) {
1.54      www      7590: 		  $expiretime=120;
                   7591:                }
                   7592: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7593:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7594:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7595: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7596:                }
1.620     albertel 7597:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7598:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7599: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7600:                        &log($env{'user.domain'},$env{'user.name'},
                   7601:                             $env{'user.home'},
1.57      www      7602:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7603:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7604:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7605: 		       return '';
                   7606:                    }
                   7607:                }
1.620     albertel 7608:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7609:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7610: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7611:                        &log($env{'user.domain'},$env{'user.name'},
                   7612:                             $env{'user.home'},
1.57      www      7613:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7614:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7615:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7616: 		       return '';
                   7617:                    }
                   7618:                }
                   7619: 	   }
1.29      www      7620:        }
1.52      www      7621:     }
                   7622:    
                   7623: #
                   7624: # Rest of the restrictions depend on selected course
                   7625: #
                   7626: 
1.620     albertel 7627:     unless ($env{'request.course.id'}) {
1.766     albertel 7628: 	if ($thisallowed eq 'A') {
                   7629: 	    return 'A';
1.814     raeburn  7630:         } elsif ($thisallowed eq 'B') {
                   7631:             return 'B';
1.766     albertel 7632: 	} else {
                   7633: 	    return '1';
                   7634: 	}
1.52      www      7635:     }
1.29      www      7636: 
1.52      www      7637: #
                   7638: # Now user is definitely in a course
                   7639: #
1.53      www      7640: 
                   7641: 
                   7642: # Course preferences
                   7643: 
                   7644:    if ($thisallowed=~/C/) {
1.620     albertel 7645:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7646:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7647:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7648: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  7649: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7650: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7651: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7652: 			$env{'request.course.id'});
                   7653: 	   }
1.237     www      7654:            return '';
                   7655:        }
                   7656: 
1.620     albertel 7657:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7658: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  7659: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7660: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7661: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7662: 			$env{'request.course.id'});
                   7663: 	   }
1.54      www      7664:            return '';
                   7665:        }
1.53      www      7666:    }
                   7667: 
                   7668: # Resource preferences
                   7669: 
                   7670:    if ($thisallowed=~/R/) {
1.620     albertel 7671:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7672:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7673: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7674: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7675: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7676: 	   }
                   7677: 	   return '';
1.54      www      7678:        }
1.53      www      7679:    }
1.30      www      7680: 
1.246     www      7681: # Restricted by state or randomout?
1.30      www      7682: 
1.52      www      7683:    if ($thisallowed=~/X/) {
1.620     albertel 7684:       if ($env{'acc.randomout'}) {
1.579     albertel 7685: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7686:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7687:             return ''; 
                   7688:          }
1.247     www      7689:       }
                   7690:       if (&condval($statecond)) {
1.52      www      7691: 	 return '2';
                   7692:       } else {
                   7693:          return '';
                   7694:       }
                   7695:    }
1.30      www      7696: 
1.766     albertel 7697:     if ($thisallowed eq 'A') {
                   7698: 	return 'A';
1.814     raeburn  7699:     } elsif ($thisallowed eq 'B') {
                   7700:         return 'B';
1.766     albertel 7701:     }
1.52      www      7702:    return 'F';
1.232     www      7703: }
1.1162    raeburn  7704: 
1.1172.2.13  raeburn  7705: # ------------------------------------------- Check construction space access
                   7706: 
                   7707: sub constructaccess {
                   7708:     my ($url,$setpriv)=@_;
                   7709: 
                   7710: # We do not allow editing of previous versions of files
                   7711:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7712: 
                   7713: # Get username and domain from URL
                   7714:     my ($ownername,$ownerdomain,$ownerhome);
                   7715: 
                   7716:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  7717:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  7718: 
                   7719: # The URL does not really point to any authorspace, forget it
                   7720:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7721: 
                   7722: # Now we need to see if the user has access to the authorspace of
                   7723: # $ownername at $ownerdomain
                   7724: 
                   7725:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7726: # Real author for this?
                   7727:        $ownerhome = $env{'user.home'};
                   7728:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7729:           return ($ownername,$ownerdomain,$ownerhome);
                   7730:        }
                   7731:     } else {
                   7732: # Co-author for this?
                   7733:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7734:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7735:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7736:             return ($ownername,$ownerdomain,$ownerhome);
                   7737:         }
                   7738:     }
                   7739: 
                   7740: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7741: # we might as well leave
                   7742:    unless ($setpriv) { return ''; }
                   7743: 
                   7744: # Backdoor access?
                   7745:     my $allowed=&allowed('eco',$ownerdomain);
                   7746: # Nope
                   7747:     unless ($allowed) { return ''; }
                   7748: # Looks like we may have access, but could be locked by the owner of the construction space
                   7749:     if ($allowed eq 'U') {
                   7750:         my %blocked=&get('environment',['domcoord.author'],
                   7751:                          $ownerdomain,$ownername);
                   7752: # Is blocked by owner
                   7753:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7754:     }
                   7755:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7756: # Grant temporary access
                   7757:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  7758:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  7759:         if (!$update) { $update = $then; }
                   7760:         my $refresh=$env{'user.refresh.time'};
                   7761:         if (!$refresh) { $refresh = $update; }
                   7762:         my $now = time;
                   7763:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7764:                            $now,'ca','constructaccess');
                   7765:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7766:         return($ownername,$ownerdomain,$ownerhome);
                   7767:     }
                   7768: # No business here
                   7769:     return '';
                   7770: }
                   7771: 
1.1172.2.66  raeburn  7772: # ----------------------------------------------------------- Content Blocking
                   7773: 
                   7774: {
                   7775: # Caches for faster Course Contents display where content blocking
                   7776: # is in operation (i.e., interval param set) for timed quiz.
                   7777: #
                   7778: # User for whom data are being temporarily cached.
                   7779: my $cacheduser='';
                   7780: # Cached blockers for this user (a hash of blocking items).
                   7781: my %cachedblockers=();
                   7782: # When the data were last cached.
                   7783: my $cachedlast='';
                   7784: 
                   7785: sub load_all_blockers {
                   7786:     my ($uname,$udom,$blocks)=@_;
                   7787:     if (($uname ne '') && ($udom ne '')) {
                   7788:         if (($cacheduser eq $uname.':'.$udom) &&
                   7789:             (abs($cachedlast-time)<5)) {
                   7790:             return;
                   7791:         }
                   7792:     }
                   7793:     $cachedlast=time;
                   7794:     $cacheduser=$uname.':'.$udom;
                   7795:     %cachedblockers = &get_commblock_resources($blocks);
                   7796: }
                   7797: 
1.1162    raeburn  7798: sub get_comm_blocks {
                   7799:     my ($cdom,$cnum) = @_;
                   7800:     if ($cdom eq '' || $cnum eq '') {
                   7801:         return unless ($env{'request.course.id'});
                   7802:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7803:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7804:     }
                   7805:     my %commblocks;
                   7806:     my $hashid=$cdom.'_'.$cnum;
                   7807:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7808:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7809:         %commblocks = %{$blocksref};
                   7810:     } else {
                   7811:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7812:         my $cachetime = 600;
                   7813:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7814:     }
                   7815:     return %commblocks;
                   7816: }
                   7817: 
1.1172.2.66  raeburn  7818: sub get_commblock_resources {
                   7819:     my ($blocks) = @_;
                   7820:     my %blockers = ();
                   7821:     return %blockers unless ($env{'request.course.id'});
                   7822:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  7823:     my %commblocks;
                   7824:     if (ref($blocks) eq 'HASH') {
                   7825:         %commblocks = %{$blocks};
                   7826:     } else {
                   7827:         %commblocks = &get_comm_blocks();
                   7828:     }
1.1172.2.66  raeburn  7829:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  7830:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  7831:     return %blockers unless (ref($navmap));
                   7832:     my $now = time;
1.1162    raeburn  7833:     foreach my $block (keys(%commblocks)) {
                   7834:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7835:             my ($start,$end) = ($1,$2);
                   7836:             if ($start <= $now && $end >= $now) {
                   7837:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7838:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7839:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  7840:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7841:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  7842:                             }
                   7843:                         }
                   7844:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  7845:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7846:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  7847:                             }
                   7848:                         }
                   7849:                     }
                   7850:                 }
                   7851:             }
                   7852:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7853:             my $item = $1;
1.1163    raeburn  7854:             my @to_test;
1.1162    raeburn  7855:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7856:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66  raeburn  7857:                     my @interval;
                   7858:                     my $type = 'map';
                   7859:                     if ($item eq 'course') {
                   7860:                         $type = 'course';
                   7861:                         @interval=&EXT("resource.0.interval");
                   7862:                     } else {
                   7863:                         if ($item =~ /___\d+___/) {
                   7864:                             $type = 'resource';
                   7865:                             @interval=&EXT("resource.0.interval",$item);
                   7866:                             if (ref($navmap)) {
                   7867:                                 my $res = $navmap->getBySymb($item);
                   7868:                                 push(@to_test,$res);
                   7869:                             }
1.1162    raeburn  7870:                         } else {
1.1172.2.66  raeburn  7871:                             my $mapsymb = &symbread($item,1);
                   7872:                             if ($mapsymb) {
                   7873:                                 if (ref($navmap)) {
                   7874:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   7875:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   7876:                                     foreach my $res (@to_test) {
                   7877:                                         my $symb = $res->symb();
                   7878:                                         next if ($symb eq $mapsymb);
                   7879:                                         if ($symb ne '') {
                   7880:                                             @interval=&EXT("resource.0.interval",$symb);
                   7881:                                             if ($interval[1] eq 'map') {
                   7882:                                                 last;
1.1162    raeburn  7883:                                             }
                   7884:                                         }
                   7885:                                     }
                   7886:                                 }
                   7887:                             }
                   7888:                         }
1.1172.2.66  raeburn  7889:                     }
                   7890:                     if ($interval[0] =~ /^\d+$/) {
                   7891:                         my $first_access;
                   7892:                         if ($type eq 'resource') {
                   7893:                             $first_access=&get_first_access($interval[1],$item);
                   7894:                         } elsif ($type eq 'map') {
                   7895:                             $first_access=&get_first_access($interval[1],undef,$item);
                   7896:                         } else {
                   7897:                             $first_access=&get_first_access($interval[1]);
                   7898:                         }
                   7899:                         if ($first_access) {
                   7900:                             my $timesup = $first_access+$interval[0];
                   7901:                             if ($timesup > $now) {
                   7902:                                 my $activeblock;
                   7903:                                 foreach my $res (@to_test) {
                   7904:                                     if ($res->answerable()) {
                   7905:                                         $activeblock = 1;
                   7906:                                         last;
                   7907:                                     }
                   7908:                                 }
                   7909:                                 if ($activeblock) {
                   7910:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7911:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7912:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   7913:                                          }
                   7914:                                     }
                   7915:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7916:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7917:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  7918:                                         }
1.1162    raeburn  7919:                                     }
                   7920:                                 }
                   7921:                             }
                   7922:                         }
                   7923:                     }
                   7924:                 }
                   7925:             }
                   7926:         }
                   7927:     }
1.1172.2.66  raeburn  7928:     return %blockers;
1.1162    raeburn  7929: }
                   7930: 
1.1172.2.66  raeburn  7931: sub has_comm_blocking {
                   7932:     my ($priv,$symb,$uri,$blocks) = @_;
                   7933:     my @blockers;
                   7934:     return unless ($env{'request.course.id'});
                   7935:     return unless ($priv eq 'bre');
                   7936:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7937:     return if ($env{'request.state'} eq 'construct');
                   7938:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   7939:     return unless (keys(%cachedblockers) > 0);
                   7940:     my (%possibles,@symbs);
                   7941:     if (!$symb) {
                   7942:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  7943:     }
1.1172.2.66  raeburn  7944:     if ($symb) {
                   7945:         @symbs = ($symb);
                   7946:     } elsif (keys(%possibles)) {
                   7947:         @symbs = keys(%possibles);
                   7948:     }
                   7949:     my $noblock;
                   7950:     foreach my $symb (@symbs) {
                   7951:         last if ($noblock);
                   7952:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   7953:         foreach my $block (keys(%cachedblockers)) {
                   7954:             if ($block =~ /^firstaccess____(.+)$/) {
                   7955:                 my $item = $1;
                   7956:                 if (($item eq $map) || ($item eq $symb)) {
                   7957:                     $noblock = 1;
                   7958:                     last;
                   7959:                 }
1.1162    raeburn  7960:             }
1.1172.2.66  raeburn  7961:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   7962:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   7963:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   7964:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   7965:                             push(@blockers,$block);
                   7966:                         }
                   7967:                     }
                   7968:                 }
                   7969:             }
                   7970:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   7971:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   7972:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   7973:                         push(@blockers,$block);
                   7974:                     }
                   7975:                 }
1.1162    raeburn  7976:             }
                   7977:         }
                   7978:     }
1.1172.2.66  raeburn  7979:     return if ($noblock);
                   7980:     return @blockers;
                   7981: }
1.1162    raeburn  7982: }
                   7983: 
1.1172.2.66  raeburn  7984: # -------------------------------- Deversion and split uri into path an filename
                   7985: 
1.1133    foxr     7986: #
1.1172.2.66  raeburn  7987: #   Removes the version from a URI and
1.1133    foxr     7988: #   splits it in to its filename and path to the filename.
                   7989: #   Seems like File::Basename could have done this more clearly.
                   7990: #   Parameters:
                   7991: #      $uri   - input URI
                   7992: #   Returns:
                   7993: #     Two element list consisting of 
                   7994: #     $pathname  - the URI up to and excluding the trailing /
                   7995: #     $filename  - The part of the URI following the last /
                   7996: #  NOTE:
                   7997: #    Another realization of this is simply:
                   7998: #    use File::Basename;
                   7999: #    ...
                   8000: #    $uri = shift;
                   8001: #    $filename = basename($uri);
                   8002: #    $path     = dirname($uri);
                   8003: #    return ($filename, $path);
                   8004: #
                   8005: #     The implementation below is probably faster however.
                   8006: #
1.710     albertel 8007: sub split_uri_for_cond {
                   8008:     my $uri=&deversion(&declutter(shift));
                   8009:     my @uriparts=split(/\//,$uri);
                   8010:     my $filename=pop(@uriparts);
                   8011:     my $pathname=join('/',@uriparts);
                   8012:     return ($pathname,$filename);
                   8013: }
1.232     www      8014: # --------------------------------------------------- Is a resource on the map?
                   8015: 
                   8016: sub is_on_map {
1.710     albertel 8017:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8018:     #Trying to find the conditional for the file
1.620     albertel 8019:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8020: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8021:     if ($match) {
1.289     bowersj2 8022: 	return (1,$1);
                   8023:     } else {
1.434     www      8024: 	return (0,0);
1.289     bowersj2 8025:     }
1.12      www      8026: }
                   8027: 
1.427     www      8028: # --------------------------------------------------------- Get symb from alias
                   8029: 
                   8030: sub get_symb_from_alias {
                   8031:     my $symb=shift;
                   8032:     my ($map,$resid,$url)=&decode_symb($symb);
                   8033: # Already is a symb
                   8034:     if ($url) { return $symb; }
                   8035: # Must be an alias
                   8036:     my $aliassymb='';
                   8037:     my %bighash;
1.620     albertel 8038:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8039:                             &GDBM_READER(),0640)) {
                   8040:         my $rid=$bighash{'mapalias_'.$symb};
                   8041: 	if ($rid) {
                   8042: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8043: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8044: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8045: 	}
                   8046:         untie %bighash;
                   8047:     }
                   8048:     return $aliassymb;
                   8049: }
                   8050: 
1.12      www      8051: # ----------------------------------------------------------------- Define Role
                   8052: 
                   8053: sub definerole {
                   8054:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  8055:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8056:     foreach my $role (split(':',$sysrole)) {
                   8057: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8058:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8059:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8060: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8061:                return "refused:s:$crole&$cqual"; 
                   8062:             }
                   8063:         }
1.191     harris41 8064:     }
1.800     albertel 8065:     foreach my $role (split(':',$domrole)) {
                   8066: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8067:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8068:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8069: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8070:                return "refused:d:$crole&$cqual"; 
                   8071:             }
                   8072:         }
1.191     harris41 8073:     }
1.800     albertel 8074:     foreach my $role (split(':',$courole)) {
                   8075: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8076:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8077:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8078: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8079:                return "refused:c:$crole&$cqual"; 
                   8080:             }
                   8081:         }
1.191     harris41 8082:     }
1.1172.2.84  raeburn  8083:     my $uhome;
                   8084:     if (($uname ne '') && ($udom ne '')) {
                   8085:         $uhome = &homeserver($uname,$udom);
                   8086:         return $uhome if ($uhome eq 'no_host');
                   8087:     } else {
                   8088:         $uname = $env{'user.name'};
                   8089:         $udom = $env{'user.domain'};
                   8090:         $uhome = $env{'user.home'};
                   8091:     }
1.620     albertel 8092:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  8093:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8094:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  8095:     return reply($command,$uhome);
1.12      www      8096:   } else {
                   8097:     return 'refused';
                   8098:   }
1.105     harris41 8099: }
                   8100: 
                   8101: # ---------------- Make a metadata query against the network of library servers
                   8102: 
                   8103: sub metadata_query {
1.1172.2.33  raeburn  8104:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8105:     my %rhash;
1.845     albertel 8106:     my %libserv = &all_library();
1.244     matthew  8107:     my @server_list = (defined($server_array) ? @$server_array
                   8108:                                               : keys(%libserv) );
                   8109:     for my $server (@server_list) {
1.1172.2.33  raeburn  8110:         my $domains = '';
                   8111:         if (ref($domains_hash) eq 'HASH') {
                   8112:             $domains = $domains_hash->{$server};    
                   8113:         }
1.118     harris41 8114: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  8115: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8116: 	    $rhash{$server}=$reply;
                   8117: 	}
                   8118: 	else {
                   8119: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  8120: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8121: 			     $server);
                   8122: 	    $rhash{$server}=$reply;
                   8123: 	}
1.112     harris41 8124:     }
1.118     harris41 8125:     return \%rhash;
1.240     www      8126: }
                   8127: 
                   8128: # ----------------------------------------- Send log queries and wait for reply
                   8129: 
                   8130: sub log_query {
                   8131:     my ($uname,$udom,$query,%filters)=@_;
                   8132:     my $uhome=&homeserver($uname,$udom);
                   8133:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8134:     my $uhost=&hostname($uhome);
1.800     albertel 8135:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8136:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8137:                        $uhome);
1.479     albertel 8138:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8139:     return get_query_reply($queryid);
                   8140: }
                   8141: 
1.818     raeburn  8142: # -------------------------- Update MySQL table for portfolio file
                   8143: 
                   8144: sub update_portfolio_table {
1.821     raeburn  8145:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8146:     if ($group ne '') {
                   8147:         $file_name =~s /^\Q$group\E//;
                   8148:     }
1.818     raeburn  8149:     my $homeserver = &homeserver($uname,$udom);
                   8150:     my $queryid=
1.821     raeburn  8151:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8152:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8153:     my $reply = &get_query_reply($queryid);
                   8154:     return $reply;
                   8155: }
                   8156: 
1.899     raeburn  8157: # -------------------------- Update MySQL allusers table
                   8158: 
                   8159: sub update_allusers_table {
                   8160:     my ($uname,$udom,$names) = @_;
                   8161:     my $homeserver = &homeserver($uname,$udom);
                   8162:     my $queryid=
                   8163:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8164:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8165:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8166:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8167:                'generation='.&escape($names->{'generation'}).'%%'.
                   8168:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8169:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8170:     return;
1.899     raeburn  8171: }
                   8172: 
1.508     raeburn  8173: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8174: 
                   8175: sub fetch_enrollment_query {
1.511     raeburn  8176:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  8177:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8178:     my $maxtries = 1;
1.508     raeburn  8179:     if ($context eq 'automated') {
                   8180:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  8181:         $sleep = 2;
                   8182:         $loopmax = 100;
1.547     raeburn  8183:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8184:     } else {
                   8185:         $homeserver = &homeserver($cnum,$dom);
                   8186:     }
1.838     albertel 8187:     my $host=&hostname($homeserver);
1.506     raeburn  8188:     my $cmd = '';
1.1000    raeburn  8189:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8190:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8191:     }
                   8192:     $cmd =~ s/%%$//;
                   8193:     $cmd = &escape($cmd);
                   8194:     my $query = 'fetchenrollment';
1.620     albertel 8195:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8196:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8197:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8198:         return 'error: '.$queryid;
                   8199:     }
1.1172.2.93  raeburn  8200:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8201:     my $tries = 1;
                   8202:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  8203:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8204:         $tries ++;
                   8205:     }
1.526     raeburn  8206:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8207:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8208:     } else {
1.901     albertel 8209:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  8210:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8211:             foreach my $line (@responses) {
                   8212:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8213:                 $$replyref{$key} = $value;
                   8214:             }
                   8215:         } else {
1.1117    foxr     8216:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8217:             foreach my $line (@responses) {
                   8218:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8219:                 $$replyref{$key} = $value;
                   8220:                 if ($value > 0) {
1.800     albertel 8221:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8222:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8223:                         my $destname = $pathname.'/'.$filename;
                   8224:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8225:                         if ($xml_classlist =~ /^error/) {
                   8226:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8227:                         } else {
1.1172.2.96  raeburn  8228:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8229:                                 print FILE &unescape($xml_classlist);
                   8230:                                 close(FILE);
1.526     raeburn  8231:                             } else {
                   8232:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8233:                             }
                   8234:                         }
                   8235:                     }
                   8236:                 }
                   8237:             }
                   8238:         }
                   8239:         return 'ok';
                   8240:     }
                   8241:     return 'error';
                   8242: }
                   8243: 
1.242     www      8244: sub get_query_reply {
1.1172.2.79  raeburn  8245:     my ($queryid,$sleep,$loopmax) = @_;
                   8246:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8247:         $sleep = 0.2;
                   8248:     }
                   8249:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8250:         $loopmax = 100;
                   8251:     }
1.1117    foxr     8252:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8253:     my $reply='';
1.1172.2.79  raeburn  8254:     for (1..$loopmax) {
                   8255: 	sleep($sleep);
1.240     www      8256:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  8257: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8258: 		$reply = join('',<$fh>);
                   8259: 		close($fh);
1.240     www      8260: 	   } else { return 'error: reply_file_error'; }
1.242     www      8261:            return &unescape($reply);
                   8262: 	}
1.240     www      8263:     }
1.242     www      8264:     return 'timeout:'.$queryid;
1.240     www      8265: }
                   8266: 
                   8267: sub courselog_query {
1.241     www      8268: #
                   8269: # possible filters:
                   8270: # url: url or symb
                   8271: # username
                   8272: # domain
                   8273: # action: view, submit, grade
                   8274: # start: timestamp
                   8275: # end: timestamp
                   8276: #
1.240     www      8277:     my (%filters)=@_;
1.620     albertel 8278:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8279:     if ($filters{'url'}) {
                   8280: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8281:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8282:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8283:     }
1.620     albertel 8284:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8285:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8286:     return &log_query($cname,$cdom,'courselog',%filters);
                   8287: }
                   8288: 
                   8289: sub userlog_query {
1.858     raeburn  8290: #
                   8291: # possible filters:
                   8292: # action: log check role
                   8293: # start: timestamp
                   8294: # end: timestamp
                   8295: #
1.240     www      8296:     my ($uname,$udom,%filters)=@_;
                   8297:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8298: }
                   8299: 
1.506     raeburn  8300: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8301: 
                   8302: sub auto_run {
1.508     raeburn  8303:     my ($cnum,$cdom) = @_;
1.876     raeburn  8304:     my $response = 0;
                   8305:     my $settings;
                   8306:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8307:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8308:         $settings = $domconfig{'autoenroll'};
                   8309:         if ($settings->{'run'} eq '1') {
                   8310:             $response = 1;
                   8311:         }
                   8312:     } else {
1.934     raeburn  8313:         my $homeserver;
                   8314:         if (&is_course($cdom,$cnum)) {
                   8315:             $homeserver = &homeserver($cnum,$cdom);
                   8316:         } else {
                   8317:             $homeserver = &domain($cdom,'primary');
                   8318:         }
                   8319:         if ($homeserver ne 'no_host') {
                   8320:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8321:         }
1.876     raeburn  8322:     }
1.506     raeburn  8323:     return $response;
                   8324: }
1.776     albertel 8325: 
1.506     raeburn  8326: sub auto_get_sections {
1.508     raeburn  8327:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8328:     my $homeserver;
                   8329:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8330:         $homeserver = &homeserver($cnum,$cdom);
                   8331:     }
                   8332:     if (!defined($homeserver)) { 
                   8333:         if ($cdom =~ /^$match_domain$/) {
                   8334:             $homeserver = &domain($cdom,'primary');
                   8335:         }
                   8336:     }
                   8337:     my @secs;
                   8338:     if (defined($homeserver)) {
                   8339:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8340:         unless ($response eq 'refused') {
                   8341:             @secs = split(/:/,$response);
                   8342:         }
1.506     raeburn  8343:     }
                   8344:     return @secs;
                   8345: }
1.776     albertel 8346: 
1.506     raeburn  8347: sub auto_new_course {
1.1099    raeburn  8348:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8349:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8350:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8351:     return $response;
                   8352: }
1.776     albertel 8353: 
1.506     raeburn  8354: sub auto_validate_courseID {
1.508     raeburn  8355:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8356:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8357:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8358:     return $response;
                   8359: }
1.776     albertel 8360: 
1.1007    raeburn  8361: sub auto_validate_instcode {
1.1020    raeburn  8362:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8363:     my ($homeserver,$response);
                   8364:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8365:         $homeserver = &homeserver($cnum,$cdom);
                   8366:     }
                   8367:     if (!defined($homeserver)) {
                   8368:         if ($cdom =~ /^$match_domain$/) {
                   8369:             $homeserver = &domain($cdom,'primary');
                   8370:         }
                   8371:     }
1.1065    raeburn  8372:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8373:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  8374:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8375:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8376: }
                   8377: 
1.506     raeburn  8378: sub auto_create_password {
1.873     raeburn  8379:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8380:     my ($homeserver,$response);
1.506     raeburn  8381:     my $create_passwd = 0;
                   8382:     my $authchk = '';
1.873     raeburn  8383:     if ($udom =~ /^$match_domain$/) {
                   8384:         $homeserver = &domain($udom,'primary');
                   8385:     }
                   8386:     if ($homeserver eq '') {
                   8387:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8388:             $homeserver = &homeserver($cnum,$cdom);
                   8389:         }
                   8390:     }
                   8391:     if ($homeserver eq '') {
                   8392:         $authchk = 'nodomain';
1.506     raeburn  8393:     } else {
1.873     raeburn  8394:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8395:         if ($response eq 'refused') {
                   8396:             $authchk = 'refused';
                   8397:         } else {
1.901     albertel 8398:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8399:         }
1.506     raeburn  8400:     }
                   8401:     return ($authparam,$create_passwd,$authchk);
                   8402: }
                   8403: 
1.706     raeburn  8404: sub auto_photo_permission {
                   8405:     my ($cnum,$cdom,$students) = @_;
                   8406:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8407:     my ($outcome,$perm_reqd,$conditions) = 
                   8408: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8409:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8410: 	return (undef,undef);
                   8411:     }
1.706     raeburn  8412:     return ($outcome,$perm_reqd,$conditions);
                   8413: }
                   8414: 
                   8415: sub auto_checkphotos {
                   8416:     my ($uname,$udom,$pid) = @_;
                   8417:     my $homeserver = &homeserver($uname,$udom);
                   8418:     my ($result,$resulttype);
                   8419:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8420: 				   &escape($uname).':'.&escape($pid),
                   8421: 				   $homeserver));
1.709     albertel 8422:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8423: 	return (undef,undef);
                   8424:     }
1.706     raeburn  8425:     if ($outcome) {
                   8426:         ($result,$resulttype) = split(/:/,$outcome);
                   8427:     } 
                   8428:     return ($result,$resulttype);
                   8429: }
                   8430: 
                   8431: sub auto_photochoice {
                   8432:     my ($cnum,$cdom) = @_;
                   8433:     my $homeserver = &homeserver($cnum,$cdom);
                   8434:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8435: 						       &escape($cdom),
                   8436: 						       $homeserver)));
1.709     albertel 8437:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8438: 	return (undef,undef);
                   8439:     }
1.706     raeburn  8440:     return ($update,$comment);
                   8441: }
                   8442: 
                   8443: sub auto_photoupdate {
                   8444:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8445:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8446:     my $host=&hostname($homeserver);
1.706     raeburn  8447:     my $cmd = '';
                   8448:     my $maxtries = 1;
1.800     albertel 8449:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8450:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8451:     }
                   8452:     $cmd =~ s/%%$//;
                   8453:     $cmd = &escape($cmd);
                   8454:     my $query = 'institutionalphotos';
                   8455:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8456:     unless ($queryid=~/^\Q$host\E\_/) {
                   8457:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8458:         return 'error: '.$queryid;
                   8459:     }
                   8460:     my $reply = &get_query_reply($queryid);
                   8461:     my $tries = 1;
                   8462:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8463:         $reply = &get_query_reply($queryid);
                   8464:         $tries ++;
                   8465:     }
                   8466:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8467:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8468:     } else {
                   8469:         my @responses = split(/:/,$reply);
                   8470:         my $outcome = shift(@responses); 
                   8471:         foreach my $item (@responses) {
                   8472:             my ($key,$value) = split(/=/,$item);
                   8473:             $$photo{$key} = $value;
                   8474:         }
                   8475:         return $outcome;
                   8476:     }
                   8477:     return 'error';
                   8478: }
                   8479: 
1.521     raeburn  8480: sub auto_instcode_format {
1.793     albertel 8481:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8482: 	$cat_order) = @_;
1.521     raeburn  8483:     my $courses = '';
1.772     raeburn  8484:     my @homeservers;
1.521     raeburn  8485:     if ($caller eq 'global') {
1.841     albertel 8486: 	my %servers = &get_servers($codedom,'library');
                   8487: 	foreach my $tryserver (keys(%servers)) {
                   8488: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8489: 		push(@homeservers,$tryserver);
                   8490: 	    }
1.584     raeburn  8491:         }
1.1022    raeburn  8492:     } elsif ($caller eq 'requests') {
                   8493:         if ($codedom =~ /^$match_domain$/) {
                   8494:             my $chome = &domain($codedom,'primary');
                   8495:             unless ($chome eq 'no_host') {
                   8496:                 push(@homeservers,$chome);
                   8497:             }
                   8498:         }
1.521     raeburn  8499:     } else {
1.772     raeburn  8500:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8501:     }
1.793     albertel 8502:     foreach my $code (keys(%{$instcodes})) {
                   8503:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8504:     }
                   8505:     chop($courses);
1.772     raeburn  8506:     my $ok_response = 0;
                   8507:     my $response;
                   8508:     while (@homeservers > 0 && $ok_response == 0) {
                   8509:         my $server = shift(@homeservers); 
                   8510:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8511:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8512:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8513: 		split(/:/,$response);
1.772     raeburn  8514:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8515:             push(@{$codetitles},&str2array($codetitles_str));
                   8516:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8517:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8518:             $ok_response = 1;
                   8519:         }
                   8520:     }
                   8521:     if ($ok_response) {
1.521     raeburn  8522:         return 'ok';
1.772     raeburn  8523:     } else {
                   8524:         return $response;
1.521     raeburn  8525:     }
                   8526: }
                   8527: 
1.792     raeburn  8528: sub auto_instcode_defaults {
                   8529:     my ($domain,$returnhash,$code_order) = @_;
                   8530:     my @homeservers;
1.841     albertel 8531: 
                   8532:     my %servers = &get_servers($domain,'library');
                   8533:     foreach my $tryserver (keys(%servers)) {
                   8534: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8535: 	    push(@homeservers,$tryserver);
                   8536: 	}
1.792     raeburn  8537:     }
1.841     albertel 8538: 
1.792     raeburn  8539:     my $response;
1.841     albertel 8540:     foreach my $server (@homeservers) {
1.792     raeburn  8541:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8542:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8543: 	
                   8544: 	foreach my $pair (split(/\&/,$response)) {
                   8545: 	    my ($name,$value)=split(/\=/,$pair);
                   8546: 	    if ($name eq 'code_order') {
                   8547: 		@{$code_order} = split(/\&/,&unescape($value));
                   8548: 	    } else {
                   8549: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8550: 	    }
                   8551: 	}
                   8552: 	return 'ok';
1.792     raeburn  8553:     }
1.841     albertel 8554: 
                   8555:     return $response;
1.1003    raeburn  8556: }
                   8557: 
                   8558: sub auto_possible_instcodes {
1.1007    raeburn  8559:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8560:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8561:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8562:         return;
                   8563:     }
1.1003    raeburn  8564:     my (@homeservers,$uhome);
                   8565:     if (defined(&domain($domain,'primary'))) {
                   8566:         $uhome=&domain($domain,'primary');
                   8567:         push(@homeservers,&domain($domain,'primary'));
                   8568:     } else {
                   8569:         my %servers = &get_servers($domain,'library');
                   8570:         foreach my $tryserver (keys(%servers)) {
                   8571:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8572:                 push(@homeservers,$tryserver);
                   8573:             }
                   8574:         }
                   8575:     }
                   8576:     my $response;
                   8577:     foreach my $server (@homeservers) {
                   8578:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8579:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8580:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8581:             split(':',$response);
                   8582:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8583:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8584:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8585:             my ($name,$value)=split('=',$item);
                   8586:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8587:         }
                   8588:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8589:             my ($name,$value)=split('=',$item);
                   8590:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8591:         }
                   8592:         return 'ok';
                   8593:     }
                   8594:     return $response;
                   8595: }
1.792     raeburn  8596: 
1.1010    raeburn  8597: sub auto_courserequest_checks {
                   8598:     my ($dom) = @_;
1.1020    raeburn  8599:     my ($homeserver,%validations);
                   8600:     if ($dom =~ /^$match_domain$/) {
                   8601:         $homeserver = &domain($dom,'primary');
                   8602:     }
                   8603:     unless ($homeserver eq 'no_host') {
                   8604:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8605:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8606:             my @items = split(/&/,$response);
                   8607:             foreach my $item (@items) {
                   8608:                 my ($key,$value) = split('=',$item);
                   8609:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8610:             }
                   8611:         }
                   8612:     }
1.1010    raeburn  8613:     return %validations; 
                   8614: }
                   8615: 
1.1020    raeburn  8616: sub auto_courserequest_validation {
1.1172.2.43  raeburn  8617:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8618:     my ($homeserver,$response);
                   8619:     if ($dom =~ /^$match_domain$/) {
                   8620:         $homeserver = &domain($dom,'primary');
                   8621:     }
1.1172.2.43  raeburn  8622:     unless ($homeserver eq 'no_host') {
                   8623:         my $customdata;
                   8624:         if (ref($custominfo) eq 'HASH') {
                   8625:             $customdata = &freeze_escape($custominfo);
                   8626:         }
1.1020    raeburn  8627:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8628:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  8629:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8630:                                     $customdata,$homeserver));
1.1020    raeburn  8631:     }
                   8632:     return $response;
                   8633: }
                   8634: 
1.777     albertel 8635: sub auto_validate_class_sec {
1.918     raeburn  8636:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8637:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8638:     my $ownerlist;
                   8639:     if (ref($owners) eq 'ARRAY') {
                   8640:         $ownerlist = join(',',@{$owners});
                   8641:     } else {
                   8642:         $ownerlist = $owners;
                   8643:     }
1.773     raeburn  8644:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8645:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8646:     return $response;
                   8647: }
                   8648: 
1.1172.2.94  raeburn  8649: sub auto_validate_instclasses {
                   8650:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   8651:     my ($homeserver,%validations);
                   8652:     $homeserver = &homeserver($cnum,$cdom);
                   8653:     unless ($homeserver eq 'no_host') {
                   8654:         my $ownerlist;
                   8655:         if (ref($owners) eq 'ARRAY') {
                   8656:             $ownerlist = join(',',@{$owners});
                   8657:         } else {
                   8658:             $ownerlist = $owners;
                   8659:         }
                   8660:         if (ref($classesref) eq 'HASH') {
                   8661:             my $classes = &freeze_escape($classesref);
                   8662:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   8663:                                 ':'.$cdom.':'.$classes,$homeserver);
                   8664:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8665:                 my @items = split(/&/,$response);
                   8666:                 foreach my $item (@items) {
                   8667:                     my ($key,$value) = split('=',$item);
                   8668:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   8669:                 }
                   8670:             }
                   8671:         }
                   8672:     }
                   8673:     return %validations;
                   8674: }
                   8675: 
1.1172.2.38  raeburn  8676: sub auto_crsreq_update {
                   8677:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  8678:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  8679:     my ($homeserver,%crsreqresponse);
                   8680:     if ($cdom =~ /^$match_domain$/) {
                   8681:         $homeserver = &domain($cdom,'primary');
                   8682:     }
                   8683:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8684:         my $info;
                   8685:         if (ref($inbound) eq 'HASH') {
                   8686:             $info = &freeze_escape($inbound);
                   8687:         }
                   8688:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8689:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8690:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  8691:                             &escape($title).':'.&escape($code).':'.
                   8692:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  8693:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8694:             my @items = split(/&/,$response);
                   8695:             foreach my $item (@items) {
                   8696:                 my ($key,$value) = split('=',$item);
                   8697:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8698:             }
                   8699:         }
                   8700:     }
                   8701:     return \%crsreqresponse;
                   8702: }
                   8703: 
1.1172.2.78  raeburn  8704: sub auto_export_grades {
                   8705:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   8706:     my ($homeserver,%exportresponse);
                   8707:     if ($cdom =~ /^$match_domain$/) {
                   8708:         $homeserver = &domain($cdom,'primary');
                   8709:     }
                   8710:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8711:         my $info;
                   8712:         if (ref($inforef) eq 'HASH') {
                   8713:             $info = &freeze_escape($inforef);
                   8714:         }
                   8715:         if (ref($gradesref) eq 'HASH') {
                   8716:             my $grades = &freeze_escape($gradesref);
                   8717:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   8718:                                 $info.':'.$grades,$homeserver);
                   8719:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   8720:                 my @items = split(/&/,$response);
                   8721:                 foreach my $item (@items) {
                   8722:                     my ($key,$value) = split('=',$item);
                   8723:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   8724:                 }
                   8725:             }
                   8726:         }
                   8727:     }
                   8728:     return \%exportresponse;
                   8729: }
                   8730: 
1.1172.2.68  raeburn  8731: sub check_instcode_cloning {
                   8732:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   8733:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8734:         return;
                   8735:     }
                   8736:     my $canclone;
                   8737:     if (@{$code_order} > 0) {
                   8738:         my $instcoderegexp ='^';
                   8739:         my @clonecodes = split(/\&/,$cloner);
                   8740:         foreach my $item (@{$code_order}) {
                   8741:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   8742:                 foreach my $pair (@clonecodes) {
                   8743:                     my ($key,$val) = split(/\=/,$pair,2);
                   8744:                     $val = &unescape($val);
                   8745:                     if ($key eq $item) {
                   8746:                         $instcoderegexp .= '('.$val.')';
                   8747:                         last;
                   8748:                     }
                   8749:                 }
                   8750:             } else {
                   8751:                 $instcoderegexp .= $codedefaults->{$item};
                   8752:             }
                   8753:         }
                   8754:         $instcoderegexp .= '$';
                   8755:         my (@from,@to);
                   8756:         eval {
                   8757:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8758:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8759:         };
                   8760:         if ((@from > 0) && (@to > 0)) {
                   8761:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8762:             if (!@diffs) {
                   8763:                 $canclone = 1;
                   8764:             }
                   8765:         }
                   8766:     }
                   8767:     return $canclone;
                   8768: }
                   8769: 
                   8770: sub default_instcode_cloning {
                   8771:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   8772:     my (%codedefaults,@code_order,$canclone);
                   8773:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   8774:         %codedefaults = %{$codedefaultsref};
                   8775:         @code_order = @{$codeorderref};
                   8776:     } elsif ($clonedom) {
                   8777:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   8778:     }
                   8779:     if (($domdefclone) && (@code_order)) {
                   8780:         my @clonecodes = split(/\+/,$domdefclone);
                   8781:         my $instcoderegexp ='^';
                   8782:         foreach my $item (@code_order) {
                   8783:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   8784:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   8785:             } else {
                   8786:                 $instcoderegexp .= $codedefaults{$item};
                   8787:             }
                   8788:         }
                   8789:         $instcoderegexp .= '$';
                   8790:         my (@from,@to);
                   8791:         eval {
                   8792:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8793:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8794:         };
                   8795:         if ((@from > 0) && (@to > 0)) {
                   8796:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8797:             if (!@diffs) {
                   8798:                 $canclone = 1;
                   8799:             }
                   8800:         }
                   8801:     }
                   8802:     return $canclone;
                   8803: }
                   8804: 
1.679     raeburn  8805: # ------------------------------------------------------- Course Group routines
                   8806: 
                   8807: sub get_coursegroups {
1.809     raeburn  8808:     my ($cdom,$cnum,$group,$namespace) = @_;
                   8809:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  8810: }
                   8811: 
1.679     raeburn  8812: sub modify_coursegroup {
                   8813:     my ($cdom,$cnum,$groupsettings) = @_;
                   8814:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   8815: }
                   8816: 
1.809     raeburn  8817: sub toggle_coursegroup_status {
                   8818:     my ($cdom,$cnum,$group,$action) = @_;
                   8819:     my ($from_namespace,$to_namespace);
                   8820:     if ($action eq 'delete') {
                   8821:         $from_namespace = 'coursegroups';
                   8822:         $to_namespace = 'deleted_groups';
                   8823:     } else {
                   8824:         $from_namespace = 'deleted_groups';
                   8825:         $to_namespace = 'coursegroups';
                   8826:     }
                   8827:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  8828:     if (my $tmp = &error(%curr_group)) {
                   8829:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   8830:         return ('read error',$tmp);
                   8831:     } else {
                   8832:         my %savedsettings = %curr_group; 
1.809     raeburn  8833:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  8834:         my $deloutcome;
                   8835:         if ($result eq 'ok') {
1.809     raeburn  8836:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  8837:         } else {
                   8838:             return ('write error',$result);
                   8839:         }
                   8840:         if ($deloutcome eq 'ok') {
                   8841:             return 'ok';
                   8842:         } else {
                   8843:             return ('delete error',$deloutcome);
                   8844:         }
                   8845:     }
                   8846: }
                   8847: 
1.679     raeburn  8848: sub modify_group_roles {
1.957     raeburn  8849:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  8850:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   8851:     my $role = 'gr/'.&escape($userprivs);
                   8852:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  8853:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  8854:     if ($result eq 'ok') {
                   8855:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   8856:     }
1.679     raeburn  8857:     return $result;
                   8858: }
                   8859: 
                   8860: sub modify_coursegroup_membership {
                   8861:     my ($cdom,$cnum,$membership) = @_;
                   8862:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   8863:     return $result;
                   8864: }
                   8865: 
1.682     raeburn  8866: sub get_active_groups {
                   8867:     my ($udom,$uname,$cdom,$cnum) = @_;
                   8868:     my $now = time;
                   8869:     my %groups = ();
                   8870:     foreach my $key (keys(%env)) {
1.811     albertel 8871:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  8872:             my ($start,$end) = split(/\./,$env{$key});
                   8873:             if (($end!=0) && ($end<$now)) { next; }
                   8874:             if (($start!=0) && ($start>$now)) { next; }
                   8875:             if ($1 eq $cdom && $2 eq $cnum) {
                   8876:                 $groups{$3} = $env{$key} ;
                   8877:             }
                   8878:         }
                   8879:     }
                   8880:     return %groups;
                   8881: }
                   8882: 
1.683     raeburn  8883: sub get_group_membership {
                   8884:     my ($cdom,$cnum,$group) = @_;
                   8885:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   8886: }
                   8887: 
                   8888: sub get_users_groups {
                   8889:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  8890:     my @usersgroups;
1.683     raeburn  8891:     my $cachetime=1800;
                   8892: 
                   8893:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  8894:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   8895:     if (defined($cached)) {
1.734     albertel 8896:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  8897:     } else {  
                   8898:         $grouplist = '';
1.816     raeburn  8899:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  8900:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  8901:         my $access_end = $env{'course.'.$courseid.
                   8902:                               '.default_enrollment_end_date'};
                   8903:         my $now = time;
                   8904:         foreach my $key (keys(%roleshash)) {
                   8905:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   8906:                 my $group = $1;
                   8907:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   8908:                     my $start = $2;
                   8909:                     my $end = $1;
                   8910:                     if ($start == -1) { next; } # deleted from group
                   8911:                     if (($start!=0) && ($start>$now)) { next; }
                   8912:                     if (($end!=0) && ($end<$now)) {
                   8913:                         if ($access_end && $access_end < $now) {
                   8914:                             if ($access_end - $end < 86400) {
                   8915:                                 push(@usersgroups,$group);
1.733     raeburn  8916:                             }
                   8917:                         }
1.817     raeburn  8918:                         next;
1.733     raeburn  8919:                     }
1.817     raeburn  8920:                     push(@usersgroups,$group);
1.683     raeburn  8921:                 }
                   8922:             }
                   8923:         }
1.817     raeburn  8924:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8925:         $grouplist = join(':',@usersgroups);
                   8926:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8927:     }
1.733     raeburn  8928:     return @usersgroups;
1.683     raeburn  8929: }
                   8930: 
                   8931: sub devalidate_getgroups_cache {
                   8932:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8933:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8934: 
1.683     raeburn  8935:     my $hashid="$udom:$uname:$courseid";
                   8936:     &devalidate_cache_new('getgroups',$hashid);
                   8937: }
                   8938: 
1.12      www      8939: # ------------------------------------------------------------------ Plain Text
                   8940: 
                   8941: sub plaintext {
1.988     raeburn  8942:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8943:     if ($short =~ m{^cr/}) {
1.758     albertel 8944: 	return (split('/',$short))[-1];
                   8945:     }
1.742     raeburn  8946:     if (!defined($cid)) {
                   8947:         $cid = $env{'request.course.id'};
                   8948:     }
                   8949:     my %rolenames = (
1.1008    raeburn  8950:                       Course    => 'std',
                   8951:                       Community => 'alt1',
1.742     raeburn  8952:                     );
1.1037    raeburn  8953:     if ($cid ne '') {
                   8954:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8955:             unless ($forcedefault) {
                   8956:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8957:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8958:                 return &Apache::lonlocal::mt($roletext);
                   8959:             }
                   8960:         }
                   8961:     }
                   8962:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8963:         (defined($rolenames{$type})) && 
                   8964:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8965:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8966:     } elsif ($cid ne '') {
                   8967:         my $crstype = $env{'course.'.$cid.'.type'};
                   8968:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8969:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8970:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8971:         }
1.742     raeburn  8972:     }
1.1037    raeburn  8973:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8974: }
                   8975: 
                   8976: # ----------------------------------------------------------------- Assign Role
                   8977: 
                   8978: sub assignrole {
1.957     raeburn  8979:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8980:         $context)=@_;
1.21      www      8981:     my $mrole;
                   8982:     if ($role =~ /^cr\//) {
1.393     www      8983:         my $cwosec=$url;
1.811     albertel 8984:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8985: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8986:            my $refused = 1;
                   8987:            if ($context eq 'requestcourses') {
                   8988:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8989:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8990:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8991:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8992:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8993:                            if ($crsenv{'internal.courseowner'} eq
                   8994:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8995:                                $refused = '';
                   8996:                            }
                   8997:                        }
                   8998:                    }
                   8999:                }
                   9000:            }
                   9001:            if ($refused) {
                   9002:                &logthis('Refused custom assignrole: '.
                   9003:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9004:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9005:                return 'refused';
                   9006:            }
1.104     www      9007:         }
1.21      www      9008:         $mrole='cr';
1.678     raeburn  9009:     } elsif ($role =~ /^gr\//) {
                   9010:         my $cwogrp=$url;
1.811     albertel 9011:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9012:         unless (&allowed('mdg',$cwogrp)) {
                   9013:             &logthis('Refused group assignrole: '.
                   9014:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9015:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9016:             return 'refused';
                   9017:         }
                   9018:         $mrole='gr';
1.21      www      9019:     } else {
1.82      www      9020:         my $cwosec=$url;
1.811     albertel 9021:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9022:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9023:             my $refused;
                   9024:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9025:                 if (!(&allowed('c'.$role,$url))) {
                   9026:                     $refused = 1;
                   9027:                 }
                   9028:             } else {
                   9029:                 $refused = 1;
                   9030:             }
1.947     raeburn  9031:             if ($refused) {
1.1045    raeburn  9032:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9033:                 if (!$selfenroll && $context eq 'course') {
                   9034:                     my %crsenv;
                   9035:                     if ($role eq 'cc' || $role eq 'co') {
                   9036:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9037:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9038:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9039:                                 if ($crsenv{'internal.courseowner'} eq 
                   9040:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9041:                                     $refused = '';
                   9042:                                 }
                   9043:                             }
                   9044:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9045:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9046:                                 if ($crsenv{'internal.courseowner'} eq 
                   9047:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9048:                                     $refused = '';
                   9049:                                 }
                   9050:                             }
                   9051:                         }
                   9052:                     }
                   9053:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  9054:                     $refused = '';
1.1017    raeburn  9055:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9056:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9057:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9058:                         my $wrongcc;
                   9059:                         if ($cnum =~ /^$match_community$/) {
                   9060:                             $wrongcc = 1 if ($role eq 'cc');
                   9061:                         } else {
                   9062:                             $wrongcc = 1 if ($role eq 'co');
                   9063:                         }
                   9064:                         unless ($wrongcc) {
                   9065:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9066:                             if ($crsenv{'internal.courseowner'} eq 
                   9067:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9068:                                 $refused = '';
                   9069:                             }
1.1017    raeburn  9070:                         }
                   9071:                     }
1.1172.2.9  raeburn  9072:                 } elsif ($context eq 'requestauthor') {
                   9073:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   9074:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9075:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9076:                             $refused = '';
                   9077:                         } else {
                   9078:                             my %domdefaults = &get_domain_defaults($udom);
                   9079:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9080:                                 my $checkbystatus;
                   9081:                                 if ($env{'user.adv'}) {
                   9082:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9083:                                     if ($disposition eq 'automatic') {
                   9084:                                         $refused = '';
                   9085:                                     } elsif ($disposition eq '') {
                   9086:                                         $checkbystatus = 1;
                   9087:                                     }
                   9088:                                 } else {
                   9089:                                     $checkbystatus = 1;
                   9090:                                 }
                   9091:                                 if ($checkbystatus) {
                   9092:                                     if ($env{'environment.inststatus'}) {
                   9093:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9094:                                         foreach my $type (@inststatuses) {
                   9095:                                             if (($type ne '') &&
                   9096:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9097:                                                 $refused = '';
                   9098:                                             }
                   9099:                                         }
                   9100:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9101:                                         $refused = '';
                   9102:                                     }
                   9103:                                 }
                   9104:                             }
                   9105:                         }
                   9106:                     }
1.1017    raeburn  9107:                 }
                   9108:                 if ($refused) {
1.947     raeburn  9109:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9110:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9111: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9112:                     return 'refused';
                   9113:                 }
1.932     raeburn  9114:             }
1.1131    raeburn  9115:         } elsif ($role eq 'au') {
                   9116:             if ($url ne '/'.$udom.'/') {
                   9117:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9118:                          ' to assign author role for '.$uname.':'.$udom.
                   9119:                          ' in domain: '.$url.' refused (wrong domain).');
                   9120:                 return 'refused';
                   9121:             }
1.104     www      9122:         }
1.21      www      9123:         $mrole=$role;
                   9124:     }
1.620     albertel 9125:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9126:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9127:     if ($end) { $command.='_'.$end; }
1.21      www      9128:     if ($start) {
                   9129: 	if ($end) { 
1.81      www      9130:            $command.='_'.$start; 
1.21      www      9131:         } else {
1.81      www      9132:            $command.='_0_'.$start;
1.21      www      9133:         }
                   9134:     }
1.739     raeburn  9135:     my $origstart = $start;
                   9136:     my $origend = $end;
1.957     raeburn  9137:     my $delflag;
1.357     www      9138: # actually delete
                   9139:     if ($deleteflag) {
1.373     www      9140: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9141: # modify command to delete the role
1.620     albertel 9142:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9143:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9144: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9145: # set start and finish to negative values for userrolelog
                   9146:            $start=-1;
                   9147:            $end=-1;
1.957     raeburn  9148:            $delflag = 1;
1.357     www      9149:         }
                   9150:     }
                   9151: # send command
1.349     www      9152:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9153: # log new user role if status is ok
1.349     www      9154:     if ($answer eq 'ok') {
1.663     raeburn  9155: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  9156:         if (($role eq 'cc') || ($role eq 'in') ||
                   9157:             ($role eq 'ep') || ($role eq 'ad') ||
                   9158:             ($role eq 'ta') || ($role eq 'st') ||
                   9159:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9160:             ($role eq 'co')) {
1.1172.2.13  raeburn  9161: # for course roles, perform group memberships changes triggered by role change.
                   9162:             unless ($role =~ /^gr/) {
                   9163:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9164:                                                  $origstart,$selfenroll,$context);
                   9165:             }
1.1172.2.9  raeburn  9166:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9167:                            $selfenroll,$context);
                   9168:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  9169:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9170:                  ($role eq 'da')) {
1.1172.2.9  raeburn  9171:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9172:                            $context);
                   9173:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9174:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9175:                              $context);
                   9176:         }
1.1053    raeburn  9177:         if ($role eq 'cc') {
                   9178:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9179:         }
1.349     www      9180:     }
                   9181:     return $answer;
1.169     harris41 9182: }
                   9183: 
1.1053    raeburn  9184: sub autoupdate_coowners {
                   9185:     my ($url,$end,$start,$uname,$udom) = @_;
                   9186:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9187:     if (($cdom ne '') && ($cnum ne '')) {
                   9188:         my $now = time;
                   9189:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9190:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9191:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9192:             my $instcode = $coursehash{'internal.coursecode'};
                   9193:             if ($instcode ne '') {
1.1056    raeburn  9194:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9195:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9196:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9197:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9198:                         if ($result eq 'valid') {
                   9199:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9200:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9201:                                     push(@newcoowners,$coowner);
                   9202:                                 }
                   9203:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9204:                                     push(@newcoowners,$uname.':'.$udom);
                   9205:                                 }
                   9206:                                 @newcoowners = sort(@newcoowners);
                   9207:                             } else {
                   9208:                                 push(@newcoowners,$uname.':'.$udom);
                   9209:                             }
                   9210:                         } else {
                   9211:                             if ($coursehash{'internal.co-owners'}) {
                   9212:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9213:                                     unless ($coowner eq $uname.':'.$udom) {
                   9214:                                         push(@newcoowners,$coowner);
                   9215:                                     }
                   9216:                                 }
                   9217:                                 unless (@newcoowners > 0) {
                   9218:                                     $delcoowners = 1;
                   9219:                                     $coowners = '';
                   9220:                                 }
                   9221:                             }
                   9222:                         }
                   9223:                         if (@newcoowners || $delcoowners) {
                   9224:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9225:                                             $delcoowners,@newcoowners);
                   9226:                         }
                   9227:                     }
                   9228:                 }
                   9229:             }
                   9230:         }
                   9231:     }
                   9232: }
                   9233: 
                   9234: sub store_coowners {
                   9235:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9236:     my $cid = $cdom.'_'.$cnum;
                   9237:     my ($coowners,$delresult,$putresult);
                   9238:     if (@newcoowners) {
                   9239:         $coowners = join(',',@newcoowners);
                   9240:         my %coownershash = (
                   9241:                             'internal.co-owners' => $coowners,
                   9242:                            );
                   9243:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9244:         if ($putresult eq 'ok') {
                   9245:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9246:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9247:             }
                   9248:         }
                   9249:     }
                   9250:     if ($delcoowners) {
                   9251:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9252:         if ($delresult eq 'ok') {
                   9253:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9254:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9255:             }
                   9256:         }
                   9257:     }
                   9258:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9259:         my %crsinfo =
                   9260:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9261:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9262:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9263:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9264:         }
                   9265:     }
                   9266: }
                   9267: 
1.169     harris41 9268: # -------------------------------------------------- Modify user authentication
1.197     www      9269: # Overrides without validation
                   9270: 
1.169     harris41 9271: sub modifyuserauth {
                   9272:     my ($udom,$uname,$umode,$upass)=@_;
                   9273:     my $uhome=&homeserver($uname,$udom);
1.197     www      9274:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   9275:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9276:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9277:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9278:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9279: 		     &escape($upass),$uhome);
1.620     albertel 9280:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9281:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9282:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9283:     &log($udom,,$uname,$uhome,
1.620     albertel 9284:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9285:                                      $env{'user.name'}.', '.$umode.
1.197     www      9286:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9287:     unless ($reply eq 'ok') {
1.197     www      9288:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9289: 	return 'error: '.$reply;
                   9290:     }   
1.170     harris41 9291:     return 'ok';
1.80      www      9292: }
                   9293: 
1.81      www      9294: # --------------------------------------------------------------- Modify a user
1.80      www      9295: 
1.81      www      9296: sub modifyuser {
1.206     matthew  9297:     my ($udom,    $uname, $uid,
                   9298:         $umode,   $upass, $first,
                   9299:         $middle,  $last,  $gene,
1.1058    raeburn  9300:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9301:     $udom= &LONCAPA::clean_domain($udom);
                   9302:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9303:     my $showcandelete = 'none';
                   9304:     if (ref($candelete) eq 'ARRAY') {
                   9305:         if (@{$candelete} > 0) {
                   9306:             $showcandelete = join(', ',@{$candelete});
                   9307:         }
                   9308:     }
1.81      www      9309:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9310:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9311: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9312:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9313:                                      ' desiredhome not specified'). 
1.620     albertel 9314:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9315:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9316:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9317:     my $newuser;
                   9318:     if ($uhome eq 'no_host') {
                   9319:         $newuser = 1;
                   9320:     }
1.80      www      9321: # ----------------------------------------------------------------- Create User
1.406     albertel 9322:     if (($uhome eq 'no_host') && 
                   9323: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      9324:         my $unhome='';
1.844     albertel 9325:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9326:             $unhome = $desiredhome;
1.620     albertel 9327: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9328: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9329:         } else { # load balancing routine for determining $unhome
1.81      www      9330:             my $loadm=10000000;
1.841     albertel 9331: 	    my %servers = &get_servers($udom,'library');
                   9332: 	    foreach my $tryserver (keys(%servers)) {
                   9333: 		my $answer=reply('load',$tryserver);
                   9334: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9335: 		    $loadm=$answer;
                   9336: 		    $unhome=$tryserver;
                   9337: 		}
1.80      www      9338: 	    }
                   9339:         }
                   9340:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9341: 	    return 'error: unable to find a home server for '.$uname.
                   9342:                    ' in domain '.$udom;
1.80      www      9343:         }
                   9344:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9345:                          &escape($upass),$unhome);
                   9346: 	unless ($reply eq 'ok') {
                   9347:             return 'error: '.$reply;
                   9348:         }   
1.230     stredwic 9349:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9350:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9351: 	    return 'error: unable verify users home machine.';
1.80      www      9352:         }
1.209     matthew  9353:     }   # End of creation of new user
1.80      www      9354: # ---------------------------------------------------------------------- Add ID
                   9355:     if ($uid) {
                   9356:        $uid=~tr/A-Z/a-z/;
                   9357:        my %uidhash=&idrget($udom,$uname);
1.196     www      9358:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9359:          && (!$forceid)) {
1.80      www      9360: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9361: 	      return 'error: user id "'.$uid.'" does not match '.
                   9362:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9363:           }
                   9364:        } else {
                   9365: 	  &idput($udom,($uname => $uid));
                   9366:        }
                   9367:     }
                   9368: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9369:     my @tmp=&get('environment',
1.899     raeburn  9370: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9371:                     'permanentemail','inststatus'],
1.134     albertel 9372: 		   $udom,$uname);
1.1075    raeburn  9373:     my (%names,%oldnames);
1.313     matthew  9374:     if ($tmp[0] =~ m/^error:.*/) { 
                   9375:         %names=(); 
                   9376:     } else {
                   9377:         %names = @tmp;
1.1075    raeburn  9378:         %oldnames = %names;
1.313     matthew  9379:     }
1.388     www      9380: #
1.1058    raeburn  9381: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9382: # of users did not contain them), do not overwrite existing values
                   9383: # unless field is in $candelete array ref.  
                   9384: #
                   9385: 
                   9386:     my @fields = ('firstname','middlename','lastname','generation',
                   9387:                   'permanentemail','id');
                   9388:     my %newvalues;
                   9389:     if (ref($candelete) eq 'ARRAY') {
                   9390:         foreach my $field (@fields) {
                   9391:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9392:                 if ($field eq 'firstname') {
                   9393:                     $names{$field} = $first;
                   9394:                 } elsif ($field eq 'middlename') {
                   9395:                     $names{$field} = $middle;
                   9396:                 } elsif ($field eq 'lastname') {
                   9397:                     $names{$field} = $last;
                   9398:                 } elsif ($field eq 'generation') { 
                   9399:                     $names{$field} = $gene;
                   9400:                 } elsif ($field eq 'permanentemail') {
                   9401:                     $names{$field} = $email;
                   9402:                 } elsif ($field eq 'id') {
                   9403:                     $names{$field}  = $uid;
                   9404:                 }
                   9405:             }
                   9406:         }
                   9407:     }
1.388     www      9408:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9409:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9410:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9411:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9412:     if ($email) {
                   9413:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9414:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9415:     }
1.899     raeburn  9416:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9417:     if (defined($inststatus)) {
                   9418:         $names{'inststatus'} = '';
                   9419:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9420:         if (ref($usertypes) eq 'HASH') {
                   9421:             my @okstatuses; 
                   9422:             foreach my $item (split(/:/,$inststatus)) {
                   9423:                 if (defined($usertypes->{$item})) {
                   9424:                     push(@okstatuses,$item);  
                   9425:                 }
                   9426:             }
                   9427:             if (@okstatuses) {
                   9428:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9429:             }
                   9430:         }
                   9431:     }
1.1075    raeburn  9432:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9433:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9434:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9435:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9436:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9437:     } else {
                   9438:         $logmsg .= ' during self creation';
                   9439:     }
1.1075    raeburn  9440:     my $changed;
                   9441:     if ($newuser) {
                   9442:         $changed = 1;
                   9443:     } else {
                   9444:         foreach my $field (@fields) {
                   9445:             if ($names{$field} ne $oldnames{$field}) {
                   9446:                 $changed = 1;
                   9447:                 last;
                   9448:             }
                   9449:         }
                   9450:     }
                   9451:     unless ($changed) {
                   9452:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9453:         &logthis($logmsg);
                   9454:         return 'ok';
                   9455:     }
                   9456:     my $reply = &put('environment', \%names, $udom,$uname);
                   9457:     if ($reply ne 'ok') { 
                   9458:         return 'error: '.$reply;
                   9459:     }
1.1087    raeburn  9460:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9461:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9462:     }
1.1075    raeburn  9463:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9464:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9465:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9466:     &logthis($logmsg);
1.134     albertel 9467:     return 'ok';
1.80      www      9468: }
                   9469: 
1.81      www      9470: # -------------------------------------------------------------- Modify student
1.80      www      9471: 
1.81      www      9472: sub modifystudent {
                   9473:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9474:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  9475:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9476:     if (!$cid) {
1.620     albertel 9477: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9478: 	    return 'not_in_class';
                   9479: 	}
1.80      www      9480:     }
                   9481: # --------------------------------------------------------------- Make the user
1.81      www      9482:     my $reply=&modifyuser
1.209     matthew  9483: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9484:          $desiredhome,$email,$inststatus);
1.80      www      9485:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9486:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  9487:     # student's environment
1.297     matthew  9488:     $uid = undef if (!$forceid);
1.455     albertel 9489:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  9490: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  9491:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9492:     return $reply;
                   9493: }
                   9494: 
                   9495: sub modify_student_enrollment {
1.1172.2.23  raeburn  9496:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  9497:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9498:     my ($cdom,$cnum,$chome);
                   9499:     if (!$cid) {
1.620     albertel 9500: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9501: 	    return 'not_in_class';
                   9502: 	}
1.620     albertel 9503: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9504: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9505:     } else {
                   9506: 	($cdom,$cnum)=split(/_/,$cid);
                   9507:     }
1.620     albertel 9508:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9509:     if (!$chome) {
1.457     raeburn  9510: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9511:     }
1.455     albertel 9512:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9513:     # Make sure the user exists
1.81      www      9514:     my $uhome=&homeserver($uname,$udom);
                   9515:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9516: 	return 'error: no such user';
                   9517:     }
1.297     matthew  9518:     # Get student data if we were not given enough information
                   9519:     if (!defined($first)  || $first  eq '' || 
                   9520:         !defined($last)   || $last   eq '' || 
                   9521:         !defined($uid)    || $uid    eq '' || 
                   9522:         !defined($middle) || $middle eq '' || 
                   9523:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9524:         # They did not supply us with enough data to enroll the student, so
                   9525:         # we need to pick up more information.
1.297     matthew  9526:         my %tmp = &get('environment',
1.294     matthew  9527:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9528:                        ,$udom,$uname);
                   9529: 
1.800     albertel 9530:         #foreach my $key (keys(%tmp)) {
                   9531:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9532:         #}
1.294     matthew  9533:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9534:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9535:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9536:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9537:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9538:     }
1.556     albertel 9539:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9540:     my $user = "$uname:$udom";
                   9541:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9542:     my $reply=cput('classlist',
1.1148    raeburn  9543: 		   {$user => 
1.1172.2.76  raeburn  9544: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 9545: 		   $cdom,$cnum);
1.1148    raeburn  9546:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9547:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9548:     } else { 
1.81      www      9549: 	return 'error: '.$reply;
                   9550:     }
1.297     matthew  9551:     # Add student role to user
1.83      www      9552:     my $uurl='/'.$cid;
1.81      www      9553:     $uurl=~s/\_/\//g;
                   9554:     if ($usec) {
                   9555: 	$uurl.='/'.$usec;
                   9556:     }
1.1148    raeburn  9557:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9558:                              $selfenroll,$context);
                   9559:     if ($result ne 'ok') {
                   9560:         if ($old_entry{$user} ne '') {
                   9561:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9562:         } else {
                   9563:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9564:         }
                   9565:     }
                   9566:     return $result; 
1.21      www      9567: }
                   9568: 
1.556     albertel 9569: sub format_name {
                   9570:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9571:     my $name;
                   9572:     if ($first ne 'lastname') {
                   9573: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9574:     } else {
                   9575: 	if ($lastname=~/\S/) {
                   9576: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9577: 	    $name=~s/\s+,/,/;
                   9578: 	} else {
                   9579: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9580: 	}
                   9581:     }
                   9582:     $name=~s/^\s+//;
                   9583:     $name=~s/\s+$//;
                   9584:     $name=~s/\s+/ /g;
                   9585:     return $name;
                   9586: }
                   9587: 
1.84      www      9588: # ------------------------------------------------- Write to course preferences
                   9589: 
                   9590: sub writecoursepref {
                   9591:     my ($courseid,%prefs)=@_;
                   9592:     $courseid=~s/^\///;
                   9593:     $courseid=~s/\_/\//g;
                   9594:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9595:     my $chome=homeserver($cnum,$cdomain);
                   9596:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9597: 	return 'error: no such course';
                   9598:     }
                   9599:     my $cstring='';
1.800     albertel 9600:     foreach my $pref (keys(%prefs)) {
                   9601: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9602:     }
1.84      www      9603:     $cstring=~s/\&$//;
                   9604:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9605: }
                   9606: 
                   9607: # ---------------------------------------------------------- Make/modify course
                   9608: 
                   9609: sub createcourse {
1.741     raeburn  9610:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  9611:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      9612:     $url=&declutter($url);
                   9613:     my $cid='';
1.1028    raeburn  9614:     if ($context eq 'requestcourses') {
                   9615:         my $can_create = 0;
                   9616:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9617:         if ($udom eq $ownerdom) {
                   9618:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   9619:                                   $context)) {
                   9620:                 $can_create = 1;
                   9621:             }
                   9622:         } else {
                   9623:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9624:                                            $category);
                   9625:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   9626:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   9627:                 if (@curr > 0) {
                   9628:                     my @options = qw(approval validate autolimit);
                   9629:                     my $optregex = join('|',@options);
                   9630:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   9631:                         $can_create = 1;
                   9632:                     }
                   9633:                 }
                   9634:             }
                   9635:         }
                   9636:         if ($can_create) {
                   9637:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   9638:                 unless (&allowed('ccc',$udom)) {
                   9639:                     return 'refused'; 
                   9640:                 }
1.1017    raeburn  9641:             }
                   9642:         } else {
                   9643:             return 'refused';
                   9644:         }
1.1028    raeburn  9645:     } elsif (!&allowed('ccc',$udom)) {
                   9646:         return 'refused';
1.84      www      9647:     }
1.1011    raeburn  9648: # --------------------------------------------------------------- Get Unique ID
                   9649:     my $uname;
                   9650:     if ($cnum =~ /^$match_courseid$/) {
                   9651:         my $chome=&homeserver($cnum,$udom,'true');
                   9652:         if (($chome eq '') || ($chome eq 'no_host')) {
                   9653:             $uname = $cnum;
                   9654:         } else {
1.1038    raeburn  9655:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9656:         }
                   9657:     } else {
1.1038    raeburn  9658:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9659:     }
                   9660:     return $uname if ($uname =~ /^error/);
                   9661: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  9662:     if (!defined($course_server)) {
                   9663:         if (defined(&domain($udom,'primary'))) {
                   9664:             $course_server = &domain($udom,'primary');
                   9665:         } else {
                   9666:             $course_server = $env{'user.home'}; 
                   9667:         }
                   9668:     }
                   9669:     my %host_servers =
                   9670:         &Apache::lonnet::get_servers($udom,'library');
                   9671:     unless ($host_servers{$course_server}) {
                   9672:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  9673:     }
1.84      www      9674: # ------------------------------------------------------------- Make the course
                   9675:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  9676:                       $course_server);
1.84      www      9677:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  9678:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      9679:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9680: 	return 'error: no such course';
                   9681:     }
1.271     www      9682: # ----------------------------------------------------------------- Course made
1.516     raeburn  9683: # log existence
1.1029    raeburn  9684:     my $now = time;
1.918     raeburn  9685:     my $newcourse = {
                   9686:                     $udom.'_'.$uname => {
1.921     raeburn  9687:                                      description => $description,
                   9688:                                      inst_code   => $inst_code,
                   9689:                                      owner       => $course_owner,
                   9690:                                      type        => $crstype,
1.1029    raeburn  9691:                                      creator     => $env{'user.name'}.':'.
                   9692:                                                     $env{'user.domain'},
                   9693:                                      created     => $now,
                   9694:                                      context     => $context,
1.918     raeburn  9695:                                                 },
                   9696:                     };
1.921     raeburn  9697:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      9698: # set toplevel url
1.271     www      9699:     my $topurl=$url;
                   9700:     unless ($nonstandard) {
                   9701: # ------------------------------------------ For standard courses, make top url
                   9702:         my $mapurl=&clutter($url);
1.278     www      9703:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 9704:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      9705: <map>
                   9706: <resource id="1" type="start"></resource>
                   9707: <resource id="2" src="$mapurl"></resource>
                   9708: <resource id="3" type="finish"></resource>
                   9709: <link index="1" from="1" to="2"></link>
                   9710: <link index="2" from="2" to="3"></link>
                   9711: </map>
                   9712: ENDINITMAP
                   9713:         $topurl=&declutter(
1.638     albertel 9714:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      9715:                           );
                   9716:     }
                   9717: # ----------------------------------------------------------- Write preferences
1.84      www      9718:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  9719:                      ('description'              => $description,
                   9720:                       'url'                      => $topurl,
                   9721:                       'internal.creator'         => $env{'user.name'}.':'.
                   9722:                                                     $env{'user.domain'},
                   9723:                       'internal.created'         => $now,
                   9724:                       'internal.creationcontext' => $context)
                   9725:                     );
1.84      www      9726:     return '/'.$udom.'/'.$uname;
                   9727: }
                   9728: 
1.1011    raeburn  9729: # ------------------------------------------------------------------- Create ID
                   9730: sub generate_coursenum {
1.1038    raeburn  9731:     my ($udom,$crstype) = @_;
1.1011    raeburn  9732:     my $domdesc = &domain($udom);
                   9733:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  9734:     my $first;
                   9735:     if ($crstype eq 'Community') {
                   9736:         $first = '0';
                   9737:     } else {
                   9738:         $first = int(1+rand(9)); 
                   9739:     } 
                   9740:     my $uname=$first.
1.1011    raeburn  9741:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9742:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9743:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9744: # ----------------------------------------------- Make sure that does not exist
                   9745:     my $uhome=&homeserver($uname,$udom,'true');
                   9746:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  9747:         if ($crstype eq 'Community') {
                   9748:             $first = '0';
                   9749:         } else {
                   9750:             $first = int(1+rand(9));
                   9751:         }
                   9752:         $uname=$first.
1.1011    raeburn  9753:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9754:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9755:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9756:         $uhome=&homeserver($uname,$udom,'true');
                   9757:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   9758:             return 'error: unable to generate unique course-ID';
                   9759:         }
                   9760:     }
                   9761:     return $uname;
                   9762: }
                   9763: 
1.813     albertel 9764: sub is_course {
1.1167    droeschl 9765:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   9766:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  9767:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   9768:     my $uhome=&homeserver($cnum,$cdom);
                   9769:     my $iscourse;
                   9770:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   9771:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   9772:     } else {
                   9773:         my $hashid = $cdom.':'.$cnum;
                   9774:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   9775:         unless (defined($cached)) {
                   9776:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   9777:                                         $cnum,undef,undef,'.');
                   9778:             $iscourse = 0;
                   9779:             if (exists($courses{$cdom.'_'.$cnum})) {
                   9780:                 $iscourse = 1;
                   9781:             }
                   9782:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   9783:         }
                   9784:     }
                   9785:     return unless($iscourse);
1.1167    droeschl 9786:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 9787: }
                   9788: 
1.1015    raeburn  9789: sub store_userdata {
                   9790:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  9791:     my $result;
1.1016    raeburn  9792:     if ($datakey ne '') {
1.1013    raeburn  9793:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  9794:             if ($udom eq '' || $uname eq '') {
                   9795:                 $udom = $env{'user.domain'};
                   9796:                 $uname = $env{'user.name'};
                   9797:             }
                   9798:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  9799:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   9800:                 $result = 'error: no_host';
                   9801:             } else {
                   9802:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   9803:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   9804: 
                   9805:                 my $namevalue='';
                   9806:                 foreach my $key (keys(%{$storehash})) {
                   9807:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   9808:                 }
                   9809:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  9810:                 unless ($namespace eq 'courserequests') {
                   9811:                     $datakey = &escape($datakey);
                   9812:                 }
1.1105    raeburn  9813:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   9814:                                   $namevalue,$uhome);
1.1013    raeburn  9815:             }
                   9816:         } else {
                   9817:             $result = 'error: data to store was not a hash reference'; 
                   9818:         }
                   9819:     } else {
                   9820:         $result= 'error: invalid requestkey'; 
                   9821:     }
                   9822:     return $result;
                   9823: }
                   9824: 
1.21      www      9825: # ---------------------------------------------------------- Assign Custom Role
                   9826: 
                   9827: sub assigncustomrole {
1.957     raeburn  9828:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9829:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  9830:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      9831: }
                   9832: 
                   9833: # ----------------------------------------------------------------- Revoke Role
                   9834: 
                   9835: sub revokerole {
1.957     raeburn  9836:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9837:     my $now=time;
1.965     raeburn  9838:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      9839: }
                   9840: 
                   9841: # ---------------------------------------------------------- Revoke Custom Role
                   9842: 
                   9843: sub revokecustomrole {
1.957     raeburn  9844:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9845:     my $now=time;
1.357     www      9846:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  9847:            $deleteflag,$selfenroll,$context);
1.17      www      9848: }
                   9849: 
1.533     banghart 9850: # ------------------------------------------------------------ Disk usage
1.535     albertel 9851: sub diskusage {
1.955     raeburn  9852:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   9853:     $directorypath =~ s/\/$//;
                   9854:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   9855:                        .&escape($getpropath).':'.&escape($uname).':'
                   9856:                        .&escape($udom),homeserver($uname,$udom));
                   9857:     if ($listing eq 'unknown_cmd') {
                   9858:         if ($getpropath) {
                   9859:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   9860:         }
                   9861:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   9862:     }
1.514     albertel 9863:     return $listing;
1.512     banghart 9864: }
                   9865: 
1.566     banghart 9866: sub is_locked {
1.1096    raeburn  9867:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 9868:     my @check;
                   9869:     my $is_locked;
1.1093    raeburn  9870:     push (@check,$file_name);
1.613     albertel 9871:     my %locked = &get('file_permissions',\@check,
1.620     albertel 9872: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 9873:     my ($tmp)=keys(%locked);
                   9874:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  9875:     
1.566     banghart 9876:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  9877:         $is_locked = 'false';
                   9878:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  9879:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  9880:                $is_locked = 'true';
1.1096    raeburn  9881:                if (ref($which) eq 'ARRAY') {
                   9882:                    push(@{$which},$entry);
                   9883:                } else {
                   9884:                    last;
                   9885:                }
1.745     raeburn  9886:            }
                   9887:        }
1.566     banghart 9888:     } else {
                   9889:         $is_locked = 'false';
                   9890:     }
1.1093    raeburn  9891:     return $is_locked;
1.566     banghart 9892: }
                   9893: 
1.759     albertel 9894: sub declutter_portfile {
                   9895:     my ($file) = @_;
1.833     albertel 9896:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 9897:     return $file;
                   9898: }
                   9899: 
1.559     banghart 9900: # ------------------------------------------------------------- Mark as Read Only
                   9901: 
                   9902: sub mark_as_readonly {
                   9903:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 9904:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9905:     my ($tmp)=keys(%current_permissions);
                   9906:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 9907:     foreach my $file (@{$files}) {
1.759     albertel 9908: 	$file = &declutter_portfile($file);
1.561     banghart 9909:         push(@{$current_permissions{$file}},$what);
1.559     banghart 9910:     }
1.613     albertel 9911:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9912:     return;
                   9913: }
                   9914: 
1.572     banghart 9915: # ------------------------------------------------------------Save Selected Files
                   9916: 
                   9917: sub save_selected_files {
                   9918:     my ($user, $path, @files) = @_;
                   9919:     my $filename = $user."savedfiles";
1.573     banghart 9920:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  9921:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 9922:     foreach my $file (@files) {
1.620     albertel 9923:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 9924:     }
                   9925:     foreach my $file (@other_files) {
1.574     banghart 9926:         print (OUT $file."\n");
1.572     banghart 9927:     }
1.574     banghart 9928:     close (OUT);
1.572     banghart 9929:     return 'ok';
                   9930: }
                   9931: 
1.574     banghart 9932: sub clear_selected_files {
                   9933:     my ($user) = @_;
                   9934:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  9935:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 9936:     print (OUT undef);
                   9937:     close (OUT);
                   9938:     return ("ok");    
                   9939: }
                   9940: 
1.572     banghart 9941: sub files_in_path {
                   9942:     my ($user, $path) = @_;
                   9943:     my $filename = $user."savedfiles";
                   9944:     my %return_files;
1.1172.2.96  raeburn  9945:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 9946:     while (my $line_in = <IN>) {
1.574     banghart 9947:         chomp ($line_in);
                   9948:         my @paths_and_file = split (m!/!, $line_in);
                   9949:         my $file_part = pop (@paths_and_file);
                   9950:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9951:         $path_part.='/';
                   9952:         my $path_and_file = $path_part.$file_part;
                   9953:         if ($path_part eq $path) {
                   9954:             $return_files{$file_part}= 'selected';
                   9955:         }
                   9956:     }
1.574     banghart 9957:     close (IN);
                   9958:     return (\%return_files);
1.572     banghart 9959: }
                   9960: 
                   9961: # called in portfolio select mode, to show files selected NOT in current directory
                   9962: sub files_not_in_path {
                   9963:     my ($user, $path) = @_;
                   9964:     my $filename = $user."savedfiles";
                   9965:     my @return_files;
                   9966:     my $path_part;
1.1172.2.96  raeburn  9967:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 9968:     while (my $line = <IN>) {
1.572     banghart 9969:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9970:         my @paths_and_file = split(m|/|, $line);
                   9971:         my $file_part = pop(@paths_and_file);
                   9972:         chomp($file_part);
                   9973:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9974:         $path_part .= '/';
                   9975:         my $path_and_file = $path_part.$file_part;
                   9976:         if ($path_part ne $path) {
1.800     albertel 9977:             push(@return_files, ($path_and_file));
1.572     banghart 9978:         }
                   9979:     }
1.800     albertel 9980:     close(OUT);
1.574     banghart 9981:     return (@return_files);
1.572     banghart 9982: }
                   9983: 
1.745     raeburn  9984: #----------------------------------------------Get portfolio file permissions
1.629     banghart 9985: 
1.745     raeburn  9986: sub get_portfile_permissions {
                   9987:     my ($domain,$user) = @_;
1.613     albertel 9988:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9989:     my ($tmp)=keys(%current_permissions);
                   9990:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9991:     return \%current_permissions;
                   9992: }
                   9993: 
                   9994: #---------------------------------------------Get portfolio file access controls
                   9995: 
1.749     raeburn  9996: sub get_access_controls {
1.745     raeburn  9997:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 9998:     my %access;
                   9999:     my $real_file = $file;
                   10000:     $file =~ s/\.meta$//;
1.745     raeburn  10001:     if (defined($file)) {
1.749     raeburn  10002:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10003:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10004:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10005:             }
                   10006:         }
1.745     raeburn  10007:     } else {
1.749     raeburn  10008:         foreach my $key (keys(%{$current_permissions})) {
                   10009:             if ($key =~ /\0accesscontrol$/) {
                   10010:                 if (defined($group)) {
                   10011:                     if ($key !~ m-^\Q$group\E/-) {
                   10012:                         next;
                   10013:                     }
                   10014:                 }
                   10015:                 my ($fullpath) = split(/\0/,$key);
                   10016:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10017:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10018:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10019:                     }
                   10020:                 }
                   10021:             }
                   10022:         }
                   10023:     }
                   10024:     return %access;
                   10025: }
                   10026: 
                   10027: sub modify_access_controls {
                   10028:     my ($file_name,$changes,$domain,$user)=@_;
                   10029:     my ($outcome,$deloutcome);
                   10030:     my %store_permissions;
                   10031:     my %new_values;
                   10032:     my %new_control;
                   10033:     my %translation;
                   10034:     my @deletions = ();
                   10035:     my $now = time;
                   10036:     if (exists($$changes{'activate'})) {
                   10037:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10038:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10039:             my $numnew = scalar(@newitems);
                   10040:             for (my $i=0; $i<$numnew; $i++) {
                   10041:                 my $newkey = $newitems[$i];
                   10042:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10043:                 if ($newkey =~ /^\d+:/) { 
                   10044:                     $newkey =~ s/^(\d+)/$newid/;
                   10045:                     $translation{$1} = $newid;
                   10046:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10047:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10048:                     $translation{$1} = $newid;
                   10049:                 }
1.749     raeburn  10050:                 $new_values{$file_name."\0".$newkey} = 
                   10051:                                           $$changes{'activate'}{$newitems[$i]};
                   10052:                 $new_control{$newkey} = $now;
                   10053:             }
                   10054:         }
                   10055:     }
                   10056:     my %todelete;
                   10057:     my %changed_items;
                   10058:     foreach my $action ('delete','update') {
                   10059:         if (exists($$changes{$action})) {
                   10060:             if (ref($$changes{$action}) eq 'HASH') {
                   10061:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10062:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10063:                     if ($action eq 'delete') { 
                   10064:                         $todelete{$itemnum} = 1;
                   10065:                     } else {
                   10066:                         $changed_items{$itemnum} = $key;
                   10067:                     }
                   10068:                 }
1.745     raeburn  10069:             }
                   10070:         }
1.749     raeburn  10071:     }
                   10072:     # get lock on access controls for file.
                   10073:     my $lockhash = {
                   10074:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10075:                                                        ':'.$env{'user.domain'},
                   10076:                    }; 
                   10077:     my $tries = 0;
                   10078:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10079:    
1.1172.2.79  raeburn  10080:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10081:         $tries ++;
1.1172.2.79  raeburn  10082:         sleep(0.1);
1.749     raeburn  10083:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10084:     }
                   10085:     if ($gotlock eq 'ok') {
                   10086:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10087:         my ($tmp)=keys(%curr_permissions);
                   10088:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10089:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10090:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10091:             if (ref($curr_controls) eq 'HASH') {
                   10092:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10093:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10094:                     if (defined($todelete{$itemnum})) {
                   10095:                         push(@deletions,$file_name."\0".$control_item);
                   10096:                     } else {
                   10097:                         if (defined($changed_items{$itemnum})) {
                   10098:                             $new_control{$changed_items{$itemnum}} = $now;
                   10099:                             push(@deletions,$file_name."\0".$control_item);
                   10100:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10101:                         } else {
                   10102:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10103:                         }
                   10104:                     }
1.745     raeburn  10105:                 }
                   10106:             }
                   10107:         }
1.970     raeburn  10108:         my ($group);
                   10109:         if (&is_course($domain,$user)) {
                   10110:             ($group,my $file) = split(/\//,$file_name,2);
                   10111:         }
1.749     raeburn  10112:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10113:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10114:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10115:         #  remove lock
                   10116:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10117:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10118:         my $sqlresult =
1.970     raeburn  10119:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10120:                                     $group);
1.749     raeburn  10121:     } else {
                   10122:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10123:     }
1.749     raeburn  10124:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10125: }
                   10126: 
1.827     raeburn  10127: sub make_public_indefinitely {
                   10128:     my ($requrl) = @_;
                   10129:     my $now = time;
                   10130:     my $action = 'activate';
                   10131:     my $aclnum = 0;
                   10132:     if (&is_portfolio_url($requrl)) {
                   10133:         my (undef,$udom,$unum,$file_name,$group) =
                   10134:             &parse_portfolio_url($requrl);
                   10135:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   10136:         my %access_controls = &get_access_controls($current_perms,
                   10137:                                                    $group,$file_name);
                   10138:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10139:             my ($num,$scope,$end,$start) = 
                   10140:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   10141:             if ($scope eq 'public') {
                   10142:                 if ($start <= $now && $end == 0) {
                   10143:                     $action = 'none';
                   10144:                 } else {
                   10145:                     $action = 'update';
                   10146:                     $aclnum = $num;
                   10147:                 }
                   10148:                 last;
                   10149:             }
                   10150:         }
                   10151:         if ($action eq 'none') {
                   10152:              return 'ok';
                   10153:         } else {
                   10154:             my %changes;
                   10155:             my $newend = 0;
                   10156:             my $newstart = $now;
                   10157:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   10158:             $changes{$action}{$newkey} = {
                   10159:                 type => 'public',
                   10160:                 time => {
                   10161:                     start => $newstart,
                   10162:                     end   => $newend,
                   10163:                 },
                   10164:             };
                   10165:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10166:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   10167:             return $outcome;
                   10168:         }
                   10169:     } else {
                   10170:         return 'invalid';
                   10171:     }
                   10172: }
                   10173: 
1.745     raeburn  10174: #------------------------------------------------------Get Marked as Read Only
                   10175: 
                   10176: sub get_marked_as_readonly {
                   10177:     my ($domain,$user,$what,$group) = @_;
                   10178:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10179:     my @readonly_files;
1.629     banghart 10180:     my $cmp1=$what;
                   10181:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10182:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10183:         if (defined($group)) {
                   10184:             if ($file_name !~ m-^\Q$group\E/-) {
                   10185:                 next;
                   10186:             }
                   10187:         }
1.561     banghart 10188:         if (ref($value) eq "ARRAY"){
                   10189:             foreach my $stored_what (@{$value}) {
1.629     banghart 10190:                 my $cmp2=$stored_what;
1.759     albertel 10191:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10192:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10193:                 }
1.629     banghart 10194:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10195:                     push(@readonly_files, $file_name);
1.745     raeburn  10196:                     last;
1.563     banghart 10197:                 } elsif (!defined($what)) {
                   10198:                     push(@readonly_files, $file_name);
1.745     raeburn  10199:                     last;
1.561     banghart 10200:                 }
                   10201:             }
1.745     raeburn  10202:         }
1.561     banghart 10203:     }
                   10204:     return @readonly_files;
                   10205: }
1.577     banghart 10206: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10207: 
1.577     banghart 10208: sub get_marked_as_readonly_hash {
1.745     raeburn  10209:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10210:     my %readonly_files;
1.745     raeburn  10211:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10212:         if (defined($group)) {
                   10213:             if ($file_name !~ m-^\Q$group\E/-) {
                   10214:                 next;
                   10215:             }
                   10216:         }
1.577     banghart 10217:         if (ref($value) eq "ARRAY"){
                   10218:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10219:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10220:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10221:                         if ($lock_descriptor eq 'graded') {
                   10222:                             $readonly_files{$file_name} = 'graded';
                   10223:                         } elsif ($lock_descriptor eq 'handback') {
                   10224:                             $readonly_files{$file_name} = 'handback';
                   10225:                         } else {
                   10226:                             if (!exists($readonly_files{$file_name})) {
                   10227:                                 $readonly_files{$file_name} = 'locked';
                   10228:                             }
                   10229:                         }
1.745     raeburn  10230:                     }
1.750     banghart 10231:                 } 
1.577     banghart 10232:             }
                   10233:         } 
                   10234:     }
                   10235:     return %readonly_files;
                   10236: }
1.559     banghart 10237: # ------------------------------------------------------------ Unmark as Read Only
                   10238: 
                   10239: sub unmark_as_readonly {
1.629     banghart 10240:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10241:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10242:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10243:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10244:     my $symb_crs = $what;
                   10245:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10246:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10247:     my ($tmp)=keys(%current_permissions);
                   10248:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10249:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10250:     foreach my $file (@readonly_files) {
1.759     albertel 10251: 	my $clean_file = &declutter_portfile($file);
                   10252: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10253: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10254:         my @new_locks;
                   10255:         my @del_keys;
                   10256:         if (ref($current_locks) eq "ARRAY"){
                   10257:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10258:                 my $compare=$locker;
1.749     raeburn  10259:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10260:                     $compare=join('',@{$locker});
1.746     raeburn  10261:                     if ($compare ne $symb_crs) {
                   10262:                         push(@new_locks, $locker);
                   10263:                     }
1.563     banghart 10264:                 }
                   10265:             }
1.650     albertel 10266:             if (scalar(@new_locks) > 0) {
1.563     banghart 10267:                 $current_permissions{$file} = \@new_locks;
                   10268:             } else {
                   10269:                 push(@del_keys, $file);
1.613     albertel 10270:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10271:                 delete($current_permissions{$file});
1.563     banghart 10272:             }
                   10273:         }
1.561     banghart 10274:     }
1.613     albertel 10275:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10276:     return;
                   10277: }
1.512     banghart 10278: 
1.17      www      10279: # ------------------------------------------------------------ Directory lister
                   10280: 
                   10281: sub dirlist {
1.955     raeburn  10282:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10283:     $uri=~s/^\///;
                   10284:     $uri=~s/\/$//;
1.253     stredwic 10285:     my ($udom, $uname);
1.955     raeburn  10286:     if ($getuserdir) {
1.253     stredwic 10287:         $udom = $userdomain;
                   10288:         $uname = $username;
1.955     raeburn  10289:     } else {
                   10290:         (undef,$udom,$uname)=split(/\//,$uri);
                   10291:         if(defined($userdomain)) {
                   10292:             $udom = $userdomain;
                   10293:         }
                   10294:         if(defined($username)) {
                   10295:             $uname = $username;
                   10296:         }
1.253     stredwic 10297:     }
1.955     raeburn  10298:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10299: 
1.955     raeburn  10300:     $dirRoot = $perlvar{'lonDocRoot'};
                   10301:     if (defined($getpropath)) {
                   10302:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10303:         $dirRoot =~ s/\/$//;
1.955     raeburn  10304:     } elsif (defined($getuserdir)) {
                   10305:         my $subdir=$uname.'__';
                   10306:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10307:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10308:                    ."/$udom/$subdir/$uname";
                   10309:     } elsif (defined($alternateRoot)) {
                   10310:         $dirRoot = $alternateRoot;
1.751     banghart 10311:     }
1.253     stredwic 10312: 
                   10313:     if($udom) {
                   10314:         if($uname) {
1.1135    raeburn  10315:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10316:             if ($uhome eq 'no_host') {
                   10317:                 return ([],'no_host');
                   10318:             }
1.955     raeburn  10319:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10320:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10321:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10322:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10323:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10324:             } else {
                   10325:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10326:             }
1.605     matthew  10327:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10328:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10329:                 @listing_results = split(/:/,$listing);
                   10330:             } else {
                   10331:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10332:             }
1.1135    raeburn  10333:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10334:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10335:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10336:                 return ([],$listing);
                   10337:             } else {
                   10338:                 return (\@listing_results);
1.1135    raeburn  10339:             }
1.955     raeburn  10340:         } elsif(!$alternateRoot) {
1.1136    raeburn  10341:             my (%allusers,%listerror);
1.841     albertel 10342: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10343:  	    foreach my $tryserver (keys(%servers)) {
                   10344:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10345:                                   &escape($udom),$tryserver);
                   10346:                 if ($listing eq 'unknown_cmd') {
                   10347: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10348: 				      $udom, $tryserver);
                   10349:                 } else {
                   10350:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10351:                 }
1.841     albertel 10352: 		if ($listing eq 'unknown_cmd') {
                   10353: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10354: 				      $udom, $tryserver);
                   10355: 		    @listing_results = split(/:/,$listing);
                   10356: 		} else {
                   10357: 		    @listing_results =
                   10358: 			map { &unescape($_); } split(/:/,$listing);
                   10359: 		}
1.1136    raeburn  10360:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10361:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10362:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10363:                     $listerror{$tryserver} = $listing;
                   10364:                 } else {
1.841     albertel 10365: 		    foreach my $line (@listing_results) {
                   10366: 			my ($entry) = split(/&/,$line,2);
                   10367: 			$allusers{$entry} = 1;
                   10368: 		    }
                   10369: 		}
1.253     stredwic 10370:             }
1.1136    raeburn  10371:             my @alluserslist=();
1.800     albertel 10372:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10373:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10374:             }
1.1172.2.80  raeburn  10375:             if (!%listerror) {
                   10376:                 # no errors
                   10377:                 return (\@alluserslist);
                   10378:             } elsif (scalar(keys(%servers)) == 1) {
                   10379:                 # one library server, one error
                   10380:                 my ($key) = keys(%listerror);
                   10381:                 return (\@alluserslist, $listerror{$key});
                   10382:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10383:                 # con_lost indicates that we might miss data from at least one
                   10384:                 # library server
                   10385:                 return (\@alluserslist, 'con_lost');
                   10386:             } else {
                   10387:                 # multiple library servers and no con_lost -> data should be
                   10388:                 # complete.
                   10389:                 return (\@alluserslist);
                   10390:             }
                   10391: 
1.253     stredwic 10392:         } else {
1.1136    raeburn  10393:             return ([],'missing username');
1.253     stredwic 10394:         }
1.955     raeburn  10395:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10396:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10397:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10398:         return (\@all_domains);
1.955     raeburn  10399:     } else {
1.1136    raeburn  10400:         return ([],'missing domain');
1.275     stredwic 10401:     }
                   10402: }
                   10403: 
                   10404: # --------------------------------------------- GetFileTimestamp
                   10405: # This function utilizes dirlist and returns the date stamp for
                   10406: # when it was last modified.  It will also return an error of -1
                   10407: # if an error occurs
                   10408: 
                   10409: sub GetFileTimestamp {
1.955     raeburn  10410:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10411:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10412:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10413:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10414:                                     undef,$getuserdir);
                   10415:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10416:         return -1;
                   10417:     }
                   10418:     if (ref($fileref) eq 'ARRAY') {
                   10419:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10420:         # @stats contains first the filename, then the stat output
                   10421:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10422:     } else {
                   10423:         return -1;
1.253     stredwic 10424:     }
1.26      www      10425: }
                   10426: 
1.712     albertel 10427: sub stat_file {
                   10428:     my ($uri) = @_;
1.787     albertel 10429:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10430: 
1.955     raeburn  10431:     my ($udom,$uname,$file);
1.712     albertel 10432:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10433: 	($udom,$uname,$file) =
1.811     albertel 10434: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10435: 	$file = 'userfiles/'.$file;
                   10436:     }
                   10437:     if ($uri =~ m-^/res/-) {
                   10438: 	($udom,$uname) = 
1.807     albertel 10439: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10440: 	$file = $uri;
                   10441:     }
                   10442: 
                   10443:     if (!$udom || !$uname || !$file) {
                   10444: 	# unable to handle the uri
                   10445: 	return ();
                   10446:     }
1.956     raeburn  10447:     my $getpropath;
                   10448:     if ($file =~ /^userfiles\//) {
                   10449:         $getpropath = 1;
                   10450:     }
1.1136    raeburn  10451:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10452:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10453:         return ();
                   10454:     } else {
                   10455:         if (ref($listref) eq 'ARRAY') {
                   10456:             my @stats = split('&',$listref->[0]);
                   10457: 	    shift(@stats); #filename is first
                   10458: 	    return @stats;
                   10459:         }
1.712     albertel 10460:     }
                   10461:     return ();
                   10462: }
                   10463: 
1.26      www      10464: # -------------------------------------------------------- Value of a Condition
                   10465: 
1.713     albertel 10466: # gets the value of a specific preevaluated condition
                   10467: #    stored in the string  $env{user.state.<cid>}
                   10468: # or looks up a condition reference in the bighash and if if hasn't
                   10469: # already been evaluated recurses into docondval to get the value of
                   10470: # the condition, then memoizing it to 
                   10471: #   $env{user.state.<cid>.<condition>}
1.40      www      10472: sub directcondval {
                   10473:     my $number=shift;
1.620     albertel 10474:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 10475: 	&Apache::lonuserstate::evalstate();
                   10476:     }
1.713     albertel 10477:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   10478: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   10479:     } elsif ($number =~ /^_/) {
                   10480: 	my $sub_condition;
                   10481: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10482: 		&GDBM_READER(),0640)) {
                   10483: 	    $sub_condition=$bighash{'conditions'.$number};
                   10484: 	    untie(%bighash);
                   10485: 	}
                   10486: 	my $value = &docondval($sub_condition);
1.949     raeburn  10487: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 10488: 	return $value;
                   10489:     }
1.620     albertel 10490:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   10491:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      10492:     } else {
                   10493:        return 2;
                   10494:     }
                   10495: }
                   10496: 
1.713     albertel 10497: # get the collection of conditions for this resource
1.26      www      10498: sub condval {
                   10499:     my $condidx=shift;
1.54      www      10500:     my $allpathcond='';
1.713     albertel 10501:     foreach my $cond (split(/\|/,$condidx)) {
                   10502: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   10503: 	    $allpathcond.=
                   10504: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   10505: 	}
1.191     harris41 10506:     }
1.54      www      10507:     $allpathcond=~s/\|$//;
1.713     albertel 10508:     return &docondval($allpathcond);
                   10509: }
                   10510: 
                   10511: #evaluates an expression of conditions
                   10512: sub docondval {
                   10513:     my ($allpathcond) = @_;
                   10514:     my $result=0;
                   10515:     if ($env{'request.course.id'}
                   10516: 	&& defined($allpathcond)) {
                   10517: 	my $operand='|';
                   10518: 	my @stack;
                   10519: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   10520: 	    if ($chunk eq '(') {
                   10521: 		push @stack,($operand,$result);
                   10522: 	    } elsif ($chunk eq ')') {
                   10523: 		my $before=pop @stack;
                   10524: 		if (pop @stack eq '&') {
                   10525: 		    $result=$result>$before?$before:$result;
                   10526: 		} else {
                   10527: 		    $result=$result>$before?$result:$before;
                   10528: 		}
                   10529: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   10530: 		$operand=$chunk;
                   10531: 	    } else {
                   10532: 		my $new=directcondval($chunk);
                   10533: 		if ($operand eq '&') {
                   10534: 		    $result=$result>$new?$new:$result;
                   10535: 		} else {
                   10536: 		    $result=$result>$new?$result:$new;
                   10537: 		}
                   10538: 	    }
                   10539: 	}
1.26      www      10540:     }
                   10541:     return $result;
1.421     albertel 10542: }
                   10543: 
                   10544: # ---------------------------------------------------- Devalidate courseresdata
                   10545: 
                   10546: sub devalidatecourseresdata {
                   10547:     my ($coursenum,$coursedomain)=@_;
                   10548:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10549:     &devalidate_cache_new('courseres',$hashid);
1.28      www      10550: }
                   10551: 
1.763     www      10552: 
1.200     www      10553: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     10554: #
                   10555: #  Parameters:
                   10556: #      $coursenum    - Number of the course.
                   10557: #      $coursedomain - Domain at which the course was created.
                   10558: #  Returns:
                   10559: #     A hash of the course parameters along (I think) with timestamps
                   10560: #     and version info.
1.877     foxr     10561: 
1.624     albertel 10562: sub get_courseresdata {
                   10563:     my ($coursenum,$coursedomain)=@_;
1.200     www      10564:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   10565:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10566:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 10567:     my %dumpreply;
1.417     albertel 10568:     unless (defined($cached)) {
1.624     albertel 10569: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 10570: 	$result=\%dumpreply;
1.251     albertel 10571: 	my ($tmp) = keys(%dumpreply);
                   10572: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 10573: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 10574: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   10575: 	    return $tmp;
1.416     albertel 10576: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 10577: 	    $result=undef;
1.599     albertel 10578: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 10579: 	}
                   10580:     }
1.624     albertel 10581:     return $result;
                   10582: }
                   10583: 
1.633     albertel 10584: sub devalidateuserresdata {
                   10585:     my ($uname,$udom)=@_;
                   10586:     my $hashid="$udom:$uname";
                   10587:     &devalidate_cache_new('userres',$hashid);
                   10588: }
                   10589: 
1.624     albertel 10590: sub get_userresdata {
                   10591:     my ($uname,$udom)=@_;
                   10592:     #most student don\'t have any data set, check if there is some data
                   10593:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   10594: 
                   10595:     my $hashid="$udom:$uname";
                   10596:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   10597:     if (!defined($cached)) {
                   10598: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   10599: 	$result=\%resourcedata;
                   10600: 	&do_cache_new('userres',$hashid,$result,600);
                   10601:     }
                   10602:     my ($tmp)=keys(%$result);
                   10603:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   10604: 	return $result;
                   10605:     }
                   10606:     #error 2 occurs when the .db doesn't exist
                   10607:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  10608:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   10609: 	    &logthis("<font color=\"blue\">WARNING:".
                   10610: 		     " Trying to get resource data for ".
                   10611: 		     $uname." at ".$udom.": ".
                   10612: 		     $tmp."</font>");
                   10613:         }
1.624     albertel 10614:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 10615: 	#&EXT_cache_set($udom,$uname);
                   10616: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 10617: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 10618:     }
                   10619:     return $tmp;
                   10620: }
1.879     foxr     10621: #----------------------------------------------- resdata - return resource data
                   10622: #  Purpose:
                   10623: #    Return resource data for either users or for a course.
                   10624: #  Parameters:
                   10625: #     $name      - Course/user name.
                   10626: #     $domain    - Name of the domain the user/course is registered on.
                   10627: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   10628: #     @which     - Array of names of resources desired.
                   10629: #  Returns:
                   10630: #     The value of the first reasource in @which that is found in the
                   10631: #     resource hash.
                   10632: #  Exceptional Conditions:
                   10633: #     If the $type passed in is not valid (not the string 'course' or 
                   10634: #     'user', an undefined  reference is returned.
                   10635: #     If none of the resources are found, an undef is returned
1.624     albertel 10636: sub resdata {
                   10637:     my ($name,$domain,$type,@which)=@_;
                   10638:     my $result;
                   10639:     if ($type eq 'course') {
                   10640: 	$result=&get_courseresdata($name,$domain);
                   10641:     } elsif ($type eq 'user') {
                   10642: 	$result=&get_userresdata($name,$domain);
                   10643:     }
                   10644:     if (!ref($result)) { return $result; }    
1.251     albertel 10645:     foreach my $item (@which) {
1.927     albertel 10646: 	if (defined($result->{$item->[0]})) {
                   10647: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 10648: 	}
1.250     albertel 10649:     }
1.291     albertel 10650:     return undef;
1.200     www      10651: }
                   10652: 
1.1172.2.31  raeburn  10653: sub get_numsuppfiles {
                   10654:     my ($cnum,$cdom,$ignorecache)=@_;
                   10655:     my $hashid=$cnum.':'.$cdom;
                   10656:     my ($suppcount,$cached);
                   10657:     unless ($ignorecache) {
                   10658:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   10659:     }
                   10660:     unless (defined($cached)) {
                   10661:         my $chome=&homeserver($cnum,$cdom);
                   10662:         unless ($chome eq 'no_host') {
                   10663:             ($suppcount,my $errors) = (0,0);
                   10664:             my $suppmap = 'supplemental.sequence';
                   10665:             ($suppcount,$errors) =
                   10666:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   10667:         }
                   10668:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   10669:     }
                   10670:     return $suppcount;
                   10671: }
                   10672: 
1.379     matthew  10673: #
                   10674: # EXT resource caching routines
                   10675: #
                   10676: 
                   10677: sub clear_EXT_cache_status {
1.383     albertel 10678:     &delenv('cache.EXT.');
1.379     matthew  10679: }
                   10680: 
                   10681: sub EXT_cache_status {
                   10682:     my ($target_domain,$target_user) = @_;
1.383     albertel 10683:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 10684:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  10685:         # We know already the user has no data
                   10686:         return 1;
                   10687:     } else {
                   10688:         return 0;
                   10689:     }
                   10690: }
                   10691: 
                   10692: sub EXT_cache_set {
                   10693:     my ($target_domain,$target_user) = @_;
1.383     albertel 10694:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  10695:     #&appenv({$cachename => time});
1.379     matthew  10696: }
                   10697: 
1.28      www      10698: # --------------------------------------------------------- Value of a Variable
1.58      www      10699: sub EXT {
1.715     albertel 10700: 
1.1172.2.28  raeburn  10701:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      10702:     unless ($varname) { return ''; }
1.218     albertel 10703:     #get real user name/domain, courseid and symb
                   10704:     my $courseid;
1.359     albertel 10705:     my $publicuser;
1.427     www      10706:     if ($symbparm) {
                   10707: 	$symbparm=&get_symb_from_alias($symbparm);
                   10708:     }
1.218     albertel 10709:     if (!($uname && $udom)) {
1.790     albertel 10710:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 10711:       if (!$symbparm) {	$symbparm=$cursymb; }
                   10712:     } else {
1.620     albertel 10713: 	$courseid=$env{'request.course.id'};
1.218     albertel 10714:     }
1.48      www      10715:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   10716:     my $rest;
1.320     albertel 10717:     if (defined($therest[0])) {
1.48      www      10718:        $rest=join('.',@therest);
                   10719:     } else {
                   10720:        $rest='';
                   10721:     }
1.320     albertel 10722: 
1.57      www      10723:     my $qualifierrest=$qualifier;
                   10724:     if ($rest) { $qualifierrest.='.'.$rest; }
                   10725:     my $spacequalifierrest=$space;
                   10726:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      10727:     if ($realm eq 'user') {
1.48      www      10728: # --------------------------------------------------------------- user.resource
                   10729: 	if ($space eq 'resource') {
1.651     albertel 10730: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   10731: 		  || defined($Apache::lonhomework::parsing_a_task))
                   10732: 		 &&
1.744     albertel 10733: 		 ($symbparm eq &symbread()) ) {	
                   10734: 		# if we are in the middle of processing the resource the
                   10735: 		# get the value we are planning on committing
                   10736:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   10737:                     return $Apache::lonhomework::results{$qualifierrest};
                   10738:                 } else {
                   10739:                     return $Apache::lonhomework::history{$qualifierrest};
                   10740:                 }
1.335     albertel 10741: 	    } else {
1.359     albertel 10742: 		my %restored;
1.620     albertel 10743: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 10744: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   10745: 		} else {
                   10746: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   10747: 		}
1.335     albertel 10748: 		return $restored{$qualifierrest};
                   10749: 	    }
1.48      www      10750: # ----------------------------------------------------------------- user.access
                   10751:         } elsif ($space eq 'access') {
1.218     albertel 10752: 	    # FIXME - not supporting calls for a specific user
1.48      www      10753:             return &allowed($qualifier,$rest);
                   10754: # ------------------------------------------ user.preferences, user.environment
                   10755:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 10756: 	    if (($uname eq $env{'user.name'}) &&
                   10757: 		($udom eq $env{'user.domain'})) {
                   10758: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 10759: 	    } else {
1.359     albertel 10760: 		my %returnhash;
                   10761: 		if (!$publicuser) {
                   10762: 		    %returnhash=&userenvironment($udom,$uname,
                   10763: 						 $qualifierrest);
                   10764: 		}
1.218     albertel 10765: 		return $returnhash{$qualifierrest};
                   10766: 	    }
1.48      www      10767: # ----------------------------------------------------------------- user.course
                   10768:         } elsif ($space eq 'course') {
1.218     albertel 10769: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10770:             return $env{join('.',('request.course',$qualifier))};
1.48      www      10771: # ------------------------------------------------------------------- user.role
                   10772:         } elsif ($space eq 'role') {
1.218     albertel 10773: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10774:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      10775:             if ($qualifier eq 'value') {
                   10776: 		return $role;
                   10777:             } elsif ($qualifier eq 'extent') {
                   10778:                 return $where;
                   10779:             }
                   10780: # ----------------------------------------------------------------- user.domain
                   10781:         } elsif ($space eq 'domain') {
1.218     albertel 10782:             return $udom;
1.48      www      10783: # ------------------------------------------------------------------- user.name
                   10784:         } elsif ($space eq 'name') {
1.218     albertel 10785:             return $uname;
1.48      www      10786: # ---------------------------------------------------- Any other user namespace
1.29      www      10787:         } else {
1.359     albertel 10788: 	    my %reply;
                   10789: 	    if (!$publicuser) {
                   10790: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   10791: 	    }
                   10792: 	    return $reply{$qualifierrest};
1.48      www      10793:         }
1.236     www      10794:     } elsif ($realm eq 'query') {
                   10795: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 10796:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   10797: 						[$spacequalifierrest]);
1.620     albertel 10798: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      10799:    } elsif ($realm eq 'request') {
1.48      www      10800: # ------------------------------------------------------------- request.browser
                   10801:         if ($space eq 'browser') {
1.1145    bisitz   10802:             return $env{'browser.'.$qualifier};
1.57      www      10803: # ------------------------------------------------------------ request.filename
                   10804:         } else {
1.620     albertel 10805:             return $env{'request.'.$spacequalifierrest};
1.29      www      10806:         }
1.28      www      10807:     } elsif ($realm eq 'course') {
1.48      www      10808: # ---------------------------------------------------------- course.description
1.620     albertel 10809:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      10810:     } elsif ($realm eq 'resource') {
1.165     www      10811: 
1.620     albertel 10812: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 10813: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   10814: 	}
1.693     albertel 10815: 
1.1172.2.30  raeburn  10816:         if ($qualifier eq '') {
                   10817: 	    if ($space eq 'title') {
                   10818: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   10819: 	        return &gettitle($symbparm);
                   10820: 	    }
1.693     albertel 10821: 	
1.1172.2.30  raeburn  10822: 	    if ($space eq 'map') {
                   10823: 	        my ($map) = &decode_symb($symbparm);
                   10824: 	        return &symbread($map);
                   10825: 	    }
                   10826:             if ($space eq 'maptitle') {
                   10827:                 my ($map) = &decode_symb($symbparm);
                   10828:                 return &gettitle($map);
                   10829:             }
                   10830: 	    if ($space eq 'filename') {
                   10831: 	        if ($symbparm) {
                   10832: 		    return &clutter((&decode_symb($symbparm))[2]);
                   10833: 	        }
                   10834: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 10835: 	    }
1.1172.2.30  raeburn  10836: 
                   10837:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   10838:                 if ($space eq 'visibleparts') {
                   10839:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10840:                     my $item;
                   10841:                     if (ref($navmap)) {
                   10842:                         my $res = $navmap->getBySymb($symbparm);
                   10843:                         my $parts = $res->parts();
                   10844:                         if (ref($parts) eq 'ARRAY') {
                   10845:                             $item = join(',',@{$parts});
                   10846:                         }
                   10847:                         undef($navmap);
                   10848:                     }
                   10849:                     return $item;
                   10850:                 }
                   10851:             }
                   10852:         }
1.693     albertel 10853: 
                   10854: 	my ($section, $group, @groups);
1.593     albertel 10855: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  10856:         if (($courseid eq '') && ($cid)) {
                   10857:             $courseid = $cid;
                   10858:         }
                   10859: 	if (($symbparm && $courseid) && 
                   10860: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      10861: 
1.218     albertel 10862: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      10863: 
1.60      www      10864: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 10865: 	    my $symbp=$symbparm;
1.735     albertel 10866: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 10867: 
                   10868: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   10869: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   10870: 
1.620     albertel 10871: 	    if (($env{'user.name'} eq $uname) &&
                   10872: 		($env{'user.domain'} eq $udom)) {
                   10873: 		$section=$env{'request.course.sec'};
1.733     raeburn  10874:                 @groups = split(/:/,$env{'request.course.groups'});  
                   10875:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 10876: 	    } else {
1.539     albertel 10877: 		if (! defined($usection)) {
1.551     albertel 10878: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 10879: 		} else {
                   10880: 		    $section = $usection;
                   10881: 		}
1.733     raeburn  10882:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 10883: 	    }
                   10884: 
                   10885: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   10886: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   10887: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   10888: 
1.593     albertel 10889: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 10890: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 10891: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      10892: 
1.60      www      10893: # ----------------------------------------------------------- first, check user
1.624     albertel 10894: 
                   10895: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 10896: 				       ([$courselevelr,'resource'],
                   10897: 					[$courselevelm,'map'     ],
                   10898: 					[$courselevel, 'course'  ]));
1.931     albertel 10899: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      10900: 
1.594     albertel 10901: # ------------------------------------------------ second, check some of course
1.684     raeburn  10902:             my $coursereply;
1.691     raeburn  10903:             if (@groups > 0) {
                   10904:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   10905:                                        $mapparm,$spacequalifierrest);
1.927     albertel 10906:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  10907:             }
1.96      www      10908: 
1.684     raeburn  10909: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 10910: 				  $env{'course.'.$courseid.'.domain'},
                   10911: 				  'course',
                   10912: 				  ([$seclevelr,   'resource'],
                   10913: 				   [$seclevelm,   'map'     ],
                   10914: 				   [$seclevel,    'course'  ],
                   10915: 				   [$courselevelr,'resource']));
                   10916: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      10917: 
1.60      www      10918: # ------------------------------------------------------ third, check map parms
1.218     albertel 10919: 	    my %parmhash=();
                   10920: 	    my $thisparm='';
                   10921: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 10922: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 10923: 		    &GDBM_READER(),0640)) {
1.218     albertel 10924: 		$thisparm=$parmhash{$symbparm};
                   10925: 		untie(%parmhash);
                   10926: 	    }
1.927     albertel 10927: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 10928: 	}
1.594     albertel 10929: # ------------------------------------------ fourth, look in resource metadata
1.71      www      10930: 
1.218     albertel 10931: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 10932: 	my $filename;
                   10933: 	if (!$symbparm) { $symbparm=&symbread(); }
                   10934: 	if ($symbparm) {
1.409     www      10935: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 10936: 	} else {
1.620     albertel 10937: 	    $filename=$env{'request.filename'};
1.282     albertel 10938: 	}
                   10939: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 10940: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 10941: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 10942: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      10943: 
1.927     albertel 10944: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 10945: 	if ($symbparm && defined($courseid) && 
1.620     albertel 10946: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 10947: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   10948: 				     $env{'course.'.$courseid.'.domain'},
                   10949: 				     'course',
1.927     albertel 10950: 				     ([$courselevelm,'map'   ],
                   10951: 				      [$courselevel, 'course']));
                   10952: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 10953: 	}
1.145     www      10954: # ------------------------------------------------------------------ Cascade up
1.218     albertel 10955: 	unless ($space eq '0') {
1.336     albertel 10956: 	    my @parts=split(/_/,$space);
                   10957: 	    my $id=pop(@parts);
                   10958: 	    my $part=join('_',@parts);
                   10959: 	    if ($part eq '') { $part='0'; }
1.927     albertel 10960: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 10961: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  10962: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 10963: 	}
1.395     albertel 10964: 	if ($recurse) { return undef; }
                   10965: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 10966: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      10967: # ---------------------------------------------------- Any other user namespace
                   10968:     } elsif ($realm eq 'environment') {
                   10969: # ----------------------------------------------------------------- environment
1.620     albertel 10970: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   10971: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 10972: 	} else {
1.770     albertel 10973: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   10974: 		return '';
                   10975: 	    }
1.219     albertel 10976: 	    my %returnhash=&userenvironment($udom,$uname,
                   10977: 					    $spacequalifierrest);
                   10978: 	    return $returnhash{$spacequalifierrest};
                   10979: 	}
1.28      www      10980:     } elsif ($realm eq 'system') {
1.48      www      10981: # ----------------------------------------------------------------- system.time
                   10982: 	if ($space eq 'time') {
                   10983: 	    return time;
                   10984:         }
1.696     albertel 10985:     } elsif ($realm eq 'server') {
                   10986: # ----------------------------------------------------------------- system.time
                   10987: 	if ($space eq 'name') {
                   10988: 	    return $ENV{'SERVER_NAME'};
                   10989:         }
1.28      www      10990:     }
1.48      www      10991:     return '';
1.61      www      10992: }
                   10993: 
1.927     albertel 10994: sub get_reply {
                   10995:     my ($reply_value) = @_;
1.940     raeburn  10996:     if (ref($reply_value) eq 'ARRAY') {
                   10997:         if (wantarray) {
                   10998: 	    return @$reply_value;
                   10999:         }
                   11000:         return $reply_value->[0];
                   11001:     } else {
                   11002:         return $reply_value;
1.927     albertel 11003:     }
                   11004: }
                   11005: 
1.691     raeburn  11006: sub check_group_parms {
                   11007:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   11008:     my @groupitems = ();
                   11009:     my $resultitem;
1.927     albertel 11010:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  11011:     foreach my $group (@{$groups}) {
                   11012:         foreach my $level (@levels) {
1.927     albertel 11013:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11014:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11015:         }
                   11016:     }
                   11017:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11018:                             $env{'course.'.$courseid.'.domain'},
                   11019:                                      'course',@groupitems);
                   11020:     return $coursereply;
                   11021: }
                   11022: 
                   11023: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11024:     my ($courseid,@groups) = @_;
                   11025:     @groups = sort(@groups);
1.691     raeburn  11026:     return @groups;
                   11027: }
                   11028: 
1.395     albertel 11029: sub packages_tab_default {
                   11030:     my ($uri,$varname)=@_;
                   11031:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11032: 
                   11033:     my (@extension,@specifics,$do_default);
                   11034:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11035: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11036: 	if ($pack_type eq 'default') {
                   11037: 	    $do_default=1;
                   11038: 	} elsif ($pack_type eq 'extension') {
                   11039: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11040: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11041: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11042: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11043: 	}
                   11044:     }
                   11045:     # first look for a package that matches the requested part id
                   11046:     foreach my $package (@specifics) {
                   11047: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11048: 	next if ($pack_part ne $part);
                   11049: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11050: 	    return $packagetab{"$pack_type&$name&default"};
                   11051: 	}
                   11052:     }
                   11053:     # look for any possible matching non extension_ package
                   11054:     foreach my $package (@specifics) {
                   11055: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11056: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11057: 	    return $packagetab{"$pack_type&$name&default"};
                   11058: 	}
1.585     albertel 11059: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11060: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11061: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11062: 	}
                   11063:     }
1.738     albertel 11064:     # look for any posible extension_ match
                   11065:     foreach my $package (@extension) {
                   11066: 	my ($package,$pack_type)=@{$package};
                   11067: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11068: 	    return $packagetab{"$pack_type&$name&default"};
                   11069: 	}
                   11070: 	if (defined($packagetab{$package."&$name&default"})) {
                   11071: 	    return $packagetab{$package."&$name&default"};
                   11072: 	}
                   11073:     }
                   11074:     # look for a global default setting
                   11075:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11076: 	return $packagetab{"default&$name&default"};
                   11077:     }
1.395     albertel 11078:     return undef;
                   11079: }
                   11080: 
1.334     albertel 11081: sub add_prefix_and_part {
                   11082:     my ($prefix,$part)=@_;
                   11083:     my $keyroot;
                   11084:     if (defined($prefix) && $prefix !~ /^__/) {
                   11085: 	# prefix that has a part already
                   11086: 	$keyroot=$prefix;
                   11087:     } elsif (defined($prefix)) {
                   11088: 	# prefix that is missing a part
                   11089: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11090:     } else {
                   11091: 	# no prefix at all
                   11092: 	if (defined($part)) { $keyroot='_'.$part; }
                   11093:     }
                   11094:     return $keyroot;
                   11095: }
                   11096: 
1.71      www      11097: # ---------------------------------------------------------------- Get metadata
                   11098: 
1.599     albertel 11099: my %metaentry;
1.1070    www      11100: my %importedpartids;
1.1172.2.99  raeburn  11101: my %importedrespids;
1.71      www      11102: sub metadata {
1.176     www      11103:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11104:     $uri=&declutter($uri);
1.288     albertel 11105:     # if it is a non metadata possible uri return quickly
1.529     albertel 11106:     if (($uri eq '') || 
                   11107: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  11108: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  11109:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11110: 	return undef;
                   11111:     }
1.1172.2.49  raeburn  11112:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11113: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11114: 	return undef;
1.288     albertel 11115:     }
1.73      www      11116:     my $filename=$uri;
                   11117:     $uri=~s/\.meta$//;
1.172     www      11118: #
                   11119: # Is the metadata already cached?
1.177     www      11120: # Look at timestamp of caching
1.172     www      11121: # Everything is cached by the main uri, libraries are never directly cached
                   11122: #
1.428     albertel 11123:     if (!defined($liburi)) {
1.599     albertel 11124: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11125: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11126:     }
                   11127:     {
1.1069    www      11128: # Imported parts would go here
1.1172.2.99  raeburn  11129:         my @origfiletagids=();
1.1069    www      11130:         my $importedparts=0;
1.1172.2.99  raeburn  11131: 
                   11132: # Imported responseids would go here
                   11133:         my $importedresponses=0;
1.172     www      11134: #
                   11135: # Is this a recursive call for a library?
                   11136: #
1.599     albertel 11137: #	if (! exists($metacache{$uri})) {
                   11138: #	    $metacache{$uri}={};
                   11139: #	}
1.924     albertel 11140: 	my $cachetime = 60*60;
1.171     www      11141:         if ($liburi) {
                   11142: 	    $liburi=&declutter($liburi);
                   11143:             $filename=$liburi;
1.401     bowersj2 11144:         } else {
1.599     albertel 11145: 	    &devalidate_cache_new('meta',$uri);
                   11146: 	    undef(%metaentry);
1.401     bowersj2 11147: 	}
1.140     www      11148:         my %metathesekeys=();
1.73      www      11149:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11150: 	my $metastring;
1.1140    www      11151: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11152: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11153: 	    $metastring = 
1.929     albertel 11154: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11155: 					  ('grade_target' => 'meta'));
                   11156: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11157: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11158:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11159: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11160: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11161: 	    $metastring=&getfile($file);
1.489     albertel 11162: 	}
1.208     albertel 11163:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11164:         my $token;
1.140     www      11165:         undef %metathesekeys;
1.71      www      11166:         while ($token=$parser->get_token) {
1.339     albertel 11167: 	    if ($token->[0] eq 'S') {
                   11168: 		if (defined($token->[2]->{'package'})) {
1.172     www      11169: #
                   11170: # This is a package - get package info
                   11171: #
1.339     albertel 11172: 		    my $package=$token->[2]->{'package'};
                   11173: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11174: 		    if (defined($token->[2]->{'id'})) { 
                   11175: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11176: 		    }
1.599     albertel 11177: 		    if ($metaentry{':packages'}) {
                   11178: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11179: 		    } else {
1.599     albertel 11180: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11181: 		    }
1.736     albertel 11182: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11183: 			my $part=$keyroot;
                   11184: 			$part=~s/^\_//;
1.736     albertel 11185: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11186: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11187: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11188: 			    # ignore package.tab specified default values
                   11189:                             # here &package_tab_default() will fetch those
                   11190: 			    if ($subp eq 'default') { next; }
1.736     albertel 11191: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11192: 			    my $unikey;
                   11193: 			    if ($pack =~ /_0$/) {
                   11194: 				$unikey='parameter_0_'.$name;
                   11195: 				$part=0;
                   11196: 			    } else {
                   11197: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11198: 			    }
1.339     albertel 11199: 			    if ($subp eq 'display') {
                   11200: 				$value.=' [Part: '.$part.']';
                   11201: 			    }
1.599     albertel 11202: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11203: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11204: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11205: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11206: 			    }
1.599     albertel 11207: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11208: 				$metaentry{':'.$unikey}=
                   11209: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11210: 			    }
1.339     albertel 11211: 			}
                   11212: 		    }
                   11213: 		} else {
1.172     www      11214: #
                   11215: # This is not a package - some other kind of start tag
1.339     albertel 11216: #
                   11217: 		    my $entry=$token->[1];
1.1068    www      11218: 		    my $unikey='';
1.175     www      11219: 
1.339     albertel 11220: 		    if ($entry eq 'import') {
1.175     www      11221: #
                   11222: # Importing a library here
1.339     albertel 11223: #
1.1067    www      11224:                         my $location=$parser->get_text('/import');
                   11225:                         my $dir=$filename;
                   11226:                         $dir=~s|[^/]*$||;
                   11227:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  11228: 
                   11229:                         my $importid=$token->[2]->{'id'};
1.1068    www      11230:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  11231: #
                   11232: # Check metadata for imported file to
                   11233: # see if it contained response items
                   11234: #
                   11235:                         my %currmetaentry = %metaentry;
                   11236:                         my $libresponseorder = &metadata($location,'responseorder');
                   11237:                         my $origfile;
                   11238:                         if ($libresponseorder ne '') {
                   11239:                             if ($#origfiletagids<0) {
                   11240:                                 undef(%importedrespids);
                   11241:                                 undef(%importedpartids);
                   11242:                             }
                   11243:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   11244:                             if (@{$importedrespids{$importid}} > 0) {
                   11245:                                 $importedresponses = 1;
                   11246: # We need to get the original file and the imported file to get the response order correct
                   11247: # Load and inspect original file
                   11248:                                 if ($#origfiletagids<0) {
                   11249:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11250:                                     $origfile=&getfile($origfilelocation);
                   11251:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11252:                                 }
                   11253:                             }
                   11254:                         }
                   11255: # Do not overwrite contents of %metaentry hash for resource itself with 
                   11256: # hash populated for imported library file
                   11257:                         %metaentry = %currmetaentry;
                   11258:                         undef(%currmetaentry);
1.1068    www      11259:                         if ($importmode eq 'problem') {
1.1069    www      11260: # Import as problem/response
1.1068    www      11261:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11262:                         } elsif ($importmode eq 'part') {
                   11263: # Import as part(s)
1.1069    www      11264:                            $importedparts=1;
                   11265: # We need to get the original file and the imported file to get the part order correct
                   11266: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  11267: # Load and inspect original file if we didn't do that already
                   11268:                            if ($#origfiletagids<0) {
                   11269:                                undef(%importedrespids);
                   11270:                                undef(%importedpartids);
                   11271:                                if ($origfile eq '') {
                   11272:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11273:                                    $origfile=&getfile($origfilelocation);
                   11274:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11275:                                }
1.1070    www      11276:                            }
                   11277: 
1.1069    www      11278: # Load and inspect imported file
                   11279:                            my $impfile=&getfile($location);
                   11280:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11281:                            if ($#impfilepartids>=0) {
                   11282: # This problem had parts
1.1070    www      11283:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11284:                            } else {
                   11285: # Importing by turning a single problem into a problem part
                   11286: # It gets the import-tags ID as part-ID
                   11287:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11288:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11289:                            }
1.1068    www      11290:                         } else {
                   11291: # Normal import
                   11292:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11293:                            if (defined($token->[2]->{'id'})) {
                   11294:                               $unikey.='_'.$token->[2]->{'id'};
                   11295:                            }
1.1067    www      11296:                         }
                   11297: 
1.339     albertel 11298: 			if ($depthcount<20) {
1.736     albertel 11299: 			    my $metadata = 
                   11300: 				&metadata($uri,'keys', $location,$unikey,
                   11301: 					  $depthcount+1);
                   11302: 			    foreach my $meta (split(',',$metadata)) {
                   11303: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   11304: 				$metathesekeys{$meta}=1;
1.339     albertel 11305: 			    }
1.1068    www      11306: 			
                   11307:                         }
1.1067    www      11308: 		    } else {
                   11309: #
                   11310: # Not importing, some other kind of non-package, non-library start tag
                   11311: # 
                   11312:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11313:                         if (defined($token->[2]->{'id'})) {
                   11314:                             $unikey.='_'.$token->[2]->{'id'};
                   11315:                         }
1.339     albertel 11316: 			if (defined($token->[2]->{'name'})) { 
                   11317: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   11318: 			}
                   11319: 			$metathesekeys{$unikey}=1;
1.736     albertel 11320: 			foreach my $param (@{$token->[3]}) {
                   11321: 			    $metaentry{':'.$unikey.'.'.$param} =
                   11322: 				$token->[2]->{$param};
1.339     albertel 11323: 			}
                   11324: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 11325: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 11326: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   11327: 		 # only ws inside the tag, and not in default, so use default
                   11328: 		 # as value
1.599     albertel 11329: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 11330: 			} elsif ( $internaltext =~ /\S/ ) {
                   11331: 		  # something interesting inside the tag
                   11332: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 11333: 			} else {
1.908     albertel 11334: 		  # no interesting values, don't set a default
1.339     albertel 11335: 			}
1.172     www      11336: # end of not-a-package not-a-library import
1.339     albertel 11337: 		    }
1.172     www      11338: # end of not-a-package start tag
1.339     albertel 11339: 		}
1.172     www      11340: # the next is the end of "start tag"
1.339     albertel 11341: 	    }
                   11342: 	}
1.483     albertel 11343: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 11344: 	$extension = lc($extension);
                   11345: 	if ($extension eq 'htm') { $extension='html'; }
                   11346: 
1.737     albertel 11347: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 11348: 	    #no specific packages #how's our extension
                   11349: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 11350: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 11351: 					 \%metathesekeys);
                   11352: 	}
1.883     albertel 11353: 
                   11354: 	if (!exists($metaentry{':packages'})
                   11355: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 11356: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 11357: 		#no specific packages well let's get default then
                   11358: 		if ($key!~/^default&/) { next; }
1.488     albertel 11359: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 11360: 					     \%metathesekeys);
                   11361: 	    }
                   11362: 	}
1.338     www      11363: # are there custom rights to evaluate
1.599     albertel 11364: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 11365: 
1.338     www      11366:     #
                   11367:     # Importing a rights file here
1.339     albertel 11368:     #
                   11369: 	    unless ($depthcount) {
1.599     albertel 11370: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 11371: 		my $dir=$filename;
                   11372: 		$dir=~s|[^/]*$||;
                   11373: 		$location=&filelocation($dir,$location);
1.736     albertel 11374: 		my $rights_metadata =
                   11375: 		    &metadata($uri,'keys',$location,'_rights',
                   11376: 			      $depthcount+1);
                   11377: 		foreach my $rights (split(',',$rights_metadata)) {
                   11378: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   11379: 		    $metathesekeys{$rights}=1;
1.339     albertel 11380: 		}
                   11381: 	    }
                   11382: 	}
1.737     albertel 11383: 	# uniqifiy package listing
                   11384: 	my %seen;
                   11385: 	my @uniq_packages =
                   11386: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   11387: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   11388: 
1.1172.2.99  raeburn  11389:         if (($importedresponses) || ($importedparts)) {
                   11390:             if ($importedparts) {
1.1070    www      11391: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  11392:                 $metaentry{':partorder'}='';
                   11393:                 $metathesekeys{'partorder'}=1;
                   11394:             }
                   11395:             if ($importedresponses) {
                   11396: # We had imported responses and need to rebuild responseorder
                   11397:                 $metaentry{':responseorder'}='';
                   11398:                 $metathesekeys{'responseorder'}=1;
                   11399:             }
                   11400:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   11401:                 my $origid = $origfiletagids[$index+1];
                   11402:                 if ($origfiletagids[$index] eq 'part') {
                   11403: # Original part, part of the problem
                   11404:                     if ($importedparts) {
                   11405:                         $metaentry{':partorder'}.=','.$origid;
                   11406:                     }
                   11407:                 } elsif ($origfiletagids[$index] eq 'import') {
                   11408:                     if ($importedparts) {
                   11409: # We have imported parts at this position
                   11410:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   11411:                     }
                   11412:                     if ($importedresponses) {
                   11413: # We have imported responses at this position
                   11414:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   11415:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   11416:                         }
                   11417:                     }
                   11418:                 } else {
                   11419: # Original response item, part of the problem
                   11420:                     if ($importedresponses) {
                   11421:                         $metaentry{':responseorder'}.=','.$origid;
                   11422:                     }
                   11423:                 }
                   11424:             }
                   11425:             if ($importedparts) {
                   11426:                 $metaentry{':partorder'}=~s/^\,//;
                   11427:             }
                   11428:             if ($importedresponses) {
                   11429:                 $metaentry{':responseorder'}=~s/^\,//;
                   11430:             }
1.1070    www      11431:         }
                   11432: 
1.737     albertel 11433: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 11434: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  11435: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 11436: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      11437: # this is the end of "was not already recently cached
1.71      www      11438:     }
1.599     albertel 11439:     return $metaentry{':'.$what};
1.261     albertel 11440: }
                   11441: 
1.488     albertel 11442: sub metadata_create_package_def {
1.483     albertel 11443:     my ($uri,$key,$package,$metathesekeys)=@_;
                   11444:     my ($pack,$name,$subp)=split(/\&/,$key);
                   11445:     if ($subp eq 'default') { next; }
                   11446:     
1.599     albertel 11447:     if (defined($metaentry{':packages'})) {
                   11448: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 11449:     } else {
1.599     albertel 11450: 	$metaentry{':packages'}=$package;
1.483     albertel 11451:     }
                   11452:     my $value=$packagetab{$key};
                   11453:     my $unikey;
                   11454:     $unikey='parameter_0_'.$name;
1.599     albertel 11455:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 11456:     $$metathesekeys{$unikey}=1;
1.599     albertel 11457:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11458: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 11459:     }
1.599     albertel 11460:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   11461: 	$metaentry{':'.$unikey}=
                   11462: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 11463:     }
                   11464: }
                   11465: 
1.261     albertel 11466: sub metadata_generate_part0 {
                   11467:     my ($metadata,$metacache,$uri) = @_;
                   11468:     my %allnames;
1.737     albertel 11469:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 11470: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 11471: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   11472: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 11473: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 11474: 	    $allnames{$name}=$part;
                   11475: 	  }
                   11476: 	}
                   11477:     }
                   11478:     foreach my $name (keys(%allnames)) {
                   11479:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 11480:       my $key=":parameter_0_$name";
1.261     albertel 11481:       $$metacache{"$key.part"}='0';
                   11482:       $$metacache{"$key.name"}=$name;
1.428     albertel 11483:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 11484: 					   $allnames{$name}.'_'.$name.
                   11485: 					   '.type'};
1.428     albertel 11486:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 11487: 			     '.display'};
1.644     www      11488:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 11489:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 11490:       $$metacache{"$key.display"}=$olddis;
                   11491:     }
1.71      www      11492: }
                   11493: 
1.764     albertel 11494: # ------------------------------------------------------ Devalidate title cache
                   11495: 
                   11496: sub devalidate_title_cache {
                   11497:     my ($url)=@_;
                   11498:     if (!$env{'request.course.id'}) { return; }
                   11499:     my $symb=&symbread($url);
                   11500:     if (!$symb) { return; }
                   11501:     my $key=$env{'request.course.id'}."\0".$symb;
                   11502:     &devalidate_cache_new('title',$key);
                   11503: }
                   11504: 
1.1014    droeschl 11505: # ------------------------------------------------- Get the title of a course
                   11506: 
                   11507: sub current_course_title {
                   11508:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   11509: }
1.301     www      11510: # ------------------------------------------------- Get the title of a resource
                   11511: 
                   11512: sub gettitle {
                   11513:     my $urlsymb=shift;
                   11514:     my $symb=&symbread($urlsymb);
1.534     albertel 11515:     if ($symb) {
1.620     albertel 11516: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 11517: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 11518: 	if (defined($cached)) { 
                   11519: 	    return $result;
                   11520: 	}
1.534     albertel 11521: 	my ($map,$resid,$url)=&decode_symb($symb);
                   11522: 	my $title='';
1.907     albertel 11523: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   11524: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   11525: 	} else {
                   11526: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11527: 		    &GDBM_READER(),0640)) {
                   11528: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   11529: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   11530: 		untie(%bighash);
                   11531: 	    }
1.534     albertel 11532: 	}
                   11533: 	$title=~s/\&colon\;/\:/gs;
                   11534: 	if ($title) {
1.1159    www      11535: # Remember both $symb and $title for dynamic metadata
                   11536:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      11537:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      11538: # Cache this title and then return it
1.599     albertel 11539: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 11540: 	}
                   11541: 	$urlsymb=$url;
                   11542:     }
                   11543:     my $title=&metadata($urlsymb,'title');
                   11544:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   11545:     return $title;
1.301     www      11546: }
1.613     albertel 11547: 
1.614     albertel 11548: sub get_slot {
                   11549:     my ($which,$cnum,$cdom)=@_;
                   11550:     if (!$cnum || !$cdom) {
1.790     albertel 11551: 	(undef,my $courseid)=&whichuser();
1.620     albertel 11552: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   11553: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 11554:     }
1.703     albertel 11555:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   11556:     my %slotinfo;
                   11557:     if (exists($remembered{$key})) {
                   11558: 	$slotinfo{$which} = $remembered{$key};
                   11559:     } else {
                   11560: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   11561: 	&Apache::lonhomework::showhash(%slotinfo);
                   11562: 	my ($tmp)=keys(%slotinfo);
                   11563: 	if ($tmp=~/^error:/) { return (); }
                   11564: 	$remembered{$key} = $slotinfo{$which};
                   11565:     }
1.616     albertel 11566:     if (ref($slotinfo{$which}) eq 'HASH') {
                   11567: 	return %{$slotinfo{$which}};
                   11568:     }
                   11569:     return $slotinfo{$which};
1.614     albertel 11570: }
1.1150    raeburn  11571: 
                   11572: sub get_reservable_slots {
                   11573:     my ($cnum,$cdom,$uname,$udom) = @_;
                   11574:     my $now = time;
                   11575:     my $reservable_info;
                   11576:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   11577:     if (exists($remembered{$key})) {
                   11578:         $reservable_info = $remembered{$key};
                   11579:     } else {
                   11580:         my %resv;
                   11581:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   11582:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   11583:         $reservable_info = \%resv;
                   11584:         $remembered{$key} = $reservable_info;
                   11585:     }
                   11586:     return $reservable_info;
                   11587: }
                   11588: 
                   11589: sub get_course_slots {
                   11590:     my ($cnum,$cdom) = @_;
                   11591:     my $hashid=$cnum.':'.$cdom;
                   11592:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   11593:     if (defined($cached)) {
                   11594:         if (ref($result) eq 'HASH') {
                   11595:             return %{$result};
                   11596:         }
                   11597:     } else {
                   11598:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   11599:         my ($tmp) = keys(%slots);
                   11600:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  11601:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  11602:             return %slots;
                   11603:         }
                   11604:     }
                   11605:     return;
                   11606: }
                   11607: 
                   11608: sub devalidate_slots_cache {
                   11609:     my ($cnum,$cdom)=@_;
                   11610:     my $hashid=$cnum.':'.$cdom;
                   11611:     &devalidate_cache_new('allslots',$hashid);
                   11612: }
                   11613: 
1.1172.2.8  raeburn  11614: sub get_coursechange {
                   11615:     my ($cdom,$cnum) = @_;
                   11616:     if ($cdom eq '' || $cnum eq '') {
                   11617:         return unless ($env{'request.course.id'});
                   11618:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   11619:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11620:     }
                   11621:     my $hashid=$cdom.'_'.$cnum;
                   11622:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   11623:     if ((defined($cached)) && ($change ne '')) {
                   11624:         return $change;
                   11625:     } else {
                   11626:         my %crshash;
                   11627:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   11628:         if ($crshash{'internal.contentchange'} eq '') {
                   11629:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   11630:             if ($change eq '') {
                   11631:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   11632:                 $change = $crshash{'internal.created'};
                   11633:             }
                   11634:         } else {
                   11635:             $change = $crshash{'internal.contentchange'};
                   11636:         }
                   11637:         my $cachetime = 600;
                   11638:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   11639:     }
                   11640:     return $change;
                   11641: }
                   11642: 
                   11643: sub devalidate_coursechange_cache {
                   11644:     my ($cnum,$cdom)=@_;
                   11645:     my $hashid=$cnum.':'.$cdom;
                   11646:     &devalidate_cache_new('crschange',$hashid);
                   11647: }
                   11648: 
1.31      www      11649: # ------------------------------------------------- Update symbolic store links
                   11650: 
                   11651: sub symblist {
                   11652:     my ($mapname,%newhash)=@_;
1.438     www      11653:     $mapname=&deversion(&declutter($mapname));
1.31      www      11654:     my %hash;
1.620     albertel 11655:     if (($env{'request.course.fn'}) && (%newhash)) {
                   11656:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11657:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  11658: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 11659: 		next if ($url eq 'last_known'
                   11660: 			 && $env{'form.no_update_last_known'});
                   11661: 		$hash{declutter($url)}=&encode_symb($mapname,
                   11662: 						    $newhash{$url}->[1],
                   11663: 						    $newhash{$url}->[0]);
1.191     harris41 11664:             }
1.31      www      11665:             if (untie(%hash)) {
                   11666: 		return 'ok';
                   11667:             }
                   11668:         }
                   11669:     }
                   11670:     return 'error';
1.212     www      11671: }
                   11672: 
                   11673: # --------------------------------------------------------------- Verify a symb
                   11674: 
                   11675: sub symbverify {
1.1172.2.11  raeburn  11676:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      11677:     my $thisfn=$thisurl;
1.439     www      11678:     $thisfn=&declutter($thisfn);
1.215     www      11679: # direct jump to resource in page or to a sequence - will construct own symbs
                   11680:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   11681: # check URL part
1.409     www      11682:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      11683: 
1.431     www      11684:     unless ($url eq $thisfn) { return 0; }
1.213     www      11685: 
1.216     www      11686:     $symb=&symbclean($symb);
1.510     www      11687:     $thisurl=&deversion($thisurl);
1.439     www      11688:     $thisfn=&deversion($thisfn);
1.213     www      11689: 
                   11690:     my %bighash;
                   11691:     my $okay=0;
1.431     www      11692: 
1.620     albertel 11693:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11694:                             &GDBM_READER(),0640)) {
1.1172.2.13  raeburn  11695:         my $noclutter;
1.1032    raeburn  11696:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   11697:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  11698:             if ($map =~ m{^uploaded/.+\.page$}) {
                   11699:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   11700:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   11701:                 $noclutter = 1;
                   11702:             }
                   11703:         }
                   11704:         my $ids;
                   11705:         if ($noclutter) {
                   11706:             $ids=$bighash{'ids_'.$thisurl};
                   11707:         } else {
                   11708:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  11709:         }
1.1102    raeburn  11710:         unless ($ids) {
1.1172.2.13  raeburn  11711:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  11712:             $ids=$bighash{$idkey};
1.216     www      11713:         }
                   11714:         if ($ids) {
                   11715: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  11716:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   11717:                 $symb =~ s/\?.+$//;
                   11718:             }
1.800     albertel 11719: 	    foreach my $id (split(/\,/,$ids)) {
                   11720: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      11721:                if (
                   11722:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  11723:    eq $symb) {
1.1172.2.11  raeburn  11724:                    if (ref($encstate)) {
                   11725:                        $$encstate = $bighash{'encrypted_'.$id};
                   11726:                    }
1.1172.2.13  raeburn  11727:                    if (($env{'request.role.adv'}) ||
                   11728:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  11729:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  11730:                        $okay=1;
                   11731:                        last;
                   11732:                    }
                   11733:                }
                   11734:            }
1.216     www      11735:         }
1.213     www      11736: 	untie(%bighash);
                   11737:     }
                   11738:     return $okay;
1.31      www      11739: }
                   11740: 
1.210     www      11741: # --------------------------------------------------------------- Clean-up symb
                   11742: 
                   11743: sub symbclean {
                   11744:     my $symb=shift;
1.568     albertel 11745:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      11746: # remove version from map
                   11747:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      11748: 
1.210     www      11749: # remove version from URL
                   11750:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      11751: 
1.507     www      11752: # remove wrapper
                   11753: 
1.510     www      11754:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 11755:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      11756:     return $symb;
1.409     www      11757: }
                   11758: 
                   11759: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 11760: 
                   11761: sub encode_symb {
                   11762:     my ($map,$resid,$url)=@_;
                   11763:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   11764: }
1.409     www      11765: 
                   11766: sub decode_symb {
1.568     albertel 11767:     my $symb=shift;
                   11768:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   11769:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      11770:     return (&fixversion($map),$resid,&fixversion($url));
                   11771: }
                   11772: 
                   11773: sub fixversion {
                   11774:     my $fn=shift;
1.609     banghart 11775:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      11776:     my %bighash;
                   11777:     my $uri=&clutter($fn);
1.620     albertel 11778:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      11779: # is this cached?
1.599     albertel 11780:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      11781:     if (defined($cached)) { return $result; }
                   11782: # unfortunately not cached, or expired
1.620     albertel 11783:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      11784: 	    &GDBM_READER(),0640)) {
                   11785:  	if ($bighash{'version_'.$uri}) {
                   11786:  	    my $version=$bighash{'version_'.$uri};
1.444     www      11787:  	    unless (($version eq 'mostrecent') || 
                   11788: 		    ($version==&getversion($uri))) {
1.440     www      11789:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   11790:  	    }
                   11791:  	}
                   11792:  	untie %bighash;
1.413     www      11793:     }
1.599     albertel 11794:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      11795: }
                   11796: 
                   11797: sub deversion {
                   11798:     my $url=shift;
                   11799:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   11800:     return $url;
1.210     www      11801: }
                   11802: 
1.31      www      11803: # ------------------------------------------------------ Return symb list entry
                   11804: 
                   11805: sub symbread {
1.1172.2.66  raeburn  11806:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54  raeburn  11807:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66  raeburn  11808:     if (defined($env{$cache_str})) {
                   11809:         if ($ignorecachednull) {
                   11810:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   11811:         } else {
                   11812:             return $env{$cache_str};
                   11813:         }
                   11814:     }
1.242     www      11815: # no filename provided? try from environment
1.1172.2.54  raeburn  11816:     unless ($thisfn) {
1.620     albertel 11817:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  11818:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   11819:         }
                   11820:         $thisfn=$env{'request.filename'};
1.44      www      11821:     }
1.569     albertel 11822:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      11823: # is that filename actually a symb? Verify, clean, and return
                   11824:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 11825: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 11826: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 11827: 	}
1.242     www      11828:     }
1.44      www      11829:     $thisfn=declutter($thisfn);
1.31      www      11830:     my %hash;
1.37      www      11831:     my %bighash;
                   11832:     my $syval='';
1.620     albertel 11833:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  11834:         my $targetfn = $thisfn;
1.609     banghart 11835:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  11836:             $targetfn = 'adm/wrapper/'.$thisfn;
                   11837:         }
1.687     albertel 11838: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   11839: 	    $targetfn=$1;
                   11840: 	}
1.620     albertel 11841:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11842:                       &GDBM_READER(),0640)) {
1.481     raeburn  11843: 	    $syval=$hash{$targetfn};
1.37      www      11844:             untie(%hash);
                   11845:         }
                   11846: # ---------------------------------------------------------- There was an entry
                   11847:         if ($syval) {
1.601     albertel 11848: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 11849: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  11850: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11851: 		    #return $env{$cache_str}='';
1.601     albertel 11852: 		#}    
                   11853: 		#$syval.=$1;
                   11854: 	    #}
1.37      www      11855:         } else {
                   11856: # ------------------------------------------------------- Was not in symb table
1.620     albertel 11857:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11858:                             &GDBM_READER(),0640)) {
1.37      www      11859: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      11860:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      11861:               unless ($ids) { 
                   11862:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      11863:               }
                   11864:               unless ($ids) {
                   11865: # alias?
                   11866: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      11867:               }
1.37      www      11868:               if ($ids) {
                   11869: # ------------------------------------------------------------------- Has ID(s)
                   11870:                  my @possibilities=split(/\,/,$ids);
1.39      www      11871:                  if ($#possibilities==0) {
                   11872: # ----------------------------------------------- There is only one possibility
1.37      www      11873: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 11874: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11875: 						    $resid,$thisfn);
1.1172.2.66  raeburn  11876:                      if (ref($possibles) eq 'HASH') {
                   11877:                          $possibles->{$syval} = 1;
                   11878:                      }
                   11879:                      if ($checkforblock) {
                   11880:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   11881:                          if (@blockers) {
                   11882:                              $syval = '';
                   11883:                              return;
                   11884:                          }
                   11885:                      }
                   11886:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      11887: # ------------------------------------------ There is more than one possibility
                   11888:                      my $realpossible=0;
1.800     albertel 11889:                      foreach my $id (@possibilities) {
                   11890: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  11891:                          my $canaccess;
                   11892:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   11893:                              $canaccess = 1;
                   11894:                          } else {
                   11895:                              $canaccess = &allowed('bre',$file);
                   11896:                          }
                   11897:                          if ($canaccess) {
                   11898:          		     my ($mapid,$resid)=split(/\./,$id);
                   11899:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   11900:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11901:                                                              $resid,$thisfn);
                   11902:                                  if (ref($possibles) eq 'HASH') {
                   11903:                                      $possibles->{$syval} = 1;
                   11904:                                  }
                   11905:                                  if ($checkforblock) {
                   11906:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   11907:                                      unless (@blockers > 0) {
                   11908:                                          $syval = $poss_syval;
                   11909:                                          $realpossible++;
                   11910:                                      }
                   11911:                                  } else {
                   11912:                                      $syval = $poss_syval;
                   11913:                                      $realpossible++;
                   11914:                                  }
                   11915:                              }
1.39      www      11916: 			 }
1.191     harris41 11917:                      }
1.39      www      11918: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      11919:                  } else {
                   11920:                      $syval='';
1.37      www      11921:                  }
                   11922: 	      }
1.1172.2.66  raeburn  11923:               untie(%bighash);
1.481     raeburn  11924:            }
1.31      www      11925:         }
1.62      www      11926:         if ($syval) {
1.620     albertel 11927: 	    return $env{$cache_str}=$syval;
1.62      www      11928:         }
1.31      www      11929:     }
1.949     raeburn  11930:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11931:     return $env{$cache_str}='';
1.31      www      11932: }
                   11933: 
                   11934: # ---------------------------------------------------------- Return random seed
                   11935: 
1.32      www      11936: sub numval {
                   11937:     my $txt=shift;
                   11938:     $txt=~tr/A-J/0-9/;
                   11939:     $txt=~tr/a-j/0-9/;
                   11940:     $txt=~tr/K-T/0-9/;
                   11941:     $txt=~tr/k-t/0-9/;
                   11942:     $txt=~tr/U-Z/0-5/;
                   11943:     $txt=~tr/u-z/0-5/;
                   11944:     $txt=~s/\D//g;
1.564     albertel 11945:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      11946:     return int($txt);
1.368     albertel 11947: }
                   11948: 
1.484     albertel 11949: sub numval2 {
                   11950:     my $txt=shift;
                   11951:     $txt=~tr/A-J/0-9/;
                   11952:     $txt=~tr/a-j/0-9/;
                   11953:     $txt=~tr/K-T/0-9/;
                   11954:     $txt=~tr/k-t/0-9/;
                   11955:     $txt=~tr/U-Z/0-5/;
                   11956:     $txt=~tr/u-z/0-5/;
                   11957:     $txt=~s/\D//g;
                   11958:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11959:     my $total;
                   11960:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 11961:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 11962:     return int($total);
                   11963: }
                   11964: 
1.575     albertel 11965: sub numval3 {
                   11966:     use integer;
                   11967:     my $txt=shift;
                   11968:     $txt=~tr/A-J/0-9/;
                   11969:     $txt=~tr/a-j/0-9/;
                   11970:     $txt=~tr/K-T/0-9/;
                   11971:     $txt=~tr/k-t/0-9/;
                   11972:     $txt=~tr/U-Z/0-5/;
                   11973:     $txt=~tr/u-z/0-5/;
                   11974:     $txt=~s/\D//g;
                   11975:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11976:     my $total;
                   11977:     foreach my $val (@txts) { $total+=$val; }
                   11978:     if ($_64bit) { $total=(($total<<32)>>32); }
                   11979:     return $total;
                   11980: }
                   11981: 
1.675     albertel 11982: sub digest {
                   11983:     my ($data)=@_;
                   11984:     my $digest=&Digest::MD5::md5($data);
                   11985:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   11986:     my ($e,$f);
                   11987:     {
                   11988:         use integer;
                   11989:         $e=($a+$b);
                   11990:         $f=($c+$d);
                   11991:         if ($_64bit) {
                   11992:             $e=(($e<<32)>>32);
                   11993:             $f=(($f<<32)>>32);
                   11994:         }
                   11995:     }
                   11996:     if (wantarray) {
                   11997: 	return ($e,$f);
                   11998:     } else {
                   11999: 	my $g;
                   12000: 	{
                   12001: 	    use integer;
                   12002: 	    $g=($e+$f);
                   12003: 	    if ($_64bit) {
                   12004: 		$g=(($g<<32)>>32);
                   12005: 	    }
                   12006: 	}
                   12007: 	return $g;
                   12008:     }
                   12009: }
                   12010: 
1.368     albertel 12011: sub latest_rnd_algorithm_id {
1.675     albertel 12012:     return '64bit5';
1.366     albertel 12013: }
1.32      www      12014: 
1.503     albertel 12015: sub get_rand_alg {
                   12016:     my ($courseid)=@_;
1.790     albertel 12017:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12018:     if ($courseid) {
1.620     albertel 12019: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12020:     }
                   12021:     return &latest_rnd_algorithm_id();
                   12022: }
                   12023: 
1.562     albertel 12024: sub validCODE {
                   12025:     my ($CODE)=@_;
                   12026:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12027:     return 0;
                   12028: }
                   12029: 
1.491     albertel 12030: sub getCODE {
1.620     albertel 12031:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12032:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12033: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12034: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12035: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12036:     }
                   12037:     return undef;
                   12038: }
1.1133    foxr     12039: #
                   12040: #  Determines the random seed for a specific context:
                   12041: #
                   12042: # parameters:
                   12043: #   symb      - in course context the symb for the seed.
                   12044: #   course_id - The course id of the form domain_coursenum.
                   12045: #   domain    - Domain for the user.
                   12046: #   course    - Course for the user.
                   12047: #   cenv      - environment of the course.
                   12048: #
                   12049: # NOTE:
                   12050: #   All parameters are picked out of the environment if missing
                   12051: #   or not defined.
                   12052: #   If a symb cannot be determined the current time is used instead.
                   12053: #
                   12054: #  For a given well defined symb, courside, domain, username,
                   12055: #  and course environment, the seed is reproducible.
                   12056: #
1.31      www      12057: sub rndseed {
1.1133    foxr     12058:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12059:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12060:     if (!defined($symb)) {
1.366     albertel 12061: 	unless ($symb=$wsymb) { return time; }
                   12062:     }
1.1146    foxr     12063:     if (!defined $courseid) { 
                   12064: 	$courseid=$wcourseid; 
                   12065:     }
                   12066:     if (!defined $domain) { $domain=$wdomain; }
                   12067:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12068: 
                   12069:     my $which;
                   12070:     if (defined($cenv->{'rndseed'})) {
                   12071: 	$which = $cenv->{'rndseed'};
                   12072:     } else {
                   12073: 	$which =&get_rand_alg($courseid);
                   12074:     }
1.491     albertel 12075:     if (defined(&getCODE())) {
1.675     albertel 12076: 	if ($which eq '64bit5') {
                   12077: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12078: 	} elsif ($which eq '64bit4') {
1.575     albertel 12079: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12080: 	} else {
                   12081: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12082: 	}
1.675     albertel 12083:     } elsif ($which eq '64bit5') {
                   12084: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12085:     } elsif ($which eq '64bit4') {
                   12086: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12087:     } elsif ($which eq '64bit3') {
                   12088: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12089:     } elsif ($which eq '64bit2') {
                   12090: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12091:     } elsif ($which eq '64bit') {
                   12092: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12093:     }
                   12094:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12095: }
                   12096: 
                   12097: sub rndseed_32bit {
                   12098:     my ($symb,$courseid,$domain,$username)=@_;
                   12099:     {
                   12100: 	use integer;
                   12101: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12102: 	my $symbseed=numval($symb) << 22;
                   12103: 	my $namechck=unpack("%32C*",$username) << 17;
                   12104: 	my $nameseed=numval($username) << 12;
                   12105: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12106: 	my $courseseed=unpack("%32C*",$courseid);
                   12107: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12108: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12109: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12110: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12111: 	return $num;
                   12112:     }
                   12113: }
                   12114: 
                   12115: sub rndseed_64bit {
                   12116:     my ($symb,$courseid,$domain,$username)=@_;
                   12117:     {
                   12118: 	use integer;
                   12119: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12120: 	my $symbseed=numval($symb) << 10;
                   12121: 	my $namechck=unpack("%32S*",$username);
                   12122: 	
                   12123: 	my $nameseed=numval($username) << 21;
                   12124: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12125: 	my $courseseed=unpack("%32S*",$courseid);
                   12126: 	
                   12127: 	my $num1=$symbchck+$symbseed+$namechck;
                   12128: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12129: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12130: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12131: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12132: 	return "$num1,$num2";
1.155     albertel 12133:     }
1.366     albertel 12134: }
                   12135: 
1.443     albertel 12136: sub rndseed_64bit2 {
                   12137:     my ($symb,$courseid,$domain,$username)=@_;
                   12138:     {
                   12139: 	use integer;
                   12140: 	# strings need to be an even # of cahracters long, it it is odd the
                   12141:         # last characters gets thrown away
                   12142: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12143: 	my $symbseed=numval($symb) << 10;
                   12144: 	my $namechck=unpack("%32S*",$username.' ');
                   12145: 	
                   12146: 	my $nameseed=numval($username) << 21;
1.501     albertel 12147: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12148: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12149: 	
                   12150: 	my $num1=$symbchck+$symbseed+$namechck;
                   12151: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12152: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12153: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12154: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12155: 	return "$num1,$num2";
                   12156:     }
                   12157: }
                   12158: 
                   12159: sub rndseed_64bit3 {
                   12160:     my ($symb,$courseid,$domain,$username)=@_;
                   12161:     {
                   12162: 	use integer;
                   12163: 	# strings need to be an even # of cahracters long, it it is odd the
                   12164:         # last characters gets thrown away
                   12165: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12166: 	my $symbseed=numval2($symb) << 10;
                   12167: 	my $namechck=unpack("%32S*",$username.' ');
                   12168: 	
                   12169: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12170: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12171: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12172: 	
                   12173: 	my $num1=$symbchck+$symbseed+$namechck;
                   12174: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12175: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12176: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12177: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12178: 	
1.503     albertel 12179: 	return "$num1:$num2";
1.443     albertel 12180:     }
                   12181: }
                   12182: 
1.575     albertel 12183: sub rndseed_64bit4 {
                   12184:     my ($symb,$courseid,$domain,$username)=@_;
                   12185:     {
                   12186: 	use integer;
                   12187: 	# strings need to be an even # of cahracters long, it it is odd the
                   12188:         # last characters gets thrown away
                   12189: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12190: 	my $symbseed=numval3($symb) << 10;
                   12191: 	my $namechck=unpack("%32S*",$username.' ');
                   12192: 	
                   12193: 	my $nameseed=numval3($username) << 21;
                   12194: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12195: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12196: 	
                   12197: 	my $num1=$symbchck+$symbseed+$namechck;
                   12198: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12199: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12200: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12201: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12202: 	
1.575     albertel 12203: 	return "$num1:$num2";
                   12204:     }
                   12205: }
                   12206: 
1.675     albertel 12207: sub rndseed_64bit5 {
                   12208:     my ($symb,$courseid,$domain,$username)=@_;
                   12209:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12210:     return "$num1:$num2";
                   12211: }
                   12212: 
1.366     albertel 12213: sub rndseed_CODE_64bit {
                   12214:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12215:     {
1.366     albertel 12216: 	use integer;
1.443     albertel 12217: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12218: 	my $symbseed=numval2($symb);
1.491     albertel 12219: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12220: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12221: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12222: 	my $num1=$symbseed+$CODEchck;
                   12223: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12224: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12225: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12226: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12227: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12228: 	return "$num1:$num2";
1.366     albertel 12229:     }
                   12230: }
                   12231: 
1.575     albertel 12232: sub rndseed_CODE_64bit4 {
                   12233:     my ($symb,$courseid,$domain,$username)=@_;
                   12234:     {
                   12235: 	use integer;
                   12236: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12237: 	my $symbseed=numval3($symb);
                   12238: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12239: 	my $CODEseed=numval3(&getCODE());
                   12240: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12241: 	my $num1=$symbseed+$CODEchck;
                   12242: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12243: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12244: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12245: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12246: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12247: 	return "$num1:$num2";
                   12248:     }
                   12249: }
                   12250: 
1.675     albertel 12251: sub rndseed_CODE_64bit5 {
                   12252:     my ($symb,$courseid,$domain,$username)=@_;
                   12253:     my $code = &getCODE();
                   12254:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12255:     return "$num1:$num2";
                   12256: }
                   12257: 
1.366     albertel 12258: sub setup_random_from_rndseed {
                   12259:     my ($rndseed)=@_;
1.503     albertel 12260:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  12261: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12262:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12263:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   12264:         } else {
                   12265:             &Math::Random::random_set_seed($num1,$num2);
                   12266:         }
1.366     albertel 12267:     } else {
                   12268: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12269:     }
1.36      albertel 12270: }
                   12271: 
1.474     albertel 12272: sub latest_receipt_algorithm_id {
1.835     albertel 12273:     return 'receipt3';
1.474     albertel 12274: }
                   12275: 
1.480     www      12276: sub recunique {
                   12277:     my $fucourseid=shift;
                   12278:     my $unique;
1.835     albertel 12279:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   12280: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12281: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      12282:     } else {
                   12283: 	$unique=$perlvar{'lonReceipt'};
                   12284:     }
                   12285:     return unpack("%32C*",$unique);
                   12286: }
                   12287: 
                   12288: sub recprefix {
                   12289:     my $fucourseid=shift;
                   12290:     my $prefix;
1.835     albertel 12291:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   12292: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12293: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      12294:     } else {
                   12295: 	$prefix=$perlvar{'lonHostID'};
                   12296:     }
                   12297:     return unpack("%32C*",$prefix);
                   12298: }
                   12299: 
1.76      www      12300: sub ireceipt {
1.474     albertel 12301:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 12302: 
                   12303:     my $return =&recprefix($fucourseid).'-';
                   12304: 
                   12305:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   12306: 	$env{'request.state'} eq 'construct') {
                   12307: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   12308: 	return $return;
                   12309:     }
                   12310: 
1.76      www      12311:     my $cuname=unpack("%32C*",$funame);
                   12312:     my $cudom=unpack("%32C*",$fudom);
                   12313:     my $cucourseid=unpack("%32C*",$fucourseid);
                   12314:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      12315:     my $cunique=&recunique($fucourseid);
1.474     albertel 12316:     my $cpart=unpack("%32S*",$part);
1.835     albertel 12317:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   12318: 
1.790     albertel 12319: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 12320: 			       
                   12321: 	$return.= ($cunique%$cuname+
                   12322: 		   $cunique%$cudom+
                   12323: 		   $cusymb%$cuname+
                   12324: 		   $cusymb%$cudom+
                   12325: 		   $cucourseid%$cuname+
                   12326: 		   $cucourseid%$cudom+
                   12327: 		   $cpart%$cuname+
                   12328: 		   $cpart%$cudom);
                   12329:     } else {
                   12330: 	$return.= ($cunique%$cuname+
                   12331: 		   $cunique%$cudom+
                   12332: 		   $cusymb%$cuname+
                   12333: 		   $cusymb%$cudom+
                   12334: 		   $cucourseid%$cuname+
                   12335: 		   $cucourseid%$cudom);
                   12336:     }
                   12337:     return $return;
1.76      www      12338: }
                   12339: 
                   12340: sub receipt {
1.474     albertel 12341:     my ($part)=@_;
1.790     albertel 12342:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 12343:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      12344: }
1.260     ng       12345: 
1.790     albertel 12346: sub whichuser {
                   12347:     my ($passedsymb)=@_;
                   12348:     my ($symb,$courseid,$domain,$name,$publicuser);
                   12349:     if (defined($env{'form.grade_symb'})) {
                   12350: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   12351: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   12352: 	if (!$allowed &&
                   12353: 	    exists($env{'request.course.sec'}) &&
                   12354: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   12355: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   12356: 			      '/'.$env{'request.course.sec'});
                   12357: 	}
                   12358: 	if ($allowed) {
                   12359: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   12360: 	    $courseid=$tmp_courseid;
                   12361: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   12362: 	    ($name)=&get_env_multiple('form.grade_username');
                   12363: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   12364: 	}
                   12365:     }
                   12366:     if (!$passedsymb) {
                   12367: 	$symb=&symbread();
                   12368:     } else {
                   12369: 	$symb=$passedsymb;
                   12370:     }
                   12371:     $courseid=$env{'request.course.id'};
                   12372:     $domain=$env{'user.domain'};
                   12373:     $name=$env{'user.name'};
                   12374:     if ($name eq 'public' && $domain eq 'public') {
                   12375: 	if (!defined($env{'form.username'})) {
                   12376: 	    $env{'form.username'}.=time.rand(10000000);
                   12377: 	}
                   12378: 	$name.=$env{'form.username'};
                   12379:     }
                   12380:     return ($symb,$courseid,$domain,$name,$publicuser);
                   12381: 
                   12382: }
                   12383: 
1.36      albertel 12384: # ------------------------------------------------------------ Serves up a file
1.472     albertel 12385: # returns either the contents of the file or 
                   12386: # -1 if the file doesn't exist
1.481     raeburn  12387: #
                   12388: # if the target is a file that was uploaded via DOCS, 
                   12389: # a check will be made to see if a current copy exists on the local server,
                   12390: # if it does this will be served, otherwise a copy will be retrieved from
                   12391: # the home server for the course and stored in /home/httpd/html/userfiles on
                   12392: # the local server.   
1.472     albertel 12393: 
1.36      albertel 12394: sub getfile {
1.538     albertel 12395:     my ($file) = @_;
1.609     banghart 12396:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 12397:     &repcopy($file);
                   12398:     return &readfile($file);
                   12399: }
                   12400: 
                   12401: sub repcopy_userfile {
                   12402:     my ($file)=@_;
1.1142    raeburn  12403:     my $londocroot = $perlvar{'lonDocRoot'};
                   12404:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  12405:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 12406:     my ($cdom,$cnum,$filename) = 
1.811     albertel 12407: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 12408:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   12409:     if (-e "$file") {
1.828     www      12410: # we already have a local copy, check it out
1.538     albertel 12411: 	my @fileinfo = stat($file);
1.828     www      12412: 	my $rtncode;
                   12413: 	my $info;
1.538     albertel 12414: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 12415: 	if ($lwpresp ne 'ok') {
1.828     www      12416: # there is no such file anymore, even though we had a local copy
1.482     albertel 12417: 	    if ($rtncode eq '404') {
1.538     albertel 12418: 		unlink($file);
1.482     albertel 12419: 	    }
                   12420: 	    return -1;
                   12421: 	}
                   12422: 	if ($info < $fileinfo[9]) {
1.828     www      12423: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  12424: 	    return 'ok';
1.828     www      12425: 	} else {
                   12426: # the file is outdated, get rid of it
                   12427: 	    unlink($file);
1.482     albertel 12428: 	}
1.828     www      12429:     }
                   12430: # one way or the other, at this point, we don't have the file
                   12431: # construct the correct path for the file
                   12432:     my @parts = ($cdom,$cnum); 
                   12433:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   12434: 	push @parts, split(/\//,$1);
                   12435:     }
                   12436:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   12437:     foreach my $part (@parts) {
                   12438: 	$path .= '/'.$part;
                   12439: 	if (!-e $path) {
                   12440: 	    mkdir($path,0770);
1.482     albertel 12441: 	}
                   12442:     }
1.828     www      12443: # now the path exists for sure
                   12444: # get a user agent
                   12445:     my $ua=new LWP::UserAgent;
                   12446:     my $transferfile=$file.'.in.transfer';
                   12447: # FIXME: this should flock
                   12448:     if (-e $transferfile) { return 'ok'; }
                   12449:     my $request;
                   12450:     $uri=~s/^\///;
1.980     raeburn  12451:     my $homeserver = &homeserver($cnum,$cdom);
                   12452:     my $protocol = $protocol{$homeserver};
                   12453:     $protocol = 'http' if ($protocol ne 'https');
                   12454:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      12455:     my $response=$ua->request($request,$transferfile);
                   12456: # did it work?
                   12457:     if ($response->is_error()) {
                   12458: 	unlink($transferfile);
                   12459: 	&logthis("Userfile repcopy failed for $uri");
                   12460: 	return -1;
                   12461:     }
                   12462: # worked, rename the transfer file
                   12463:     rename($transferfile,$file);
1.607     raeburn  12464:     return 'ok';
1.481     raeburn  12465: }
                   12466: 
1.517     albertel 12467: sub tokenwrapper {
                   12468:     my $uri=shift;
1.980     raeburn  12469:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 12470:     $uri=~s|^/||;
1.620     albertel 12471:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 12472:     my $token=$1;
1.552     albertel 12473:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   12474:     if ($udom && $uname && $file) {
                   12475: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  12476:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  12477:         my $homeserver = &homeserver($uname,$udom);
                   12478:         my $protocol = $protocol{$homeserver};
                   12479:         $protocol = 'http' if ($protocol ne 'https');
                   12480:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 12481:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   12482:                                '&tokenissued='.$perlvar{'lonHostID'};
                   12483:     } else {
                   12484:         return '/adm/notfound.html';
                   12485:     }
                   12486: }
                   12487: 
1.828     www      12488: # call with reqtype HEAD: get last modification time
                   12489: # call with reqtype GET: get the file contents
                   12490: # Do not call this with reqtype GET for large files! It loads everything into memory
                   12491: #
1.481     raeburn  12492: sub getuploaded {
                   12493:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   12494:     $uri=~s/^\///;
1.980     raeburn  12495:     my $homeserver = &homeserver($cnum,$cdom);
                   12496:     my $protocol = $protocol{$homeserver};
                   12497:     $protocol = 'http' if ($protocol ne 'https');
                   12498:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  12499:     my $ua=new LWP::UserAgent;
                   12500:     my $request=new HTTP::Request($reqtype,$uri);
                   12501:     my $response=$ua->request($request);
                   12502:     $$rtncode = $response->code;
1.482     albertel 12503:     if (! $response->is_success()) {
                   12504: 	return 'failed';
                   12505:     }      
                   12506:     if ($reqtype eq 'HEAD') {
1.486     www      12507: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 12508:     } elsif ($reqtype eq 'GET') {
                   12509: 	$$info = $response->content;
1.472     albertel 12510:     }
1.482     albertel 12511:     return 'ok';
1.36      albertel 12512: }
                   12513: 
1.481     raeburn  12514: sub readfile {
                   12515:     my $file = shift;
                   12516:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   12517:     my $fh;
1.1172.2.96  raeburn  12518:     open($fh,"<",$file);
1.481     raeburn  12519:     my $a='';
1.800     albertel 12520:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  12521:     return $a;
                   12522: }
                   12523: 
1.36      albertel 12524: sub filelocation {
1.590     banghart 12525:     my ($dir,$file) = @_;
                   12526:     my $location;
                   12527:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 12528: 
                   12529:     if ($file =~ m-^/adm/-) {
                   12530: 	$file=~s-^/adm/wrapper/-/-;
                   12531: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   12532:     }
1.882     albertel 12533: 
1.1139    www      12534:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  12535:         $location = $file;
1.609     banghart 12536:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 12537:         my ($udom,$uname,$filename)=
1.811     albertel 12538:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 12539:         my $home=&homeserver($uname,$udom);
                   12540:         my $is_me=0;
                   12541:         my @ids=&current_machine_ids();
                   12542:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   12543:         if ($is_me) {
1.1117    foxr     12544:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 12545:         } else {
                   12546:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   12547:   	      $udom.'/'.$uname.'/'.$filename;
                   12548:         }
1.882     albertel 12549:     } elsif ($file =~ m-^/adm/-) {
                   12550: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 12551:     } else {
                   12552:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      12553:         $file=~s:^/(res|priv)/:/:;
                   12554:         my $space=$1;
1.590     banghart 12555:         if ( !( $file =~ m:^/:) ) {
                   12556:             $location = $dir. '/'.$file;
                   12557:         } else {
1.1142    raeburn  12558:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 12559:         }
1.59      albertel 12560:     }
1.590     banghart 12561:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 12562:     while ($location=~m{/\.\./}) {
                   12563: 	if ($location =~ m{/[^/]+/\.\./}) {
                   12564: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   12565: 	} else {
                   12566: 	    $location=~ s{/\.\./}{/}g;
                   12567: 	}
                   12568:     } #remove dir/..
1.590     banghart 12569:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   12570:     return $location;
1.46      www      12571: }
1.36      albertel 12572: 
1.46      www      12573: sub hreflocation {
                   12574:     my ($dir,$file)=@_;
1.980     raeburn  12575:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 12576: 	$file=filelocation($dir,$file);
1.700     albertel 12577:     } elsif ($file=~m-^/adm/-) {
                   12578: 	$file=~s-^/adm/wrapper/-/-;
                   12579: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 12580:     }
                   12581:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   12582: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   12583:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  12584: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   12585: 	        {/uploaded/$1/$2/}x;
1.46      www      12586:     }
1.913     albertel 12587:     if ($file=~ m{^/userfiles/}) {
                   12588: 	$file =~ s{^/userfiles/}{/uploaded/};
                   12589:     }
1.462     albertel 12590:     return $file;
1.465     albertel 12591: }
                   12592: 
1.1139    www      12593: 
                   12594: 
                   12595: 
                   12596: 
1.465     albertel 12597: sub current_machine_domains {
1.853     albertel 12598:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   12599: }
                   12600: 
                   12601: sub machine_domains {
                   12602:     my ($hostname) = @_;
1.465     albertel 12603:     my @domains;
1.838     albertel 12604:     my %hostname = &all_hostnames();
1.465     albertel 12605:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  12606: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 12607: 	if ($hostname eq $name) {
1.844     albertel 12608: 	    push(@domains,&host_domain($id));
1.465     albertel 12609: 	}
                   12610:     }
                   12611:     return @domains;
                   12612: }
                   12613: 
                   12614: sub current_machine_ids {
1.853     albertel 12615:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   12616: }
                   12617: 
                   12618: sub machine_ids {
                   12619:     my ($hostname) = @_;
                   12620:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 12621:     my @ids;
1.888     albertel 12622:     my %name_to_host = &all_names();
1.889     albertel 12623:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   12624: 	return @{ $name_to_host{$hostname} };
                   12625:     }
                   12626:     return;
1.31      www      12627: }
                   12628: 
1.824     raeburn  12629: sub additional_machine_domains {
                   12630:     my @domains;
1.1172.2.96  raeburn  12631:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  12632:     while( my $line = <$fh>) {
                   12633:         $line =~ s/\s//g;
                   12634:         push(@domains,$line);
                   12635:     }
                   12636:     return @domains;
                   12637: }
                   12638: 
                   12639: sub default_login_domain {
                   12640:     my $domain = $perlvar{'lonDefDomain'};
                   12641:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   12642:     foreach my $posdom (&current_machine_domains(),
                   12643:                         &additional_machine_domains()) {
                   12644:         if (lc($posdom) eq lc($testdomain)) {
                   12645:             $domain=$posdom;
                   12646:             last;
                   12647:         }
                   12648:     }
                   12649:     return $domain;
                   12650: }
                   12651: 
1.31      www      12652: # ------------------------------------------------------------- Declutters URLs
                   12653: 
                   12654: sub declutter {
                   12655:     my $thisfn=shift;
1.569     albertel 12656:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  12657:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   12658:         $thisfn=~s{^/home/httpd/html}{};
                   12659:     }
1.31      www      12660:     $thisfn=~s/^\///;
1.697     albertel 12661:     $thisfn=~s|^adm/wrapper/||;
                   12662:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      12663:     $thisfn=~s/^res\///;
1.1172    bisitz   12664:     $thisfn=~s/^priv\///;
1.1032    raeburn  12665:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   12666:         $thisfn=~s/\?.+$//;
                   12667:     }
1.268     www      12668:     return $thisfn;
                   12669: }
                   12670: 
                   12671: # ------------------------------------------------------------- Clutter up URLs
                   12672: 
                   12673: sub clutter {
                   12674:     my $thisfn='/'.&declutter(shift);
1.887     albertel 12675:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 12676: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      12677:        $thisfn='/res'.$thisfn; 
                   12678:     }
1.1031    raeburn  12679:     if ($thisfn !~m|^/adm|) {
                   12680: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 12681: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 12682: 	} else {
                   12683: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   12684: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 12685: 	    if ($embstyle eq 'ssi'
                   12686: 		|| ($embstyle eq 'hdn')
                   12687: 		|| ($embstyle eq 'rat')
                   12688: 		|| ($embstyle eq 'prv')
                   12689: 		|| ($embstyle eq 'ign')) {
                   12690: 		#do nothing with these
                   12691: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 12692: 		|| ($embstyle eq 'emb')
                   12693: 		|| ($embstyle eq 'wrp')) {
                   12694: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 12695: 	    } elsif ($embstyle eq 'unk'
                   12696: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 12697: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 12698: 	    } else {
1.718     www      12699: #		&logthis("Got a blank emb style");
1.695     albertel 12700: 	    }
1.694     albertel 12701: 	}
                   12702:     }
1.31      www      12703:     return $thisfn;
1.12      www      12704: }
                   12705: 
1.787     albertel 12706: sub clutter_with_no_wrapper {
                   12707:     my $uri = &clutter(shift);
                   12708:     if ($uri =~ m-^/adm/-) {
                   12709: 	$uri =~ s-^/adm/wrapper/-/-;
                   12710: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   12711:     }
                   12712:     return $uri;
                   12713: }
                   12714: 
1.557     albertel 12715: sub freeze_escape {
                   12716:     my ($value)=@_;
                   12717:     if (ref($value)) {
                   12718: 	$value=&nfreeze($value);
                   12719: 	return '__FROZEN__'.&escape($value);
                   12720:     }
                   12721:     return &escape($value);
                   12722: }
                   12723: 
1.11      www      12724: 
1.557     albertel 12725: sub thaw_unescape {
                   12726:     my ($value)=@_;
                   12727:     if ($value =~ /^__FROZEN__/) {
                   12728: 	substr($value,0,10,undef);
                   12729: 	$value=&unescape($value);
                   12730: 	return &thaw($value);
                   12731:     }
                   12732:     return &unescape($value);
                   12733: }
                   12734: 
1.436     albertel 12735: sub correct_line_ends {
                   12736:     my ($result)=@_;
                   12737:     $$result =~s/\r\n/\n/mg;
                   12738:     $$result =~s/\r/\n/mg;
1.415     albertel 12739: }
1.1       albertel 12740: # ================================================================ Main Program
                   12741: 
1.184     www      12742: sub goodbye {
1.204     albertel 12743:    &logthis("Starting Shut down");
1.443     albertel 12744: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 12745:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 12746: #converted
1.599     albertel 12747: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 12748:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   12749: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   12750: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 12751: #1.1 only
1.870     albertel 12752: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   12753: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   12754: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   12755: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   12756:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 12757:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   12758:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      12759:    &flushcourselogs();
                   12760:    &logthis("Shutting down");
                   12761: }
                   12762: 
1.852     albertel 12763: sub get_dns {
1.1172.2.17  raeburn  12764:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 12765:     if (!$ignore_cache) {
                   12766: 	my ($content,$cached)=
                   12767: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   12768: 	if ($cached) {
1.1172.2.17  raeburn  12769: 	    &$func($content,$hashref);
1.869     albertel 12770: 	    return;
                   12771: 	}
                   12772:     }
                   12773: 
                   12774:     my %alldns;
1.1172.2.96  raeburn  12775:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   12776:         foreach my $dns (<$config>) {
                   12777: 	    next if ($dns !~ /^\^(\S*)/x);
                   12778:             my $line = $1;
                   12779:             my ($host,$protocol) = split(/:/,$line);
                   12780:             if ($protocol ne 'https') {
                   12781:                 $protocol = 'http';
                   12782:             }
                   12783: 	    $alldns{$host} = $protocol;
1.979     raeburn  12784:         }
1.1172.2.96  raeburn  12785:         close($config);
1.869     albertel 12786:     }
                   12787:     while (%alldns) {
1.1172.2.52  raeburn  12788: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 12789: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  12790:         $ua->timeout(30);
1.979     raeburn  12791: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 12792: 	my $response=$ua->request($request);
1.979     raeburn  12793:         delete($alldns{$dns});
1.852     albertel 12794: 	next if ($response->is_error());
                   12795: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  12796:         unless ($nocache) {
1.1172.2.23  raeburn  12797: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  12798:         }
                   12799: 	&$func(\@content,$hashref);
1.869     albertel 12800: 	return;
1.852     albertel 12801:     }
                   12802:     close($config);
1.871     albertel 12803:     my $which = (split('/',$url))[3];
                   12804:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.96  raeburn  12805:     open($config,"<","$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 12806:     my @content = <$config>;
1.1172.2.17  raeburn  12807:     &$func(\@content,$hashref);
                   12808:     return;
                   12809: }
                   12810: 
                   12811: # ------------------------------------------------------Get DNS checksums file
                   12812: sub parse_dns_checksums_tab {
                   12813:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  12814:     my $lonhost = $perlvar{'lonHostID'};
                   12815:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  12816:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  12817:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   12818:     my $webconfdir = '/etc/httpd/conf';
                   12819:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   12820:         $webconfdir = '/etc/apache2';
                   12821:     } elsif ($distro =~ /^sles(\d+)$/) {
                   12822:         if ($1 >= 10) {
                   12823:             $webconfdir = '/etc/apache2';
                   12824:         }
                   12825:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   12826:         if ($1 >= 10.0) {
                   12827:             $webconfdir = '/etc/apache2';
                   12828:         }
                   12829:     }
1.1172.2.17  raeburn  12830:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12831:     my (%chksum,%revnum);
                   12832:     if (ref($lines) eq 'ARRAY') {
                   12833:         chomp(@{$lines});
1.1172.2.34  raeburn  12834:         my $version = shift(@{$lines});
                   12835:         if ($version eq $release) {
1.1172.2.17  raeburn  12836:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  12837:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  12838:                 if ($file =~ m{^/etc/httpd/conf}) {
                   12839:                     if ($webconfdir eq '/etc/apache2') {
                   12840:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   12841:                     }
                   12842:                 }
1.1172.2.34  raeburn  12843:                 $chksum{$file} = $shasum;
                   12844:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  12845:             }
                   12846:             if (ref($hashref) eq 'HASH') {
                   12847:                 %{$hashref} = (
                   12848:                                 sums     => \%chksum,
                   12849:                                 versions => \%revnum,
                   12850:                               );
                   12851:             }
                   12852:         }
                   12853:     }
1.869     albertel 12854:     return;
1.852     albertel 12855: }
1.1172.2.17  raeburn  12856: 
                   12857: sub fetch_dns_checksums {
                   12858:     my %checksums;
1.1172.2.34  raeburn  12859:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  12860:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  12861:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12862:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  12863:              \%checksums);
                   12864:     return \%checksums;
                   12865: }
                   12866: 
1.327     albertel 12867: # ------------------------------------------------------------ Read domain file
                   12868: {
1.852     albertel 12869:     my $loaded;
1.846     albertel 12870:     my %domain;
                   12871: 
1.852     albertel 12872:     sub parse_domain_tab {
                   12873: 	my ($lines) = @_;
                   12874: 	foreach my $line (@$lines) {
                   12875: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      12876: 
1.846     albertel 12877: 	    chomp($line);
1.852     albertel 12878: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 12879: 	    my %this_domain;
                   12880: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   12881: 			       'lang_def', 'city', 'longi', 'lati',
                   12882: 			       'primary') {
                   12883: 		$this_domain{$field} = shift(@elements);
                   12884: 	    }
                   12885: 	    $domain{$name} = \%this_domain;
1.852     albertel 12886: 	}
                   12887:     }
1.864     albertel 12888: 
                   12889:     sub reset_domain_info {
                   12890: 	undef($loaded);
                   12891: 	undef(%domain);
                   12892:     }
                   12893: 
1.852     albertel 12894:     sub load_domain_tab {
1.1172.2.70  raeburn  12895: 	my ($ignore_cache,$nocache) = @_;
                   12896: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 12897: 	my $fh;
1.1172.2.96  raeburn  12898: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 12899: 	    my @lines = <$fh>;
                   12900: 	    &parse_domain_tab(\@lines);
1.448     albertel 12901: 	}
1.852     albertel 12902: 	close($fh);
                   12903: 	$loaded = 1;
1.327     albertel 12904:     }
1.846     albertel 12905: 
                   12906:     sub domain {
1.852     albertel 12907: 	&load_domain_tab() if (!$loaded);
                   12908: 
1.846     albertel 12909: 	my ($name,$what) = @_;
                   12910: 	return if ( !exists($domain{$name}) );
                   12911: 
                   12912: 	if (!$what) {
                   12913: 	    return $domain{$name}{'description'};
                   12914: 	}
                   12915: 	return $domain{$name}{$what};
                   12916:     }
1.974     raeburn  12917: 
                   12918:     sub domain_info {
                   12919:         &load_domain_tab() if (!$loaded);
                   12920:         return %domain;
                   12921:     }
                   12922: 
1.327     albertel 12923: }
                   12924: 
                   12925: 
1.1       albertel 12926: # ------------------------------------------------------------- Read hosts file
                   12927: {
1.838     albertel 12928:     my %hostname;
1.844     albertel 12929:     my %hostdom;
1.845     albertel 12930:     my %libserv;
1.852     albertel 12931:     my $loaded;
1.888     albertel 12932:     my %name_to_host;
1.1074    raeburn  12933:     my %internetdom;
1.1107    raeburn  12934:     my %LC_dns_serv;
1.852     albertel 12935: 
                   12936:     sub parse_hosts_tab {
                   12937: 	my ($file) = @_;
                   12938: 	foreach my $configline (@$file) {
                   12939: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  12940:             chomp($configline);
                   12941: 	    if ($configline =~ /^\^/) {
                   12942:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   12943:                     $LC_dns_serv{$1} = 1;
                   12944:                 }
                   12945:                 next;
                   12946:             }
1.1074    raeburn  12947: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 12948: 	    $name=~s/\s//g;
                   12949: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  12950:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   12951:                     my $curr = $hostname{$id};
                   12952:                     my $skip;
                   12953:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   12954:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   12955:                             $skip = 1;
                   12956:                         } else {
                   12957:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   12958:                         }
                   12959:                     }
                   12960:                     unless ($skip) {
                   12961:                         push(@{$name_to_host{$name}},$id);
                   12962:                     }
                   12963:                 } else {
                   12964:                     push(@{$name_to_host{$name}},$id);
                   12965:                 }
1.852     albertel 12966: 		$hostname{$id}=$name;
                   12967: 		$hostdom{$id}=$domain;
                   12968: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  12969:                 if (defined($protocol)) {
                   12970:                     if ($protocol eq 'https') {
                   12971:                         $protocol{$id} = $protocol;
                   12972:                     } else {
                   12973:                         $protocol{$id} = 'http'; 
                   12974:                     }
1.968     raeburn  12975:                 } else {
1.969     raeburn  12976:                     $protocol{$id} = 'http';
1.968     raeburn  12977:                 }
1.1074    raeburn  12978:                 if (defined($intdom)) {
                   12979:                     $internetdom{$id} = $intdom;
                   12980:                 }
1.852     albertel 12981: 	    }
                   12982: 	}
                   12983:     }
1.864     albertel 12984:     
                   12985:     sub reset_hosts_info {
1.897     albertel 12986: 	&purge_remembered();
1.864     albertel 12987: 	&reset_domain_info();
                   12988: 	&reset_hosts_ip_info();
1.892     albertel 12989: 	undef(%name_to_host);
1.864     albertel 12990: 	undef(%hostname);
                   12991: 	undef(%hostdom);
                   12992: 	undef(%libserv);
                   12993: 	undef($loaded);
                   12994:     }
1.1       albertel 12995: 
1.852     albertel 12996:     sub load_hosts_tab {
1.1172.2.70  raeburn  12997: 	my ($ignore_cache,$nocache) = @_;
                   12998: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  12999: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13000: 	my @config = <$config>;
                   13001: 	&parse_hosts_tab(\@config);
                   13002: 	close($config);
                   13003: 	$loaded=1;
1.1       albertel 13004:     }
1.852     albertel 13005: 
1.838     albertel 13006:     sub hostname {
1.852     albertel 13007: 	&load_hosts_tab() if (!$loaded);
                   13008: 
1.838     albertel 13009: 	my ($lonid) = @_;
                   13010: 	return $hostname{$lonid};
                   13011:     }
1.845     albertel 13012: 
1.838     albertel 13013:     sub all_hostnames {
1.852     albertel 13014: 	&load_hosts_tab() if (!$loaded);
                   13015: 
1.838     albertel 13016: 	return %hostname;
                   13017:     }
1.845     albertel 13018: 
1.888     albertel 13019:     sub all_names {
1.1172.2.70  raeburn  13020:         my ($ignore_cache,$nocache) = @_;
                   13021: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13022: 
                   13023: 	return %name_to_host;
                   13024:     }
                   13025: 
1.974     raeburn  13026:     sub all_host_domain {
                   13027:         &load_hosts_tab() if (!$loaded);
                   13028:         return %hostdom;
                   13029:     }
                   13030: 
1.845     albertel 13031:     sub is_library {
1.852     albertel 13032: 	&load_hosts_tab() if (!$loaded);
                   13033: 
1.845     albertel 13034: 	return exists($libserv{$_[0]});
                   13035:     }
                   13036: 
                   13037:     sub all_library {
1.852     albertel 13038: 	&load_hosts_tab() if (!$loaded);
                   13039: 
1.845     albertel 13040: 	return %libserv;
                   13041:     }
                   13042: 
1.1062    droeschl 13043:     sub unique_library {
                   13044: 	#2x reverse removes all hostnames that appear more than once
                   13045:         my %unique = reverse &all_library();
                   13046:         return reverse %unique;
                   13047:     }
                   13048: 
1.841     albertel 13049:     sub get_servers {
1.852     albertel 13050: 	&load_hosts_tab() if (!$loaded);
                   13051: 
1.841     albertel 13052: 	my ($domain,$type) = @_;
                   13053: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13054: 	                                          : %hostname;
                   13055: 	my %result;
1.842     albertel 13056: 	if (ref($domain) eq 'ARRAY') {
                   13057: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13058: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13059: 		    $result{$host} = $hostname;
                   13060: 		}
                   13061: 	    }
                   13062: 	} else {
                   13063: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13064: 		if ($hostdom{$host} eq $domain) {
                   13065: 		    $result{$host} = $hostname;
                   13066: 		}
1.841     albertel 13067: 	    }
                   13068: 	}
                   13069: 	return %result;
                   13070:     }
1.845     albertel 13071: 
1.1062    droeschl 13072:     sub get_unique_servers {
                   13073:         my %unique = reverse &get_servers(@_);
                   13074: 	return reverse %unique;
                   13075:     }
                   13076: 
1.844     albertel 13077:     sub host_domain {
1.852     albertel 13078: 	&load_hosts_tab() if (!$loaded);
                   13079: 
1.844     albertel 13080: 	my ($lonid) = @_;
                   13081: 	return $hostdom{$lonid};
                   13082:     }
                   13083: 
1.841     albertel 13084:     sub all_domains {
1.852     albertel 13085: 	&load_hosts_tab() if (!$loaded);
                   13086: 
1.841     albertel 13087: 	my %seen;
                   13088: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13089: 	return @uniq;
                   13090:     }
1.1074    raeburn  13091: 
                   13092:     sub internet_dom {
                   13093:         &load_hosts_tab() if (!$loaded);
                   13094: 
                   13095:         my ($lonid) = @_;
                   13096:         return $internetdom{$lonid};
                   13097:     }
1.1107    raeburn  13098: 
                   13099:     sub is_LC_dns {
                   13100:         &load_hosts_tab() if (!$loaded);
                   13101: 
                   13102:         my ($hostname) = @_;
                   13103:         return exists($LC_dns_serv{$hostname});
                   13104:     }
                   13105: 
1.1       albertel 13106: }
                   13107: 
1.847     albertel 13108: { 
                   13109:     my %iphost;
1.856     albertel 13110:     my %name_to_ip;
                   13111:     my %lonid_to_ip;
1.869     albertel 13112: 
1.847     albertel 13113:     sub get_hosts_from_ip {
                   13114: 	my ($ip) = @_;
                   13115: 	my %iphosts = &get_iphost();
                   13116: 	if (ref($iphosts{$ip})) {
                   13117: 	    return @{$iphosts{$ip}};
                   13118: 	}
                   13119: 	return;
1.839     albertel 13120:     }
1.864     albertel 13121:     
                   13122:     sub reset_hosts_ip_info {
                   13123: 	undef(%iphost);
                   13124: 	undef(%name_to_ip);
                   13125: 	undef(%lonid_to_ip);
                   13126:     }
1.856     albertel 13127: 
                   13128:     sub get_host_ip {
                   13129: 	my ($lonid) = @_;
                   13130: 	if (exists($lonid_to_ip{$lonid})) {
                   13131: 	    return $lonid_to_ip{$lonid};
                   13132: 	}
                   13133: 	my $name=&hostname($lonid);
                   13134:    	my $ip = gethostbyname($name);
                   13135: 	return if (!$ip || length($ip) ne 4);
                   13136: 	$ip=inet_ntoa($ip);
                   13137: 	$name_to_ip{$name}   = $ip;
                   13138: 	$lonid_to_ip{$lonid} = $ip;
                   13139: 	return $ip;
                   13140:     }
1.847     albertel 13141:     
                   13142:     sub get_iphost {
1.1172.2.70  raeburn  13143: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13144: 
1.869     albertel 13145: 	if (!$ignore_cache) {
                   13146: 	    if (%iphost) {
                   13147: 		return %iphost;
                   13148: 	    }
                   13149: 	    my ($ip_info,$cached)=
                   13150: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13151: 	    if ($cached) {
                   13152: 		%iphost      = %{$ip_info->[0]};
                   13153: 		%name_to_ip  = %{$ip_info->[1]};
                   13154: 		%lonid_to_ip = %{$ip_info->[2]};
                   13155: 		return %iphost;
                   13156: 	    }
                   13157: 	}
1.894     albertel 13158: 
                   13159: 	# get yesterday's info for fallback
                   13160: 	my %old_name_to_ip;
                   13161: 	my ($ip_info,$cached)=
                   13162: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13163: 	if ($cached) {
                   13164: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13165: 	}
                   13166: 
1.1172.2.70  raeburn  13167: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13168: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13169: 	    my $ip;
                   13170: 	    if (!exists($name_to_ip{$name})) {
                   13171: 		$ip = gethostbyname($name);
                   13172: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13173: 		    if (defined($old_name_to_ip{$name})) {
                   13174: 			$ip = $old_name_to_ip{$name};
                   13175: 			&logthis("Can't find $name defaulting to old $ip");
                   13176: 		    } else {
                   13177: 			&logthis("Name $name no IP found");
                   13178: 			next;
                   13179: 		    }
                   13180: 		} else {
                   13181: 		    $ip=inet_ntoa($ip);
1.847     albertel 13182: 		}
                   13183: 		$name_to_ip{$name} = $ip;
                   13184: 	    } else {
                   13185: 		$ip = $name_to_ip{$name};
1.653     albertel 13186: 	    }
1.888     albertel 13187: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13188: 		$lonid_to_ip{$id} = $ip;
                   13189: 	    }
                   13190: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13191: 	}
1.1172.2.70  raeburn  13192:         unless ($nocache) {
                   13193: 	    &do_cache_new('iphost','iphost',
                   13194: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   13195: 		          48*60*60);
                   13196:         }
1.869     albertel 13197: 
1.847     albertel 13198: 	return %iphost;
1.598     albertel 13199:     }
                   13200: 
1.992     raeburn  13201:     #
                   13202:     #  Given a DNS returns the loncapa host name for that DNS 
                   13203:     # 
                   13204:     sub host_from_dns {
                   13205:         my ($dns) = @_;
                   13206:         my @hosts;
                   13207:         my $ip;
                   13208: 
1.993     raeburn  13209:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  13210:             $ip = $name_to_ip{$dns};
                   13211:         }
                   13212:         if (!$ip) {
                   13213:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   13214:             if (length($ip) == 4) { 
                   13215: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   13216:             }
                   13217:         }
                   13218:         if ($ip) {
                   13219: 	    @hosts = get_hosts_from_ip($ip);
                   13220: 	    return $hosts[0];
                   13221:         }
                   13222:         return undef;
1.986     foxr     13223:     }
1.992     raeburn  13224: 
1.1074    raeburn  13225:     sub get_internet_names {
                   13226:         my ($lonid) = @_;
                   13227:         return if ($lonid eq '');
                   13228:         my ($idnref,$cached)=
                   13229:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   13230:         if ($cached) {
                   13231:             return $idnref;
                   13232:         }
                   13233:         my $ip = &get_host_ip($lonid);
                   13234:         my @hosts = &get_hosts_from_ip($ip);
                   13235:         my %iphost = &get_iphost();
                   13236:         my (@idns,%seen);
                   13237:         foreach my $id (@hosts) {
                   13238:             my $dom = &host_domain($id);
                   13239:             my $prim_id = &domain($dom,'primary');
                   13240:             my $prim_ip = &get_host_ip($prim_id);
                   13241:             next if ($seen{$prim_ip});
                   13242:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   13243:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   13244:                     my $intdom = &internet_dom($id);
                   13245:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   13246:                         push(@idns,$intdom);
                   13247:                     }
                   13248:                 }
                   13249:             }
                   13250:             $seen{$prim_ip} = 1;
                   13251:         }
1.1172.2.23  raeburn  13252:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  13253:     }
                   13254: 
1.986     foxr     13255: }
                   13256: 
1.1079    raeburn  13257: sub all_loncaparevs {
1.1172.2.39  raeburn  13258:     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  13259: }
                   13260: 
1.1172.2.27  raeburn  13261: # ------------------------------------------------------- Read loncaparev table
                   13262: {
                   13263:     sub load_loncaparevs {
                   13264:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  13265:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  13266:                 while (my $configline=<$config>) {
                   13267:                     chomp($configline);
                   13268:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   13269:                     $loncaparevs{$hostid}=$loncaparev;
                   13270:                 }
                   13271:                 close($config);
                   13272:             }
                   13273:         }
                   13274:     }
                   13275: }
                   13276: 
                   13277: # ----------------------------------------------------- Read serverhostID table
                   13278: {
                   13279:     sub load_serverhomeIDs {
                   13280:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  13281:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  13282:                 while (my $configline=<$config>) {
                   13283:                     chomp($configline);
                   13284:                     my ($name,$id)=split(/:/,$configline);
                   13285:                     $serverhomeIDs{$name}=$id;
                   13286:                 }
                   13287:                 close($config);
                   13288:             }
                   13289:         }
                   13290:     }
                   13291: }
                   13292: 
                   13293: 
1.862     albertel 13294: BEGIN {
                   13295: 
                   13296: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   13297:     unless ($readit) {
                   13298: {
                   13299:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   13300:     %perlvar = (%perlvar,%{$configvars});
                   13301: }
                   13302: 
                   13303: 
1.1       albertel 13304: # ------------------------------------------------------ Read spare server file
                   13305: {
1.1172.2.96  raeburn  13306:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 13307: 
                   13308:     while (my $configline=<$config>) {
                   13309:        chomp($configline);
1.284     matthew  13310:        if ($configline) {
1.784     albertel 13311: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 13312: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 13313: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 13314:        }
                   13315:     }
1.448     albertel 13316:     close($config);
1.1       albertel 13317: }
1.11      www      13318: # ------------------------------------------------------------ Read permissions
                   13319: {
1.1172.2.96  raeburn  13320:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      13321: 
                   13322:     while (my $configline=<$config>) {
1.448     albertel 13323: 	chomp($configline);
                   13324: 	if ($configline) {
                   13325: 	    my ($role,$perm)=split(/ /,$configline);
                   13326: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   13327: 	}
1.11      www      13328:     }
1.448     albertel 13329:     close($config);
1.11      www      13330: }
                   13331: 
                   13332: # -------------------------------------------- Read plain texts for permissions
                   13333: {
1.1172.2.96  raeburn  13334:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      13335: 
                   13336:     while (my $configline=<$config>) {
1.448     albertel 13337: 	chomp($configline);
                   13338: 	if ($configline) {
1.742     raeburn  13339: 	    my ($short,@plain)=split(/:/,$configline);
                   13340:             %{$prp{$short}} = ();
                   13341: 	    if (@plain > 0) {
                   13342:                 $prp{$short}{'std'} = $plain[0];
                   13343:                 for (my $i=1; $i<@plain; $i++) {
                   13344:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   13345:                 }
                   13346:             }
1.448     albertel 13347: 	}
1.135     www      13348:     }
1.448     albertel 13349:     close($config);
1.135     www      13350: }
                   13351: 
                   13352: # ---------------------------------------------------------- Read package table
                   13353: {
1.1172.2.96  raeburn  13354:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      13355: 
                   13356:     while (my $configline=<$config>) {
1.483     albertel 13357: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 13358: 	chomp($configline);
                   13359: 	my ($short,$plain)=split(/:/,$configline);
                   13360: 	my ($pack,$name)=split(/\&/,$short);
                   13361: 	if ($plain ne '') {
                   13362: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   13363: 	    $packagetab{$short}=$plain; 
                   13364: 	}
1.11      www      13365:     }
1.448     albertel 13366:     close($config);
1.329     matthew  13367: }
                   13368: 
1.1172.2.27  raeburn  13369: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  13370: 
1.1172.2.27  raeburn  13371: &load_loncaparevs();
                   13372: 
                   13373: # ------------------------------------------------------- Read serverhostID table
                   13374: 
                   13375: &load_serverhomeIDs();
1.1074    raeburn  13376: 
1.1172.2.27  raeburn  13377: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  13378: {
                   13379:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   13380:     if (-e $file) {
                   13381:         my $parser = HTML::LCParser->new($file);
                   13382:         while (my $token = $parser->get_token()) {
                   13383:             if ($token->[0] eq 'S') {
                   13384:                 my $item = $token->[1];
                   13385:                 my $name = $token->[2]{'name'};
                   13386:                 my $value = $token->[2]{'value'};
                   13387:                 if ($item ne '' && $name ne '' && $value ne '') {
                   13388:                     my $release = $parser->get_text();
                   13389:                     $release =~ s/(^\s*|\s*$ )//gx;
                   13390:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   13391:                 }
                   13392:             }
                   13393:         }
                   13394:     }
1.1073    raeburn  13395: }
                   13396: 
1.1138    raeburn  13397: # ---------------------------------------------------------- Read managers table
                   13398: {
                   13399:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  13400:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  13401:             while (my $configline=<$config>) {
                   13402:                 chomp($configline);
                   13403:                 next if ($configline =~ /^\#/);
                   13404:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   13405:                     $managerstab{$configline} = 1;
                   13406:                 }
                   13407:             }
                   13408:             close($config);
                   13409:         }
                   13410:     }
                   13411: }
                   13412: 
1.329     matthew  13413: # ------------- set up temporary directory
                   13414: {
1.1117    foxr     13415:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  13416: 
1.11      www      13417: }
                   13418: 
1.794     albertel 13419: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   13420: 				'compress_threshold'=> 20_000,
                   13421:  			        });
1.185     www      13422: 
1.281     www      13423: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      13424: $dumpcount=0;
1.958     www      13425: $locknum=0;
1.22      www      13426: 
1.163     harris41 13427: &logtouch();
1.672     albertel 13428: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      13429: $readit=1;
1.564     albertel 13430:     {
                   13431: 	use integer;
                   13432: 	my $test=(2**32)+1;
1.568     albertel 13433: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 13434: 	&logthis(" Detected 64bit platform ($_64bit)");
                   13435:     }
1.195     www      13436: }
1.1       albertel 13437: }
1.179     www      13438: 
1.1       albertel 13439: 1;
1.191     harris41 13440: __END__
                   13441: 
1.243     albertel 13442: =pod
                   13443: 
1.191     harris41 13444: =head1 NAME
                   13445: 
1.243     albertel 13446: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 13447: 
                   13448: =head1 SYNOPSIS
                   13449: 
1.243     albertel 13450: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 13451: 
                   13452:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   13453: 
1.243     albertel 13454: Common parameters:
                   13455: 
                   13456: =over 4
                   13457: 
                   13458: =item *
                   13459: 
                   13460: $uname : an internal username (if $cname expecting a course Id specifically)
                   13461: 
                   13462: =item *
                   13463: 
                   13464: $udom : a domain (if $cdom expecting a course's domain specifically)
                   13465: 
                   13466: =item *
                   13467: 
                   13468: $symb : a resource instance identifier
                   13469: 
                   13470: =item *
                   13471: 
                   13472: $namespace : the name of a .db file that contains the data needed or
                   13473: being set.
                   13474: 
                   13475: =back
                   13476: 
1.394     bowersj2 13477: =head1 OVERVIEW
1.191     harris41 13478: 
1.394     bowersj2 13479: lonnet provides subroutines which interact with the
                   13480: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   13481: about classes, users, and resources.
1.243     albertel 13482: 
                   13483: For many of these objects you can also use this to store data about
                   13484: them or modify them in various ways.
1.191     harris41 13485: 
1.394     bowersj2 13486: =head2 Symbs
1.191     harris41 13487: 
1.394     bowersj2 13488: To identify a specific instance of a resource, LON-CAPA uses symbols
                   13489: or "symbs"X<symb>. These identifiers are built from the URL of the
                   13490: map, the resource number of the resource in the map, and the URL of
                   13491: the resource itself. The latter is somewhat redundant, but might help
                   13492: if maps change.
                   13493: 
                   13494: An example is
                   13495: 
                   13496:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   13497: 
                   13498: The respective map entry is
                   13499: 
                   13500:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   13501:   title="Problem 2">
                   13502:  </resource>
                   13503: 
                   13504: Symbs are used by the random number generator, as well as to store and
                   13505: restore data specific to a certain instance of for example a problem.
                   13506: 
                   13507: =head2 Storing And Retrieving Data
                   13508: 
                   13509: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   13510: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   13511: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   13512: is is the non-critical message twin of cstore. These functions are for
                   13513: handlers to store a perl hash to a user's permanent data space in an
                   13514: easy manner, and to retrieve it again on another call. It is expected
                   13515: that a handler would use this once at the beginning to retrieve data,
                   13516: and then again once at the end to send only the new data back.
                   13517: 
                   13518: The data is stored in the user's data directory on the user's
                   13519: homeserver under the ID of the course.
                   13520: 
                   13521: The hash that is returned by restore will have all of the previous
                   13522: value for all of the elements of the hash.
                   13523: 
                   13524: Example:
                   13525: 
                   13526:  #creating a hash
                   13527:  my %hash;
                   13528:  $hash{'foo'}='bar';
                   13529: 
                   13530:  #storing it
                   13531:  &Apache::lonnet::cstore(\%hash);
                   13532: 
                   13533:  #changing a value
                   13534:  $hash{'foo'}='notbar';
                   13535: 
                   13536:  #adding a new value
                   13537:  $hash{'bar'}='foo';
                   13538:  &Apache::lonnet::cstore(\%hash);
                   13539: 
                   13540:  #retrieving the hash
                   13541:  my %history=&Apache::lonnet::restore();
                   13542: 
                   13543:  #print the hash
                   13544:  foreach my $key (sort(keys(%history))) {
                   13545:    print("\%history{$key} = $history{$key}");
                   13546:  }
                   13547: 
                   13548: Will print out:
1.191     harris41 13549: 
1.394     bowersj2 13550:  %history{1:foo} = bar
                   13551:  %history{1:keys} = foo:timestamp
                   13552:  %history{1:timestamp} = 990455579
                   13553:  %history{2:bar} = foo
                   13554:  %history{2:foo} = notbar
                   13555:  %history{2:keys} = foo:bar:timestamp
                   13556:  %history{2:timestamp} = 990455580
                   13557:  %history{bar} = foo
                   13558:  %history{foo} = notbar
                   13559:  %history{timestamp} = 990455580
                   13560:  %history{version} = 2
                   13561: 
                   13562: Note that the special hash entries C<keys>, C<version> and
                   13563: C<timestamp> were added to the hash. C<version> will be equal to the
                   13564: total number of versions of the data that have been stored. The
                   13565: C<timestamp> attribute will be the UNIX time the hash was
                   13566: stored. C<keys> is available in every historical section to list which
                   13567: keys were added or changed at a specific historical revision of a
                   13568: hash.
                   13569: 
                   13570: B<Warning>: do not store the hash that restore returns directly. This
                   13571: will cause a mess since it will restore the historical keys as if the
                   13572: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 13573: 
1.394     bowersj2 13574: Calling convention:
1.191     harris41 13575: 
1.1172.2.27  raeburn  13576:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  13577:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 13578: 
1.394     bowersj2 13579: For more detailed information, see lonnet specific documentation.
1.191     harris41 13580: 
1.394     bowersj2 13581: =head1 RETURN MESSAGES
1.191     harris41 13582: 
1.394     bowersj2 13583: =over 4
1.191     harris41 13584: 
1.394     bowersj2 13585: =item * B<con_lost>: unable to contact remote host
1.191     harris41 13586: 
1.394     bowersj2 13587: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   13588: when the connection is brought back up
1.191     harris41 13589: 
1.394     bowersj2 13590: =item * B<con_failed>: unable to contact remote host and unable to save message
                   13591: for later delivery
1.191     harris41 13592: 
1.967     bisitz   13593: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 13594: 
1.394     bowersj2 13595: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 13596: that was requested
1.191     harris41 13597: 
1.243     albertel 13598: =back
1.191     harris41 13599: 
1.243     albertel 13600: =head1 PUBLIC SUBROUTINES
1.191     harris41 13601: 
1.243     albertel 13602: =head2 Session Environment Functions
1.191     harris41 13603: 
1.243     albertel 13604: =over 4
1.191     harris41 13605: 
1.394     bowersj2 13606: =item * 
                   13607: X<appenv()>
1.949     raeburn  13608: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 13609: the user envirnoment file, and will be restored for each access this
1.620     albertel 13610: user makes during this session, also modifies the %env for the current
1.949     raeburn  13611: process. Optional rolesarrayref - if defined contains a reference to an array
                   13612: of roles which are exempt from the restriction on modifying user.role entries 
                   13613: in the user's environment.db and in %env.    
1.191     harris41 13614: 
                   13615: =item *
1.394     bowersj2 13616: X<delenv()>
1.987     raeburn  13617: B<delenv($delthis,$regexp)>: removes all items from the session
                   13618: environment file that begin with $delthis. If the 
                   13619: optional second arg - $regexp - is true, $delthis is treated as a 
                   13620: regular expression, otherwise \Q$delthis\E is used. 
                   13621: The values are also deleted from the current processes %env.
1.191     harris41 13622: 
1.795     albertel 13623: =item * get_env_multiple($name) 
                   13624: 
                   13625: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   13626: values may be defined and end up as an array ref.
                   13627: 
                   13628: returns an array of values
                   13629: 
1.243     albertel 13630: =back
                   13631: 
                   13632: =head2 User Information
1.191     harris41 13633: 
1.243     albertel 13634: =over 4
1.191     harris41 13635: 
                   13636: =item *
1.394     bowersj2 13637: X<queryauthenticate()>
                   13638: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 13639: authentication scheme
                   13640: 
                   13641: =item *
1.394     bowersj2 13642: X<authenticate()>
1.1073    raeburn  13643: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 13644: authenticate user from domain's lib servers (first use the current
                   13645: one). C<$upass> should be the users password.
1.1073    raeburn  13646: $checkdefauth is optional (value is 1 if a check should be made to
                   13647:    authenticate user using default authentication method, and allow
                   13648:    account creation if username does not have account in the domain).
                   13649: $clientcancheckhost is optional (value is 1 if checking whether the
                   13650:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 13651: 
                   13652: =item *
1.394     bowersj2 13653: X<homeserver()>
                   13654: B<homeserver($uname,$udom)>: find the server which has
                   13655: the user's directory and files (there must be only one), this caches
                   13656: the answer, and also caches if there is a borken connection.
1.191     harris41 13657: 
                   13658: =item *
1.394     bowersj2 13659: X<idget()>
                   13660: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   13661: (IDs are a unique resource in a domain, there must be only 1 ID per
                   13662: username, and only 1 username per ID in a specific domain) (returns
                   13663: hash: id=>name,id=>name)
1.191     harris41 13664: 
                   13665: =item *
1.394     bowersj2 13666: X<idrget()>
                   13667: B<idrget($udom,@unames)>: find the IDs behind a list of
                   13668: usernames (returns hash: name=>id,name=>id)
1.191     harris41 13669: 
                   13670: =item *
1.394     bowersj2 13671: X<idput()>
                   13672: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 13673: 
                   13674: =item *
1.394     bowersj2 13675: X<rolesinit()>
1.1169    droeschl 13676: B<rolesinit($udom,$username)>: get user privileges.
                   13677: returns user role, first access and timer interval hashes
1.243     albertel 13678: 
                   13679: =item *
1.1171    droeschl 13680: X<privileged()>
                   13681: B<privileged($username,$domain)>: returns a true if user has a
                   13682: privileged and active role (i.e. su or dc), false otherwise.
                   13683: 
                   13684: =item *
1.551     albertel 13685: X<getsection()>
                   13686: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 13687: course $cname, return section name/number or '' for "not in course"
                   13688: and '-1' for "no section"
                   13689: 
                   13690: =item *
1.394     bowersj2 13691: X<userenvironment()>
                   13692: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 13693: passed in @what from the requested user's environment, returns a hash
                   13694: 
1.858     raeburn  13695: =item * 
                   13696: X<userlog_query()>
1.859     albertel 13697: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   13698: activity.log file. %filters defines filters applied when parsing the
                   13699: log file. These can be start or end timestamps, or the type of action
                   13700: - log to look for Login or Logout events, check for Checkin or
                   13701: Checkout, role for role selection. The response is in the form
                   13702: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   13703: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  13704: 
1.243     albertel 13705: =back
                   13706: 
                   13707: =head2 User Roles
                   13708: 
                   13709: =over 4
                   13710: 
                   13711: =item *
                   13712: 
1.1172.2.65  raeburn  13713: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   13714: returns codes for allowed actions.
                   13715: 
                   13716: The first argument is required, all others are optional.
                   13717: 
                   13718: $priv is the privilege being checked.
                   13719: $uri contains additional information about what is being checked for access (e.g.,
                   13720: URL, course ID etc.).
                   13721: $symb is the unique resource instance identifier in a course; if needed,
                   13722: but not provided, it will be retrieved via a call to &symbread().
                   13723: $role is the role for which a priv is being checked (only used if priv is evb).
                   13724: $clientip is the user's IP address (only used when checking for access to portfolio
                   13725: files).
                   13726: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   13727: prevents recursive calls to &allowed.
                   13728: 
1.243     albertel 13729:  F: full access
                   13730:  U,I,K: authentication modes (cxx only)
                   13731:  '': forbidden
                   13732:  1: user needs to choose course
                   13733:  2: browse allowed
1.766     albertel 13734:  A: passphrase authentication needed
1.1172.2.65  raeburn  13735:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 13736: 
                   13737: =item *
                   13738: 
1.1172.2.13  raeburn  13739: constructaccess($url,$setpriv) : check for access to construction space URL
                   13740: 
                   13741: See if the owner domain and name in the URL match those in the
                   13742: expected environment.  If so, return three element list
                   13743: ($ownername,$ownerdomain,$ownerhome).
                   13744: 
                   13745: Otherwise return the null string.
                   13746: 
                   13747: If second argument 'setpriv' is true, it assigns the privileges,
                   13748: and returns the same three element list, unless the owner has
                   13749: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   13750: in which case the null string is returned.
                   13751: 
                   13752: =item *
                   13753: 
1.1172.2.84  raeburn  13754: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   13755: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   13756: for system, domain, and course level. $uname and $udom are optional (current
                   13757: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 13758: 
                   13759: =item *
                   13760: 
1.988     raeburn  13761: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   13762: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  13763: $type is Course (default) or Community.
1.988     raeburn  13764: If $forcedefault evaluates to true, text returned will be default 
                   13765: text for $type. Otherwise, if this is a course, the text returned 
                   13766: will be a custom name for the role (if defined in the course's 
                   13767: environment).  If no custom name is defined the default is returned.
                   13768:    
1.832     raeburn  13769: =item *
                   13770: 
1.1172.2.23  raeburn  13771: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  13772: All arguments are optional. Returns a hash of a roles, either for
                   13773: co-author/assistant author roles for a user's Construction Space
1.906     albertel 13774: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  13775: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   13776: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   13777: For each key, value is set to colon-separated start and end times for
                   13778: the role.  If no username and domain are specified, will default to
1.934     raeburn  13779: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  13780: of role statuses (active, future or previous), roles 
                   13781: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   13782: to restrict the list of roles reported. If no array ref is 
                   13783: provided for types, will default to return only active roles.
1.834     albertel 13784: 
1.1172.2.13  raeburn  13785: =item *
                   13786: 
                   13787: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   13788: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   13789: 
                   13790: Additional optional arguments are: $type (if role checking is to be restricted
                   13791: to certain user status types -- previous (expired roles), active (currently
                   13792: available roles) or future (roles available in the future), and
                   13793: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  13794: have active Domain Coordinator role in course's domain or in additional
                   13795: domains (specified in 'Domains to check for privileged users' in course
                   13796: environment -- set via:  Course Settings -> Classlists and staff listing).
                   13797: 
                   13798: =item *
                   13799: 
                   13800: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   13801: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   13802: $possdomains and $possroles are optional array refs -- to domains to check and
                   13803: roles to check.  If $possdomains is not specified, a dump will be done of the
                   13804: users' roles.db to check for a dc or su role in any domain. This can be
                   13805: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   13806: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   13807: this then allows &privileged_by_domain() to be used, which caches the identity
                   13808: of privileged users, eliminating the need for repeated calls to &dump().
                   13809: 
                   13810: =item *
                   13811: 
                   13812: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   13813: where the outer hash keys are domains specified in the $possdomains array ref,
                   13814: next inner hash keys are privileged roles specified in the $roles array ref,
                   13815: and the innermost hash contains key = value pairs for username:domain = end:start
                   13816: for active or future "privileged" users with that role in that domain. To avoid
                   13817: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   13818: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  13819: 
1.243     albertel 13820: =back
                   13821: 
                   13822: =head2 User Modification
                   13823: 
                   13824: =over 4
                   13825: 
                   13826: =item *
                   13827: 
1.957     raeburn  13828: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 13829: user for the level given by URL.  Optional start and end dates (leave empty
                   13830: string or zero for "no date")
1.191     harris41 13831: 
                   13832: =item *
                   13833: 
1.243     albertel 13834: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   13835: change a users, password, possible return values are: ok,
                   13836: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   13837: refused
1.191     harris41 13838: 
                   13839: =item *
                   13840: 
1.243     albertel 13841: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 13842: 
                   13843: =item *
                   13844: 
1.1058    raeburn  13845: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   13846:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   13847: 
                   13848: will update user information (firstname,middlename,lastname,generation,
                   13849: permanentemail), and if forceid is true, student/employee ID also.
                   13850: A user's institutional affiliation(s) can also be updated.
                   13851: User information fields will not be overwritten with empty entries 
                   13852: unless the field is included in the $candelete array reference.
                   13853: This array is included when a single user is modified via "Manage Users",
                   13854: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 13855: 
                   13856: =item *
                   13857: 
1.286     matthew  13858: modifystudent
                   13859: 
1.957     raeburn  13860: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  13861: The course id is resolved based on the current user's environment.  
                   13862: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  13863: associated with a course.
                   13864: 
1.297     matthew  13865: This call is essentially a wrapper for lonnet::modifyuser and
                   13866: lonnet::modify_student_enrollment
1.286     matthew  13867: 
                   13868: Inputs: 
                   13869: 
                   13870: =over 4
                   13871: 
1.957     raeburn  13872: =item B<$udom> Student's loncapa domain
1.286     matthew  13873: 
1.957     raeburn  13874: =item B<$uname> Student's loncapa login name
1.286     matthew  13875: 
1.964     bisitz   13876: =item B<$uid> Student/Employee ID
1.286     matthew  13877: 
1.957     raeburn  13878: =item B<$umode> Student's authentication mode
1.286     matthew  13879: 
1.957     raeburn  13880: =item B<$upass> Student's password
1.286     matthew  13881: 
1.957     raeburn  13882: =item B<$first> Student's first name
1.286     matthew  13883: 
1.957     raeburn  13884: =item B<$middle> Student's middle name
1.286     matthew  13885: 
1.957     raeburn  13886: =item B<$last> Student's last name
1.286     matthew  13887: 
1.957     raeburn  13888: =item B<$gene> Student's generation
1.286     matthew  13889: 
1.957     raeburn  13890: =item B<$usec> Student's section in course
1.286     matthew  13891: 
                   13892: =item B<$end> Unix time of the roles expiration
                   13893: 
                   13894: =item B<$start> Unix time of the roles start date
                   13895: 
                   13896: =item B<$forceid> If defined, allow $uid to be changed
                   13897: 
                   13898: =item B<$desiredhome> server to use as home server for student
                   13899: 
1.957     raeburn  13900: =item B<$email> Student's permanent e-mail address
                   13901: 
                   13902: =item B<$type> Type of enrollment (auto or manual)
                   13903: 
1.963     raeburn  13904: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   13905: 
                   13906: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  13907: 
1.963     raeburn  13908: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  13909: 
1.963     raeburn  13910: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  13911: 
1.1172.2.19  raeburn  13912: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   13913: 
                   13914: =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  13915: 
1.286     matthew  13916: =back
1.297     matthew  13917: 
                   13918: =item *
                   13919: 
                   13920: modify_student_enrollment
                   13921: 
1.1172.2.31  raeburn  13922: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  13923: 'role.request.course' must be defined for this function to proceed.
                   13924: 
                   13925: Inputs:
                   13926: 
                   13927: =over 4
                   13928: 
1.1172.2.31  raeburn  13929: =item $udom, student's domain
1.297     matthew  13930: 
1.1172.2.31  raeburn  13931: =item $uname, student's name
1.297     matthew  13932: 
1.1172.2.31  raeburn  13933: =item $uid, student's user id
1.297     matthew  13934: 
1.1172.2.31  raeburn  13935: =item $first, student's first name
1.297     matthew  13936: 
                   13937: =item $middle
                   13938: 
                   13939: =item $last
                   13940: 
                   13941: =item $gene
                   13942: 
                   13943: =item $usec
                   13944: 
                   13945: =item $end
                   13946: 
                   13947: =item $start
                   13948: 
1.957     raeburn  13949: =item $type
                   13950: 
                   13951: =item $locktype
                   13952: 
                   13953: =item $cid
                   13954: 
                   13955: =item $selfenroll
                   13956: 
                   13957: =item $context
                   13958: 
1.1172.2.19  raeburn  13959: =item $credits, number of credits student will earn from this class
                   13960: 
1.1172.2.76  raeburn  13961: =item $instsec, institutional course section code for student
                   13962: 
1.297     matthew  13963: =back
                   13964: 
1.191     harris41 13965: 
                   13966: =item *
                   13967: 
1.243     albertel 13968: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   13969: custom role; give a custom role to a user for the level given by URL.  Specify
                   13970: name and domain of role author, and role name
1.191     harris41 13971: 
                   13972: =item *
                   13973: 
1.243     albertel 13974: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 13975: 
                   13976: =item *
                   13977: 
1.243     albertel 13978: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   13979: 
                   13980: =back
                   13981: 
                   13982: =head2 Course Infomation
                   13983: 
                   13984: =over 4
1.191     harris41 13985: 
                   13986: =item *
                   13987: 
1.1118    foxr     13988: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 13989: specified course id, including all environment settings for the
                   13990: course, the description of the course will be in the hash under the
                   13991: key 'description'
1.191     harris41 13992: 
1.1118    foxr     13993: $options is an optional parameter that if supplied is a hash reference that controls
                   13994: what how this function works.  It has the following key/values:
                   13995: 
                   13996: =over 4
                   13997: 
                   13998: =item freshen_cache
                   13999: 
                   14000: If defined, and the environment cache for the course is valid, it is 
                   14001: returned in the returned hash.
                   14002: 
                   14003: =item one_time
                   14004: 
                   14005: If defined, the last cache time is set to _now_
                   14006: 
                   14007: =item user
                   14008: 
                   14009: If defined, the supplied username is used instead of the current user.
                   14010: 
                   14011: 
                   14012: =back
                   14013: 
1.191     harris41 14014: =item *
                   14015: 
1.624     albertel 14016: resdata($name,$domain,$type,@which) : request for current parameter
                   14017: setting for a specific $type, where $type is either 'course' or 'user',
                   14018: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  14019: answers for 10 minutes.
1.243     albertel 14020: 
1.877     foxr     14021: =item *
                   14022: 
                   14023: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14024: data base, returning a hash that is keyed by the resource name and has
                   14025: values that are the resource value.  I believe that the timestamps and
                   14026: versions are also returned.
                   14027: 
1.1172.2.31  raeburn  14028: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14029: supplemental content area. This routine caches the number of files for
                   14030: 10 minutes.
                   14031: 
1.243     albertel 14032: =back
                   14033: 
                   14034: =head2 Course Modification
                   14035: 
                   14036: =over 4
1.191     harris41 14037: 
                   14038: =item *
                   14039: 
1.243     albertel 14040: writecoursepref($courseid,%prefs) : write preferences (environment
                   14041: database) for a course
1.191     harris41 14042: 
                   14043: =item *
                   14044: 
1.1011    raeburn  14045: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14046: 
                   14047: =item *
                   14048: 
1.1038    raeburn  14049: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14050: 
1.1167    droeschl 14051: =item *
                   14052: 
                   14053: is_course($courseid), is_course($cdom, $cnum)
                   14054: 
                   14055: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14056: two component version $cdom, $cnum. It checks if the specified course exists.
                   14057: 
                   14058: Returns:
                   14059:     undef if the course doesn't exist, otherwise
                   14060:     in scalar context the combined courseid.
                   14061:     in list context the two components of the course identifier, domain and 
                   14062:     courseid.    
                   14063: 
1.243     albertel 14064: =back
                   14065: 
                   14066: =head2 Resource Subroutines
                   14067: 
                   14068: =over 4
1.191     harris41 14069: 
                   14070: =item *
                   14071: 
1.243     albertel 14072: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 14073: 
                   14074: =item *
                   14075: 
1.243     albertel 14076: repcopy($filename) : subscribes to the requested file, and attempts to
                   14077: replicate from the owning library server, Might return
1.607     raeburn  14078: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   14079: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 14080: resource. Expects the local filesystem pathname
                   14081: (/home/httpd/html/res/....)
                   14082: 
                   14083: =back
                   14084: 
                   14085: =head2 Resource Information
                   14086: 
                   14087: =over 4
1.191     harris41 14088: 
                   14089: =item *
                   14090: 
1.1172.2.28  raeburn  14091: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   14092: and returns the value of a variety of different possible values,
                   14093: $varname should be a request string, and the other parameters can be
                   14094: used to specify who and what one is asking about. Ordinarily, $cid 
                   14095: does not need to be specified, as it is retrived from 
                   14096: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14097: within lonuserstate::loadmap() when initializing a course, before
                   14098: $env{'request.course.id'} has been set, so it needs to be provided
                   14099: in that one case.
1.243     albertel 14100: 
                   14101: Possible values for $varname are environment.lastname (or other item
                   14102: from the envirnment hash), user.name (or someother aspect about the
                   14103: user), resource.0.maxtries (or some other part and parameter of a
                   14104: resource)
1.204     albertel 14105: 
                   14106: =item *
                   14107: 
1.243     albertel 14108: directcondval($number) : get current value of a condition; reads from a state
                   14109: string
1.204     albertel 14110: 
                   14111: =item *
                   14112: 
1.243     albertel 14113: condval($condidx) : value of condition index based on state
1.204     albertel 14114: 
                   14115: =item *
                   14116: 
1.243     albertel 14117: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   14118: resource's metadata, $what should be either a specific key, or either
                   14119: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   14120: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   14121: 
                   14122: this function automatically caches all requests
1.191     harris41 14123: 
                   14124: =item *
                   14125: 
1.243     albertel 14126: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   14127: network of library servers; returns file handle of where SQL and regex results
                   14128: will be stored for query
1.191     harris41 14129: 
                   14130: =item *
                   14131: 
1.1172.2.66  raeburn  14132: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   14133: return symbolic list entry (all arguments optional).
                   14134: 
                   14135: Args: filename is the filename (including path) for the file for which a symb
                   14136: is required; donotrecurse, if true will prevent calls to allowed() being made
                   14137: to check access status if more than one resource was found in the bighash
                   14138: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   14139: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   14140: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   14141: cause possible symbs to be checked to determine if they are subject to content
                   14142: blocking, if so they will not be included as possible symbs; possibles is a
                   14143: ref to a hash, which, as a side effect, will be populated with all possible
                   14144: symbs (content blocking not tested).
                   14145: 
1.243     albertel 14146: returns the data handle
1.191     harris41 14147: 
                   14148: =item *
                   14149: 
1.1172.2.17  raeburn  14150: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  14151: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 14152: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  14153: on failure, user must be in a course, as it assumes the existence of
                   14154: the course initial hash, and uses $env('request.course.id'}.  The third
                   14155: arg is an optional reference to a scalar.  If this arg is passed in the
                   14156: call to symbverify, it will be set to 1 if the symb has been set to be 
                   14157: encrypted; otherwise it will be null.
1.243     albertel 14158: 
1.191     harris41 14159: =item *
                   14160: 
1.243     albertel 14161: symbclean($symb) : removes versions numbers from a symb, returns the
                   14162: cleaned symb
1.191     harris41 14163: 
                   14164: =item *
                   14165: 
1.243     albertel 14166: is_on_map($uri) : checks if the $uri is somewhere on the current
                   14167: course map, user must be in a course for it to work.
1.191     harris41 14168: 
                   14169: =item *
                   14170: 
1.243     albertel 14171: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 14172: 
                   14173: =item *
                   14174: 
1.243     albertel 14175: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   14176: a random seed, all arguments are optional, if they aren't sent it uses the
                   14177: environment to derive them. Note: if symb isn't sent and it can't get one
                   14178: from &symbread it will use the current time as its return value
1.191     harris41 14179: 
                   14180: =item *
                   14181: 
1.243     albertel 14182: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   14183: unfakeable, receipt
1.191     harris41 14184: 
                   14185: =item *
                   14186: 
1.620     albertel 14187: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 14188: 
                   14189: =item *
                   14190: 
1.243     albertel 14191: countacc($url) : count the number of accesses to a given URL
1.191     harris41 14192: 
                   14193: =item *
                   14194: 
1.243     albertel 14195: 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 14196: 
                   14197: =item *
                   14198: 
1.243     albertel 14199: 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 14200: 
                   14201: =item *
                   14202: 
1.243     albertel 14203: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 14204: 
                   14205: =item *
                   14206: 
1.243     albertel 14207: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   14208: forcing spreadsheet to reevaluate the resource scores next time.
                   14209: 
1.1172.2.13  raeburn  14210: =item *
                   14211: 
                   14212: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   14213: when viewing in course context.
                   14214: 
                   14215:  input: six args -- filename (decluttered), course number, course domain,
                   14216:                     url, symb (if registered) and group (if this is a
                   14217:                     group item -- e.g., bulletin board, group page etc.).
                   14218: 
                   14219:  output: array of five scalars --
                   14220:          $cfile -- url for file editing if editable on current server
                   14221:          $home -- homeserver of resource (i.e., for author if published,
                   14222:                                           or course if uploaded.).
                   14223:          $switchserver --  1 if server switch will be needed.
                   14224:          $forceedit -- 1 if icon/link should be to go to edit mode
                   14225:          $forceview -- 1 if icon/link should be to go to view mode
                   14226: 
                   14227: =item *
                   14228: 
                   14229: is_course_upload($file,$cnum,$cdom)
                   14230: 
                   14231: Used in course context to determine if current file was uploaded to
                   14232: the course (i.e., would be found in /userfiles/docs on the course's
                   14233: homeserver.
                   14234: 
                   14235:   input: 3 args -- filename (decluttered), course number and course domain.
                   14236:   output: boolean -- 1 if file was uploaded.
                   14237: 
1.243     albertel 14238: =back
                   14239: 
                   14240: =head2 Storing/Retreiving Data
                   14241: 
                   14242: =over 4
1.191     harris41 14243: 
                   14244: =item *
                   14245: 
1.1172.2.64  raeburn  14246: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   14247: permanently for this url; hashref needs to be given and should be a \%hashname;
                   14248: the remaining args aren't required and if they aren't passed or are '' they will
                   14249: be derived from the env (with the exception of $laststore, which is an
                   14250: optional arg used when a user's submission is stored in grading).
                   14251: $laststore is $version=$timestamp, where $version is the most recent version
                   14252: number retrieved for the corresponding $symb in the $namespace db file, and
                   14253: $timestamp is the timestamp for that transaction (UNIX time).
                   14254: $laststore is currently only passed when cstore() is called by
                   14255: structuretags::finalize_storage().
1.191     harris41 14256: 
                   14257: =item *
                   14258: 
1.1172.2.64  raeburn  14259: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   14260: but uses critical subroutine
1.191     harris41 14261: 
                   14262: =item *
                   14263: 
1.243     albertel 14264: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   14265: all args are optional
1.191     harris41 14266: 
                   14267: =item *
                   14268: 
1.717     albertel 14269: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   14270: dumps the complete (or key matching regexp) namespace into a hash
                   14271: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   14272: normally &store()ed into
                   14273: 
                   14274: $range should be either an integer '100' (give me the first 100
                   14275:                                            matching records)
                   14276:               or be  two integers sperated by a - with no spaces
                   14277:                  '30-50' (give me the 30th through the 50th matching
                   14278:                           records)
                   14279: 
                   14280: 
                   14281: =item *
                   14282: 
1.1172.2.59  raeburn  14283: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 14284: replaces a &store() version of data with a replacement set of data
                   14285: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  14286: reference. If $tolog is true, the transaction is logged in the courselog
                   14287: with an action=PUTSTORE.
1.717     albertel 14288: 
                   14289: =item *
                   14290: 
1.243     albertel 14291: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   14292: works very similar to store/cstore, but all data is stored in a
                   14293: temporary location and can be reset using tmpreset, $storehash should
                   14294: be a hash reference, returns nothing on success
1.191     harris41 14295: 
                   14296: =item *
                   14297: 
1.243     albertel 14298: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   14299: similar to restore, but all data is stored in a temporary location and
                   14300: can be reset using tmpreset. Returns a hash of values on success,
                   14301: error string otherwise.
1.191     harris41 14302: 
                   14303: =item *
                   14304: 
1.243     albertel 14305: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   14306: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 14307: 
                   14308: =item *
                   14309: 
1.243     albertel 14310: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14311: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 14312: 
                   14313: =item *
                   14314: 
1.243     albertel 14315: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   14316: namesp ($udom and $uname are optional)
1.191     harris41 14317: 
                   14318: =item *
                   14319: 
1.702     albertel 14320: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 14321: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 14322: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  14323: 
1.702     albertel 14324: $range should be either an integer '100' (give me the first 100
                   14325:                                            matching records)
                   14326:               or be  two integers sperated by a - with no spaces
                   14327:                  '30-50' (give me the 30th through the 50th matching
                   14328:                           records)
1.449     matthew  14329: =item *
                   14330: 
                   14331: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   14332: $store can be a scalar, an array reference, or if the amount to be 
                   14333: incremented is > 1, a hash reference.
                   14334: 
                   14335: ($udom and $uname are optional)
1.191     harris41 14336: 
                   14337: =item *
                   14338: 
1.243     albertel 14339: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   14340: ($udom and $uname are optional)
1.191     harris41 14341: 
                   14342: =item *
                   14343: 
1.243     albertel 14344: cput($namespace,$storehash,$udom,$uname) : critical put
                   14345: ($udom and $uname are optional)
1.191     harris41 14346: 
                   14347: =item *
                   14348: 
1.748     albertel 14349: newput($namespace,$storehash,$udom,$uname) :
                   14350: 
                   14351: Attempts to store the items in the $storehash, but only if they don't
                   14352: currently exist, if this succeeds you can be certain that you have 
                   14353: successfully created a new key value pair in the $namespace db.
                   14354: 
                   14355: 
                   14356: Args:
                   14357:  $namespace: name of database to store values to
                   14358:  $storehash: hashref to store to the db
                   14359:  $udom: (optional) domain of user containing the db
                   14360:  $uname: (optional) name of user caontaining the db
                   14361: 
                   14362: Returns:
                   14363:  'ok' -> succeeded in storing all keys of $storehash
                   14364:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   14365:                         least <key> already existed in the db (other
                   14366:                         requested keys may also already exist)
1.967     bisitz   14367:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 14368:  'con_lost' -> unable to contact request server
                   14369:  'refused' -> action was not allowed by remote machine
                   14370: 
                   14371: 
                   14372: =item *
                   14373: 
1.243     albertel 14374: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14375: reference filled in from namesp (encrypts the return communication)
                   14376: ($udom and $uname are optional)
1.191     harris41 14377: 
                   14378: =item *
                   14379: 
1.243     albertel 14380: log($udom,$name,$home,$message) : write to permanent log for user; use
                   14381: critical subroutine
                   14382: 
1.806     raeburn  14383: =item *
                   14384: 
1.860     raeburn  14385: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   14386: array reference filled in from namespace found in domain level on either
                   14387: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  14388: 
                   14389: =item *
                   14390: 
1.860     raeburn  14391: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   14392: domain level either on specified domain server ($uhome) or primary domain 
                   14393: server ($udom and $uhome are optional)
1.806     raeburn  14394: 
1.943     raeburn  14395: =item * 
                   14396: 
1.1172.2.35  raeburn  14397: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   14398: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   14399: the target domain.
                   14400: 
                   14401: May also include additional key => value pairs for the following groups:
                   14402: 
                   14403: =over
                   14404: 
                   14405: =item
                   14406: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   14407: 
                   14408: =over
                   14409: 
                   14410: =item defaultquota, authorquota
                   14411: 
                   14412: =back
                   14413: 
                   14414: =item
                   14415: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   14416: portfolio for users).
                   14417: 
                   14418: =over
                   14419: 
                   14420: =item
                   14421: aboutme, blog, webdav, portfolio
                   14422: 
                   14423: =back
                   14424: 
                   14425: =item
                   14426: requestcourses: ability to request courses, and how requests are processed.
                   14427: 
                   14428: =over
                   14429: 
                   14430: =item
1.1172.2.37  raeburn  14431: official, unofficial, community, textbook
1.1172.2.35  raeburn  14432: 
                   14433: =back
                   14434: 
                   14435: =item
                   14436: inststatus: types of institutional affiliation, and order in which they are displayed.
                   14437: 
                   14438: =over
                   14439: 
                   14440: =item
1.1172.2.44  raeburn  14441: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  14442: 
                   14443: =back
                   14444: 
                   14445: =item
                   14446: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   14447: for course's uploaded content.
                   14448: 
                   14449: =over
                   14450: 
                   14451: =item
1.1172.2.68  raeburn  14452: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   14453: communityquota, textbookquota
1.1172.2.35  raeburn  14454: 
                   14455: =back
                   14456: 
                   14457: =item
                   14458: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   14459: on your servers.
                   14460: 
                   14461: =over
                   14462: 
                   14463: =item
                   14464: remotesessions, hostedsessions
                   14465: 
                   14466: =back
                   14467: 
                   14468: =back
                   14469: 
                   14470: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   14471: utility to create a configuration.db file on a domain's primary library server
                   14472: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   14473: -- corresponding values are authentication type (internal, krb4, krb5,
                   14474: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   14475: will be available. Values are retrieved from cache (if current), unless the
                   14476: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   14477: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   14478: 
                   14479: Typical usage:
1.943     raeburn  14480: 
1.1172.2.35  raeburn  14481: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  14482: 
1.243     albertel 14483: =back
                   14484: 
                   14485: =head2 Network Status Functions
                   14486: 
                   14487: =over 4
1.191     harris41 14488: 
                   14489: =item *
                   14490: 
1.1137    raeburn  14491: dirlist() : return directory list based on URI (first arg).
                   14492: 
                   14493: Inputs: 1 required, 5 optional.
                   14494: 
                   14495: =over
                   14496: 
                   14497: =item 
                   14498: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   14499: 
                   14500: =item
                   14501: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   14502: 
                   14503: =item
                   14504: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   14505: 
                   14506: =item
                   14507: $getpropath - boolean: 1 if prepend path using &propath(). 
                   14508: 
                   14509: =item
                   14510: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   14511: 
                   14512: =item 
                   14513: $alternateRoot - path to prepend in place of path from $uri.
                   14514: 
                   14515: =back
                   14516: 
                   14517: Returns: Array of up to two items.
                   14518: 
                   14519: =over
                   14520: 
                   14521: a reference to an array of files/subdirectories
                   14522: 
                   14523: =over
                   14524: 
                   14525: Each element in the array of files/subdirectories is a & separated list of
                   14526: item name and the result of running stat on the item.  If dirlist was requested
                   14527: for a file instead of a directory, the item name will be ''. For a directory 
                   14528: listing, if the item is a metadata file, the element will end &N&M 
                   14529: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   14530: default copyright set (1).  
                   14531: 
                   14532: =back
                   14533: 
                   14534: a scalar containing error condition (if encountered).
                   14535: 
                   14536: =over
                   14537: 
                   14538: =item 
                   14539: no_host (no homeserver identified for $username:$domain).
                   14540: 
                   14541: =item 
                   14542: no_such_host (server contacted for listing not identified as valid host).
                   14543: 
                   14544: =item 
                   14545: con_lost (connection to remote server failed).
                   14546: 
                   14547: =item 
                   14548: refused (invalid $username:$domain received on lond side).
                   14549: 
                   14550: =item 
                   14551: no_such_dir (directory at specified path on lond side does not exist). 
                   14552: 
                   14553: =item 
                   14554: empty (directory at specified path on lond side is empty).
                   14555: 
                   14556: =over
                   14557: 
                   14558: This is currently not encountered because the &ls3, &ls2, 
                   14559: &ls (_handler) routines on the lond side do not filter out
                   14560: . and .. from a directory listing. 
                   14561: 
                   14562: =back
                   14563: 
                   14564: =back
                   14565: 
                   14566: =back
1.191     harris41 14567: 
                   14568: =item *
                   14569: 
1.243     albertel 14570: spareserver() : find server with least workload from spare.tab
                   14571: 
1.986     foxr     14572: 
                   14573: =item *
                   14574: 
                   14575: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   14576: if there is no corresponding loncapa host.
                   14577: 
1.243     albertel 14578: =back
                   14579: 
1.986     foxr     14580: 
1.243     albertel 14581: =head2 Apache Request
                   14582: 
                   14583: =over 4
1.191     harris41 14584: 
                   14585: =item *
                   14586: 
1.243     albertel 14587: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   14588: localhost, posts hash
                   14589: 
                   14590: =back
                   14591: 
                   14592: =head2 Data to String to Data
                   14593: 
                   14594: =over 4
1.191     harris41 14595: 
                   14596: =item *
                   14597: 
1.243     albertel 14598: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   14599: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 14600: 
                   14601: =item *
                   14602: 
1.243     albertel 14603: hashref2str($hashref) : convert a hashref into a string complete with
                   14604: escaping and '=' and '&' separators, supports elements that are
                   14605: arrayrefs and hashrefs
1.191     harris41 14606: 
                   14607: =item *
                   14608: 
1.243     albertel 14609: arrayref2str($arrayref) : convert an arrayref into a string complete
                   14610: with escaping and '&' separators, supports elements that are arrayrefs
                   14611: and hashrefs
1.191     harris41 14612: 
                   14613: =item *
                   14614: 
1.243     albertel 14615: str2hash($string) : convert string to hash using unescaping and
                   14616: splitting on '=' and '&', supports elements that are arrayrefs and
                   14617: hashrefs
1.191     harris41 14618: 
                   14619: =item *
                   14620: 
1.243     albertel 14621: str2array($string) : convert string to hash using unescaping and
                   14622: splitting on '&', supports elements that are arrayrefs and hashrefs
                   14623: 
                   14624: =back
                   14625: 
                   14626: =head2 Logging Routines
                   14627: 
                   14628: 
                   14629: These routines allow one to make log messages in the lonnet.log and
                   14630: lonnet.perm logfiles.
1.191     harris41 14631: 
1.1119    foxr     14632: =over 4
                   14633: 
1.191     harris41 14634: =item *
                   14635: 
1.243     albertel 14636: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 14637: 
                   14638: =item *
                   14639: 
1.243     albertel 14640: logthis() : append message to the normal lonnet.log file, it gets
                   14641: preiodically rolled over and deleted.
1.191     harris41 14642: 
                   14643: =item *
                   14644: 
1.243     albertel 14645: logperm() : append a permanent message to lonnet.perm.log, this log
                   14646: file never gets deleted by any automated portion of the system, only
                   14647: messages of critical importance should go in here.
                   14648: 
1.1119    foxr     14649: 
1.243     albertel 14650: =back
                   14651: 
                   14652: =head2 General File Helper Routines
                   14653: 
                   14654: =over 4
1.191     harris41 14655: 
                   14656: =item *
                   14657: 
1.481     raeburn  14658: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   14659: (a) files in /uploaded
                   14660:   (i) If a local copy of the file exists - 
                   14661:       compares modification date of local copy with last-modified date for 
                   14662:       definitive version stored on home server for course. If local copy is 
                   14663:       stale, requests a new version from the home server and stores it. 
                   14664:       If the original has been removed from the home server, then local copy 
                   14665:       is unlinked.
                   14666:   (ii) If local copy does not exist -
                   14667:       requests the file from the home server and stores it. 
                   14668:   
                   14669:   If $caller is 'uploadrep':  
                   14670:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   14671:     for request for files originally uploaded via DOCS. 
                   14672:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   14673:   
                   14674:   Otherwise:
                   14675:      This indicates a call from the content generation phase of the request.
                   14676:      -  returns the entire contents of the file or -1.
                   14677:      
                   14678: (b) files in /res
                   14679:    - returns the entire contents of a file or -1; 
                   14680:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 14681: 
1.712     albertel 14682: 
                   14683: =item *
                   14684: 
                   14685: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   14686:                   reference
                   14687: 
                   14688: returns either a stat() list of data about the file or an empty list
                   14689: if the file doesn't exist or couldn't find out about it (connection
                   14690: problems or user unknown)
                   14691: 
1.191     harris41 14692: =item *
                   14693: 
1.243     albertel 14694: filelocation($dir,$file) : returns file system location of a file
                   14695: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   14696: directory that relative $file lookups are to looked in ($dir of /a/dir
                   14697: and a file of ../bob will become /a/bob)
1.191     harris41 14698: 
                   14699: =item *
                   14700: 
                   14701: hreflocation($dir,$file) : returns file system location or a URL; same as
                   14702: filelocation except for hrefs
                   14703: 
                   14704: =item *
                   14705: 
1.1172.2.49  raeburn  14706: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   14707: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 14708: 
1.243     albertel 14709: =back
                   14710: 
1.608     albertel 14711: =head2 Usererfile file routines (/uploaded*)
                   14712: 
                   14713: =over 4
                   14714: 
                   14715: =item *
                   14716: 
                   14717: userfileupload(): main rotine for putting a file in a user or course's
                   14718:                   filespace, arguments are,
                   14719: 
1.620     albertel 14720:  formname - required - this is the name of the element in $env where the
1.608     albertel 14721:            filename, and the contents of the file to create/modifed exist
1.620     albertel 14722:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   14723:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  14724:  context - if coursedoc, store the file in the course of the active role
                   14725:              of the current user; 
                   14726:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   14727:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 14728:  subdir - required - subdirectory to put the file in under ../userfiles/
                   14729:          if undefined, it will be placed in "unknown"
                   14730: 
                   14731:  (This routine calls clean_filename() to remove any dangerous
                   14732:  characters from the filename, and then calls finuserfileupload() to
                   14733:  complete the transaction)
                   14734: 
                   14735:  returns either the url of the uploaded file (/uploaded/....) if successful
                   14736:  and /adm/notfound.html if unsuccessful
                   14737: 
                   14738: =item *
                   14739: 
                   14740: clean_filename(): routine for cleaing a filename up for storage in
                   14741:                  userfile space, argument is:
                   14742: 
                   14743:  filename - proposed filename
                   14744: 
                   14745: returns: the new clean filename
                   14746: 
                   14747: =item *
                   14748: 
1.1090    raeburn  14749: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 14750: userspace, probably shouldn't be called directly
                   14751: 
                   14752:   docuname: username or courseid of destination for the file
                   14753:   docudom: domain of user/course of destination for the file
                   14754:   formname: same as for userfileupload()
1.1090    raeburn  14755:   fname: filename (including subdirectories) for the file
                   14756:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   14757:   allfiles: reference to hash used to store objects found by parser
                   14758:   codebase: reference to hash used for codebases of java objects found by parser
                   14759:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   14760:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   14761:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   14762:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   14763:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   14764:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  14765:   mimetype: reference to scalar to accommodate mime type determined
                   14766:             from File::MMagic if $parser = parse.
1.608     albertel 14767: 
                   14768:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  14769:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   14770:  was 'overwrite').
                   14771:  
1.608     albertel 14772: 
                   14773: =item *
                   14774: 
                   14775: renameuserfile(): renames an existing userfile to a new name
                   14776: 
                   14777:   Args:
                   14778:    docuname: username or courseid of destination for the file
                   14779:    docudom: domain of user/course of destination for the file
                   14780:    old: current file name (including any subdirs under userfiles)
                   14781:    new: desired file name (including any subdirs under userfiles)
                   14782: 
                   14783: =item *
                   14784: 
                   14785: mkdiruserfile(): creates a directory is a userfiles dir
                   14786: 
                   14787:   Args:
                   14788:    docuname: username or courseid of destination for the file
                   14789:    docudom: domain of user/course of destination for the file
                   14790:    dir: dir to create (including any subdirs under userfiles)
                   14791: 
                   14792: =item *
                   14793: 
                   14794: removeuserfile(): removes a file that exists in userfiles
                   14795: 
                   14796:   Args:
                   14797:    docuname: username or courseid of destination for the file
                   14798:    docudom: domain of user/course of destination for the file
                   14799:    fname: filname to delete (including any subdirs under userfiles)
                   14800: 
                   14801: =item *
                   14802: 
                   14803: removeuploadedurl(): convience function for removeuserfile()
                   14804: 
                   14805:   Args:
                   14806:    url:  a full /uploaded/... url to delete
                   14807: 
1.747     albertel 14808: =item * 
                   14809: 
                   14810: get_portfile_permissions():
                   14811:   Args:
                   14812:     domain: domain of user or course contain the portfolio files
                   14813:     user: name of user or num of course contain the portfolio files
                   14814:   Returns:
                   14815:     hashref of a dump of the proper file_permissions.db
                   14816:    
                   14817: 
                   14818: =item * 
                   14819: 
                   14820: get_access_controls():
                   14821: 
                   14822: Args:
                   14823:   current_permissions: the hash ref returned from get_portfile_permissions()
                   14824:   group: (optional) the group you want the files associated with
                   14825:   file: (optional) the file you want access info on
                   14826: 
                   14827: Returns:
1.749     raeburn  14828:     a hash (keys are file names) of hashes containing
                   14829:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   14830:         values are XML containing access control settings (see below) 
1.747     albertel 14831: 
                   14832: Internal notes:
                   14833: 
1.749     raeburn  14834:  access controls are stored in file_permissions.db as key=value pairs.
                   14835:     key -> path to file/file_name\0uniqueID:scope_end_start
                   14836:         where scope -> public,guest,course,group,domains or users.
                   14837:               end -> UNIX time for end of access (0 -> no end date)
                   14838:               start -> UNIX time for start of access
                   14839: 
                   14840:     value -> XML description of access control
                   14841:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   14842:             <start></start>
                   14843:             <end></end>
                   14844: 
                   14845:             <password></password>  for scope type = guest
                   14846: 
                   14847:             <domain></domain>     for scope type = course or group
                   14848:             <number></number>
                   14849:             <roles id="">
                   14850:              <role></role>
                   14851:              <access></access>
                   14852:              <section></section>
                   14853:              <group></group>
                   14854:             </roles>
                   14855: 
                   14856:             <dom></dom>         for scope type = domains
                   14857: 
                   14858:             <users>             for scope type = users
                   14859:              <user>
                   14860:               <uname></uname>
                   14861:               <udom></udom>
                   14862:              </user>
                   14863:             </users>
                   14864:            </scope> 
                   14865:               
                   14866:  Access data is also aggregated for each file in an additional key=value pair:
                   14867:  key -> path to file/file_name\0accesscontrol 
                   14868:  value -> reference to hash
                   14869:           hash contains key = value pairs
                   14870:           where key = uniqueID:scope_end_start
                   14871:                 value = UNIX time record was last updated
                   14872: 
                   14873:           Used to improve speed of look-ups of access controls for each file.  
                   14874:  
                   14875:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   14876: 
1.1172.2.13  raeburn  14877: =item *
                   14878: 
1.749     raeburn  14879: modify_access_controls():
                   14880: 
                   14881: Modifies access controls for a portfolio file
                   14882: Args
                   14883: 1. file name
                   14884: 2. reference to hash of required changes,
                   14885: 3. domain
                   14886: 4. username
                   14887:   where domain,username are the domain of the portfolio owner 
                   14888:   (either a user or a course) 
                   14889: 
                   14890: Returns:
                   14891: 1. result of additions or updates ('ok' or 'error', with error message). 
                   14892: 2. result of deletions ('ok' or 'error', with error message).
                   14893: 3. reference to hash of any new or updated access controls.
                   14894: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   14895:    key = integer (inbound ID)
1.1172.2.13  raeburn  14896:    value = uniqueID
                   14897: 
                   14898: =item *
                   14899: 
                   14900: get_timebased_id():
                   14901: 
                   14902: Attempts to get a unique timestamp-based suffix for use with items added to a
                   14903: course via the Course Editor (e.g., folders, composite pages,
                   14904: group bulletin boards).
                   14905: 
                   14906: Args: (first three required; six others optional)
                   14907: 
                   14908: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   14909:    docssequence, or name of group
                   14910: 
                   14911: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   14912:    e.g., num, boardids
                   14913: 
                   14914: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   14915:    file will be named nohist_namespace.db
                   14916: 
                   14917: 4. cdom: domain of course; default is current course domain from %env
                   14918: 
                   14919: 5. cnum: course number; default is current course number from %env
                   14920: 
                   14921: 6. idtype: set to concat if an additional digit is to be appended to the
                   14922:    unix timestamp to form the suffix, if the plain timestamp is already
                   14923:    in use.  Default is to not do this, but simply increment the unix
                   14924:    timestamp by 1 until a unique key is obtained.
                   14925: 
                   14926: 7. who: holder of locking key; defaults to user:domain for user.
                   14927: 
                   14928: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   14929:    retrying); default is 3.
                   14930: 
                   14931: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   14932: 
                   14933: Returns:
                   14934: 
                   14935: 1. suffix obtained (numeric)
                   14936: 
                   14937: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   14938: 
                   14939: 3. error: contains (localized) error message if an error occurred.
                   14940: 
1.747     albertel 14941: 
1.608     albertel 14942: =back
                   14943: 
1.243     albertel 14944: =head2 HTTP Helper Routines
                   14945: 
                   14946: =over 4
                   14947: 
1.191     harris41 14948: =item *
                   14949: 
                   14950: escape() : unpack non-word characters into CGI-compatible hex codes
                   14951: 
                   14952: =item *
                   14953: 
                   14954: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   14955: 
1.243     albertel 14956: =back
                   14957: 
                   14958: =head1 PRIVATE SUBROUTINES
                   14959: 
                   14960: =head2 Underlying communication routines (Shouldn't call)
                   14961: 
                   14962: =over 4
                   14963: 
                   14964: =item *
                   14965: 
                   14966: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   14967: 
                   14968: =item *
                   14969: 
                   14970: reply() : uses subreply to send a message to remote machine, logs all failures
                   14971: 
                   14972: =item *
                   14973: 
                   14974: critical() : passes a critical message to another server; if cannot
                   14975: get through then place message in connection buffer directory and
                   14976: returns con_delayed, if incapable of saving message, returns
                   14977: con_failed
                   14978: 
                   14979: =item *
                   14980: 
                   14981: reconlonc() : tries to reconnect lonc client processes.
                   14982: 
                   14983: =back
                   14984: 
                   14985: =head2 Resource Access Logging
                   14986: 
                   14987: =over 4
                   14988: 
                   14989: =item *
                   14990: 
                   14991: flushcourselogs() : flush (save) buffer logs and access logs
                   14992: 
                   14993: =item *
                   14994: 
                   14995: courselog($what) : save message for course in hash
                   14996: 
                   14997: =item *
                   14998: 
                   14999: courseacclog($what) : save message for course using &courselog().  Perform
                   15000: special processing for specific resource types (problems, exams, quizzes, etc).
                   15001: 
1.191     harris41 15002: =item *
                   15003: 
                   15004: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15005: as a PerlChildExitHandler
1.243     albertel 15006: 
                   15007: =back
                   15008: 
                   15009: =head2 Other
                   15010: 
                   15011: =over 4
                   15012: 
                   15013: =item *
                   15014: 
                   15015: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15016: 
                   15017: =back
                   15018: 
                   15019: =cut
1.877     foxr     15020: 

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