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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.62! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.61 2015/03/30 21:58:56 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.539     albertel   92: use Time::HiRes qw( 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.550     foxr      105: my $max_connection_retries = 10;     # 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") {	
                    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.448     albertel  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.448     albertel  170:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    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.
                    373: 	sleep(1);
                    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.850     albertel  391:         sleep(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:     my $hostname = &hostname($lonid);
                    421:     if ($lonid) {
                    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.448     albertel  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') {
                    467: 	&reconlonc("$perlvar{'lonSockDir'}/$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;
                    479: 		if (open($dfh,">$dfilename")) {
                    480: 		    print $dfh "$cmd\n"; 
                    481: 		    close($dfh);
                    482: 		}
1.1       albertel  483:             }
                    484:             sleep 2;
                    485:             my $wcmd='';
                    486:             {
1.448     albertel  487: 		my $dfh;
                    488: 		if (open($dfh,"<$dfilename")) {
                    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.36  raeburn   604:     my ($r,$name,$userhashref) = @_;
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.916     albertel  619:     return undef if (!-e "$lonidsdir/$handle.id");
                    620: 
1.917     albertel  621:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    622:     return undef if (!$opened);
1.916     albertel  623: 
                    624:     flock($idf,LOCK_SH);
                    625:     my %disk_env;
                    626:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    627: 	    &GDBM_READER(),0640)) {
                    628: 	return undef;	
                    629:     }
                    630: 
                    631:     if (!defined($disk_env{'user.name'})
                    632: 	|| !defined($disk_env{'user.domain'})) {
                    633: 	return undef;
                    634:     }
1.1172.2.18  raeburn   635: 
1.1172.2.36  raeburn   636:     if (ref($userhashref) eq 'HASH') {
                    637:         $userhashref->{'name'} = $disk_env{'user.name'};
                    638:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18  raeburn   639:     }
                    640: 
1.916     albertel  641:     return $handle;
                    642: }
                    643: 
1.830     albertel  644: sub timed_flock {
                    645:     my ($file,$lock_type) = @_;
                    646:     my $failed=0;
                    647:     eval {
                    648: 	local $SIG{__DIE__}='DEFAULT';
                    649: 	local $SIG{ALRM}=sub {
                    650: 	    $failed=1;
                    651: 	    die("failed lock");
                    652: 	};
                    653: 	alarm(13);
                    654: 	flock($file,$lock_type);
                    655: 	alarm(0);
                    656:     };
                    657:     if ($failed) {
                    658: 	return undef;
                    659:     } else {
                    660: 	return 1;
                    661:     }
                    662: }
                    663: 
1.5       www       664: # ---------------------------------------------------------- Append Environment
                    665: 
                    666: sub appenv {
1.949     raeburn   667:     my ($newenv,$roles) = @_;
                    668:     if (ref($newenv) eq 'HASH') {
                    669:         foreach my $key (keys(%{$newenv})) {
                    670:             my $refused = 0;
                    671: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    672:                 $refused = 1;
                    673:                 if (ref($roles) eq 'ARRAY') {
1.1172.2.40  raeburn   674:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   675:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    676:                         $refused = 0;
                    677:                     }
                    678:                 }
                    679:             }
                    680:             if ($refused) {
                    681:                 &logthis("<font color=\"blue\">WARNING: ".
                    682:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    683:                          .'</font>');
                    684: 	        delete($newenv->{$key});
                    685:             } else {
                    686:                 $env{$key}=$newenv->{$key};
                    687:             }
                    688:         }
                    689:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    690:         if ($opened
                    691: 	    && &timed_flock($env_file,LOCK_EX)
                    692: 	    &&
                    693: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    694: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    695: 	    while (my ($key,$value) = each(%{$newenv})) {
                    696: 	        $disk_env{$key} = $value;
                    697: 	    }
                    698: 	    untie(%disk_env);
1.35      www       699:         }
1.191     harris41  700:     }
1.56      www       701:     return 'ok';
                    702: }
                    703: # ----------------------------------------------------- Delete from Environment
                    704: 
                    705: sub delenv {
1.1104    raeburn   706:     my ($delthis,$regexp,$roles) = @_;
                    707:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    708:         my $refused = 1;
                    709:         if (ref($roles) eq 'ARRAY') {
                    710:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    711:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    712:                 $refused = 0;
                    713:             }
                    714:         }
                    715:         if ($refused) {
                    716:             &logthis("<font color=\"blue\">WARNING: ".
                    717:                      "Attempt to delete from environment ".$delthis);
                    718:             return 'error';
                    719:         }
1.56      www       720:     }
1.917     albertel  721:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    722:     if ($opened
1.915     albertel  723: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  724: 	&&
                    725: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    726: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  727: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   728: 	    if ($regexp) {
                    729:                 if ($key=~/^$delthis/) {
                    730:                     delete($env{$key});
                    731:                     delete($disk_env{$key});
                    732:                 } 
                    733:             } else {
                    734:                 if ($key=~/^\Q$delthis\E/) {
                    735: 		    delete($env{$key});
                    736: 		    delete($disk_env{$key});
                    737: 	        }
                    738:             }
1.448     albertel  739: 	}
1.783     albertel  740: 	untie(%disk_env);
1.5       www       741:     }
                    742:     return 'ok';
1.369     albertel  743: }
                    744: 
1.790     albertel  745: sub get_env_multiple {
                    746:     my ($name) = @_;
                    747:     my @values;
                    748:     if (defined($env{$name})) {
                    749:         # exists is it an array
                    750:         if (ref($env{$name})) {
                    751:             @values=@{ $env{$name} };
                    752:         } else {
                    753:             $values[0]=$env{$name};
                    754:         }
                    755:     }
                    756:     return(@values);
                    757: }
                    758: 
1.958     www       759: # ------------------------------------------------------------------- Locking
                    760: 
                    761: sub set_lock {
                    762:     my ($text)=@_;
                    763:     $locknum++;
                    764:     my $id=$$.'-'.$locknum;
                    765:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    766:              'session.lock.'.$id => $text});
                    767:     return $id;
                    768: }
                    769: 
                    770: sub get_locks {
                    771:     my $num=0;
                    772:     my %texts=();
                    773:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    774:        if ($lock=~/\w/) {
                    775:           $num++;
                    776:           $texts{$lock}=$env{'session.lock.'.$lock};
                    777:        }
                    778:    }
                    779:    return ($num,%texts);
                    780: }
                    781: 
                    782: sub remove_lock {
                    783:     my ($id)=@_;
                    784:     my $newlocks='';
                    785:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    786:        if (($lock=~/\w/) && ($lock ne $id)) {
                    787:           $newlocks.=','.$lock;
                    788:        }
                    789:     }
                    790:     &appenv({'session.locks' => $newlocks});
                    791:     &delenv('session.lock.'.$id);
                    792: }
                    793: 
                    794: sub remove_all_locks {
                    795:     my $activelocks=$env{'session.locks'};
                    796:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    797:        if ($lock=~/\w/) {
                    798:           &remove_lock($lock);
                    799:        }
                    800:     }
                    801: }
                    802: 
                    803: 
1.369     albertel  804: # ------------------------------------------ Find out current server userload
                    805: sub userload {
                    806:     my $numusers=0;
                    807:     {
                    808: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    809: 	my $filename;
                    810: 	my $curtime=time;
                    811: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  812: 	    next if ($filename eq '.' || $filename eq '..');
                    813: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  814: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  815: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  816: 	}
                    817: 	closedir(LONIDS);
                    818:     }
                    819:     my $userloadpercent=0;
                    820:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    821:     if ($maxuserload) {
1.371     albertel  822: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  823:     }
1.372     albertel  824:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  825:     return $userloadpercent;
1.283     www       826: }
                    827: 
1.1       albertel  828: # ------------------------------ Find server with least workload from spare.tab
1.11      www       829: 
1.1       albertel  830: sub spareserver {
1.1083    raeburn   831:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  832:     my $spare_server;
1.370     albertel  833:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  834:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    835:                                                      :  $userloadpercent;
1.1083    raeburn   836:     my ($uint_dom,$remotesessions);
                    837:     if (($udom ne '') && (&domain($udom) ne '')) {
                    838:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    839:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    840:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    841:         $remotesessions = $udomdefaults{'remotesessions'};
                    842:     }
1.1123    raeburn   843:     my $spareshash = &this_host_spares($udom);
                    844:     if (ref($spareshash) eq 'HASH') {
                    845:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    846:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62! raeburn   847:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
        !           848:                                              $try_server));
1.1123    raeburn   849: 	        ($spare_server, $lowest_load) =
                    850: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    851:             }
1.1083    raeburn   852:         }
1.784     albertel  853: 
1.1123    raeburn   854:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    855: 
                    856:         if (!$found_server) {
                    857:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    858: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62! raeburn   859:                     next unless (&spare_can_host($udom,$uint_dom,
        !           860:                                                  $remotesessions,$try_server));
1.1123    raeburn   861: 	            ($spare_server, $lowest_load) =
                    862: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    863:                 }
                    864: 	    }
                    865:         }
1.784     albertel  866:     }
                    867: 
                    868:     if (!$want_server_name) {
1.968     raeburn   869:         my $protocol = 'http';
                    870:         if ($protocol{$spare_server} eq 'https') {
                    871:             $protocol = $protocol{$spare_server};
                    872:         }
1.1001    raeburn   873:         if (defined($spare_server)) {
                    874:             my $hostname = &hostname($spare_server);
1.1083    raeburn   875:             if (defined($hostname)) {
1.1001    raeburn   876: 	        $spare_server = $protocol.'://'.$hostname;
                    877:             }
                    878:         }
1.784     albertel  879:     }
                    880:     return $spare_server;
                    881: }
                    882: 
                    883: sub compare_server_load {
1.1172.2.41  raeburn   884:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    885: 
                    886:     if ($required) {
                    887:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    888:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    889:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    890:         if (($major eq '' && $minor eq '') ||
                    891:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    892:             return ($spare_server,$lowest_load);
                    893:         }
                    894:     }
1.784     albertel  895: 
                    896:     my $loadans     = &reply('load',    $try_server);
                    897:     my $userloadans = &reply('userload',$try_server);
                    898: 
                    899:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   900: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  901:     }
                    902: 
                    903:     my $load;
                    904:     if ($loadans =~ /\d/) {
                    905: 	if ($userloadans =~ /\d/) {
                    906: 	    #both are numbers, pick the bigger one
                    907: 	    $load = ($loadans > $userloadans) ? $loadans 
                    908: 		                              : $userloadans;
1.411     albertel  909: 	} else {
1.784     albertel  910: 	    $load = $loadans;
1.411     albertel  911: 	}
1.784     albertel  912:     } else {
                    913: 	$load = $userloadans;
                    914:     }
                    915: 
                    916:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    917: 	$spare_server = $try_server;
                    918: 	$lowest_load  = $load;
1.370     albertel  919:     }
1.784     albertel  920:     return ($spare_server,$lowest_load);
1.202     matthew   921: }
1.914     albertel  922: 
                    923: # --------------------------- ask offload servers if user already has a session
                    924: sub find_existing_session {
                    925:     my ($udom,$uname) = @_;
1.1123    raeburn   926:     my $spareshash = &this_host_spares($udom);
                    927:     if (ref($spareshash) eq 'HASH') {
                    928:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    929:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    930:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    931:             }
                    932:         }
                    933:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    934:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    935:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    936:             }
                    937:         }
1.914     albertel  938:     }
                    939:     return;
                    940: }
                    941: 
                    942: # -------------------------------- ask if server already has a session for user
                    943: sub has_user_session {
                    944:     my ($lonid,$udom,$uname) = @_;
                    945:     my $result = &reply(join(':','userhassession',
                    946: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    947:     return 1 if ($result eq 'ok');
                    948: 
                    949:     return 0;
                    950: }
                    951: 
1.1076    raeburn   952: # --------- determine least loaded server in a user's domain which allows login
                    953: 
                    954: sub choose_server {
1.1172.2.47  raeburn   955:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn   956:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   957:     my %servers = &get_servers($udom);
1.1076    raeburn   958:     my $lowest_load = 30000;
1.1172.2.47  raeburn   959:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                    960:     if ($skiploadbal) {
                    961:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                    962:         unless (defined($cached)) {
                    963:             my $cachetime = 60*60*24;
                    964:             my %domconfig =
                    965:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                    966:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                    967:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                    968:                                            $cachetime);
                    969:             }
                    970:         }
                    971:     }
1.1076    raeburn   972:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   973:         my $loginvia;
1.1172.2.47  raeburn   974:         if ($skiploadbal) {
                    975:             if (ref($balancers) eq 'HASH') {
                    976:                 next if (exists($balancers->{$lonhost}));
                    977:             }
                    978:         }
1.1115    raeburn   979:         if ($checkloginvia) {
                    980:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   981:             if ($loginvia) {
                    982:                 my ($server,$path) = split(/:/,$loginvia);
                    983:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn   984:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn   985:                 if ($login_host eq $server) {
                    986:                     $portal_path = $path;
1.1151    raeburn   987:                     $isredirect = 1;
1.1116    raeburn   988:                 }
                    989:             } else {
                    990:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn   991:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn   992:                 if ($login_host eq $lonhost) {
                    993:                     $portal_path = '';
1.1151    raeburn   994:                     $isredirect = ''; 
1.1116    raeburn   995:                 }
                    996:             }
                    997:         } else {
1.1076    raeburn   998:             ($login_host, $lowest_load) =
1.1172.2.41  raeburn   999:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1000:         }
                   1001:     }
                   1002:     if ($login_host ne '') {
1.1116    raeburn  1003:         $hostname = &hostname($login_host);
1.1076    raeburn  1004:     }
1.1151    raeburn  1005:     return ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn  1006: }
                   1007: 
1.202     matthew  1008: # --------------------------------------------- Try to change a user's password
                   1009: 
                   1010: sub changepass {
1.799     raeburn  1011:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1012:     $currentpass = &escape($currentpass);
                   1013:     $newpass     = &escape($newpass);
1.1030    raeburn  1014:     my $lonhost = $perlvar{'lonHostID'};
                   1015:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1016: 		       $server);
                   1017:     if (! $answer) {
                   1018: 	&logthis("No reply on password change request to $server ".
                   1019: 		 "by $uname in domain $udom.");
                   1020:     } elsif ($answer =~ "^ok") {
                   1021:         &logthis("$uname in $udom successfully changed their password ".
                   1022: 		 "on $server.");
                   1023:     } elsif ($answer =~ "^pwchange_failure") {
                   1024: 	&logthis("$uname in $udom was unable to change their password ".
                   1025: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1026: 		 "or pwchange");
                   1027:     } elsif ($answer =~ "^non_authorized") {
                   1028:         &logthis("$uname in $udom did not get their password correct when ".
                   1029: 		 "attempting to change it on $server.");
                   1030:     } elsif ($answer =~ "^auth_mode_error") {
                   1031:         &logthis("$uname in $udom attempted to change their password despite ".
                   1032: 		 "not being locally or internally authenticated on $server.");
                   1033:     } elsif ($answer =~ "^unknown_user") {
                   1034:         &logthis("$uname in $udom attempted to change their password ".
                   1035: 		 "on $server but were unable to because $server is not ".
                   1036: 		 "their home server.");
                   1037:     } elsif ($answer =~ "^refused") {
                   1038: 	&logthis("$server refused to change $uname in $udom password because ".
                   1039: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1040:     } elsif ($answer =~ "invalid_client") {
                   1041:         &logthis("$server refused to change $uname in $udom password because ".
                   1042:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1043:     }
                   1044:     return $answer;
1.1       albertel 1045: }
                   1046: 
1.169     harris41 1047: # ----------------------- Try to determine user's current authentication scheme
                   1048: 
                   1049: sub queryauthenticate {
                   1050:     my ($uname,$udom)=@_;
1.456     albertel 1051:     my $uhome=&homeserver($uname,$udom);
                   1052:     if (!$uhome) {
                   1053: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1054: 	return 'no_host';
                   1055:     }
                   1056:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1057:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1058: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1059:     }
1.456     albertel 1060:     return $answer;
1.169     harris41 1061: }
                   1062: 
1.1       albertel 1063: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1064: 
1.1       albertel 1065: sub authenticate {
1.1073    raeburn  1066:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1067:     $upass=&escape($upass);
                   1068:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1069:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1070:     my $newhome;
1.836     www      1071:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1072: # Maybe the machine was offline and only re-appeared again recently?
                   1073:         &reconlonc();
                   1074: # One more
1.952     raeburn  1075: 	$uhome=&homeserver($uname,$udom,1);
                   1076:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1077:             if (defined(&domain($udom,'primary'))) {
                   1078:                 $newhome=&domain($udom,'primary');
                   1079:             }
                   1080:             if ($newhome ne '') {
                   1081:                 $uhome = $newhome;
                   1082:             }
                   1083:         }
1.836     www      1084: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1085: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1086: 	    return 'no_host';
                   1087:         }
1.1       albertel 1088:     }
1.1073    raeburn  1089:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1090:     if ($answer eq 'authorized') {
1.952     raeburn  1091:         if ($newhome) {
                   1092:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1093:             return 'no_account_on_host'; 
                   1094:         } else {
                   1095:             &logthis("User $uname at $udom authorized by $uhome");
                   1096:             return $uhome;
                   1097:         }
1.471     albertel 1098:     }
                   1099:     if ($answer eq 'non_authorized') {
                   1100: 	&logthis("User $uname at $udom rejected by $uhome");
                   1101: 	return 'no_host'; 
1.9       www      1102:     }
1.471     albertel 1103:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1104:     return 'no_host';
                   1105: }
                   1106: 
1.1073    raeburn  1107: sub can_host_session {
1.1074    raeburn  1108:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1109:     my $canhost = 1;
1.1074    raeburn  1110:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1111:     if (ref($remotesessions) eq 'HASH') {
                   1112:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1113:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1114:                 $canhost = 0;
                   1115:             } else {
                   1116:                 $canhost = 1;
                   1117:             }
                   1118:         }
                   1119:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1120:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1121:                 $canhost = 1;
                   1122:             } else {
                   1123:                 $canhost = 0;
                   1124:             }
                   1125:         }
                   1126:         if ($canhost) {
                   1127:             if ($remotesessions->{'version'} ne '') {
                   1128:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1129:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1130:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1131:                         my $major = $1;
                   1132:                         my $minor = $2;
                   1133:                         if (($major < $reqmajor ) ||
                   1134:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1135:                             $canhost = 0;
                   1136:                         }
                   1137:                     } else {
                   1138:                         $canhost = 0;
                   1139:                     }
                   1140:                 }
                   1141:             }
                   1142:         }
                   1143:     }
                   1144:     if ($canhost) {
                   1145:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1146:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1147:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1148:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1149:                 if (($uint_dom ne '') && 
                   1150:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1151:                     $canhost = 0;
                   1152:                 } else {
                   1153:                     $canhost = 1;
                   1154:                 }
                   1155:             }
                   1156:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1157:                 if (($uint_dom ne '') && 
                   1158:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1159:                     $canhost = 1;
                   1160:                 } else {
                   1161:                     $canhost = 0;
                   1162:                 }
                   1163:             }
                   1164:         }
                   1165:     }
                   1166:     return $canhost;
                   1167: }
                   1168: 
1.1083    raeburn  1169: sub spare_can_host {
                   1170:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1171:     my $canhost=1;
1.1172.2.62! raeburn  1172:     my $try_server_hostname = &hostname($try_server);
        !          1173:     my $serverhomeID = &get_server_homeID($try_server_hostname);
        !          1174:     my $serverhomedom = &host_domain($serverhomeID);
        !          1175:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
        !          1176:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
        !          1177:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
        !          1178:             $canhost = 0;
        !          1179:         }
        !          1180:     }
        !          1181:     if (($canhost) && ($uint_dom)) {
        !          1182:         my @intdoms;
        !          1183:         my $internet_names = &get_internet_names($try_server);
        !          1184:         if (ref($internet_names) eq 'ARRAY') {
        !          1185:             @intdoms = @{$internet_names};
        !          1186:         }
        !          1187:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
        !          1188:             my $remoterev = &get_server_loncaparev(undef,$try_server);
        !          1189:             $canhost = &can_host_session($udom,$try_server,$remoterev,
        !          1190:                                          $remotesessions,
        !          1191:                                          $defdomdefaults{'hostedsessions'});
        !          1192:         }
1.1083    raeburn  1193:     }
                   1194:     return $canhost;
                   1195: }
                   1196: 
1.1123    raeburn  1197: sub this_host_spares {
                   1198:     my ($dom) = @_;
1.1126    raeburn  1199:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1200:     my @hosts = &current_machine_ids();
                   1201:     foreach my $lonhost (@hosts) {
                   1202:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1203:             $dom_in_use = $dom;
                   1204:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1205:             last;
                   1206:         }
                   1207:     }
1.1126    raeburn  1208:     if ($dom_in_use ne '') {
                   1209:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1210:     }
                   1211:     if (ref($result) ne 'HASH') {
                   1212:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1213:         $dom_in_use = &host_domain($lonhost_in_use);
                   1214:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1215:         if (ref($result) ne 'HASH') {
                   1216:             $result = \%spareid;
                   1217:         }
                   1218:     }
                   1219:     return $result;
                   1220: }
                   1221: 
                   1222: sub spares_for_offload  {
                   1223:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1224:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1225:     if (defined($cached)) {
                   1226:         return $result;
                   1227:     } else {
1.1126    raeburn  1228:         my $cachetime = 60*60*24;
                   1229:         my %domconfig =
                   1230:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1231:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1232:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1233:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1234:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1235:                 }
                   1236:             }
                   1237:         }
                   1238:     }
1.1126    raeburn  1239:     return;
1.1123    raeburn  1240: }
                   1241: 
1.1129    raeburn  1242: sub get_lonbalancer_config {
                   1243:     my ($servers) = @_;
                   1244:     my ($currbalancer,$currtargets);
                   1245:     if (ref($servers) eq 'HASH') {
                   1246:         foreach my $server (keys(%{$servers})) {
                   1247:             my %what = (
                   1248:                          spareid => 1,
                   1249:                          perlvar => 1,
                   1250:                        );
                   1251:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1252:             if ($result eq 'ok') {
                   1253:                 if (ref($returnhash) eq 'HASH') {
                   1254:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1255:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1256:                             $currbalancer = $server;
                   1257:                             $currtargets = {};
                   1258:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1259:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1260:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1261:                                 }
                   1262:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1263:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1264:                                 }
                   1265:                             }
                   1266:                             last;
                   1267:                         }
                   1268:                     }
                   1269:                 }
                   1270:             }
                   1271:         }
                   1272:     }
                   1273:     return ($currbalancer,$currtargets);
                   1274: }
                   1275: 
                   1276: sub check_loadbalancing {
                   1277:     my ($uname,$udom) = @_;
1.1172.2.12  raeburn  1278:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1279:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1280:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1281:     my @hosts = &current_machine_ids();
1.1129    raeburn  1282:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1283:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1284:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1285:     my $serverhomedom = &host_domain($lonhost);
                   1286: 
                   1287:     my $cachetime = 60*60*24;
                   1288: 
                   1289:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1290:         $dom_in_use = $udom;
                   1291:         $homeintdom = 1;
                   1292:     } else {
                   1293:         $dom_in_use = $serverhomedom;
                   1294:     }
                   1295:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1296:     unless (defined($cached)) {
                   1297:         my %domconfig =
                   1298:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1299:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1300:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1301:         }
                   1302:     }
                   1303:     if (ref($result) eq 'HASH') {
1.1172.2.12  raeburn  1304:         ($is_balancer,$currtargets,$currrules) =
                   1305:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1306:         if ($is_balancer) {
                   1307:             if (ref($currrules) eq 'HASH') {
                   1308:                 if ($homeintdom) {
                   1309:                     if ($uname ne '') {
                   1310:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1311:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1312:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1313:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1314:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1315:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1316:                             }
                   1317:                         }
                   1318:                         if ($rule_in_effect eq '') {
                   1319:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1320:                             if ($userenv{'inststatus'} ne '') {
                   1321:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1322:                                 my ($othertitle,$usertypes,$types) =
                   1323:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1324:                                 if (ref($types) eq 'ARRAY') {
                   1325:                                     foreach my $type (@{$types}) {
                   1326:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1327:                                             if (exists($currrules->{$type})) {
                   1328:                                                 $rule_in_effect = $currrules->{$type};
                   1329:                                             }
                   1330:                                         }
                   1331:                                     }
                   1332:                                 }
                   1333:                             } else {
                   1334:                                 if (exists($currrules->{'default'})) {
                   1335:                                     $rule_in_effect = $currrules->{'default'};
                   1336:                                 }
                   1337:                             }
                   1338:                         }
                   1339:                     } else {
                   1340:                         if (exists($currrules->{'default'})) {
                   1341:                             $rule_in_effect = $currrules->{'default'};
                   1342:                         }
                   1343:                     }
                   1344:                 } else {
                   1345:                     if ($currrules->{'_LC_external'} ne '') {
                   1346:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1347:                     }
                   1348:                 }
                   1349:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1350:                                                        $uname,$udom);
                   1351:             }
                   1352:         }
                   1353:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35  raeburn  1354:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1355:         unless (defined($cached)) {
                   1356:             my %domconfig =
                   1357:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1358:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1359:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1360:             }
                   1361:         }
                   1362:         if (ref($result) eq 'HASH') {
1.1172.2.12  raeburn  1363:             ($is_balancer,$currtargets,$currrules) =
                   1364:                 &check_balancer_result($result,@hosts);
                   1365:             if ($is_balancer) {
1.1129    raeburn  1366:                 if (ref($currrules) eq 'HASH') {
                   1367:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1368:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1369:                     }
                   1370:                 }
                   1371:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1372:                                                        $uname,$udom);
                   1373:             }
                   1374:         } else {
                   1375:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1376:                 $is_balancer = 1;
                   1377:                 $offloadto = &this_host_spares($dom_in_use);
                   1378:             }
                   1379:         }
                   1380:     } else {
                   1381:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1382:             $is_balancer = 1;
                   1383:             $offloadto = &this_host_spares($dom_in_use);
                   1384:         }
                   1385:     }
1.1172.2.5  raeburn  1386:     if ($is_balancer) {
                   1387:         my $lowest_load = 30000;
                   1388:         if (ref($offloadto) eq 'HASH') {
                   1389:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1390:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1391:                     ($otherserver,$lowest_load) =
                   1392:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1393:                 }
1.1129    raeburn  1394:             }
1.1172.2.5  raeburn  1395:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1396: 
1.1172.2.5  raeburn  1397:             if (!$found_server) {
                   1398:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1399:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1400:                         ($otherserver,$lowest_load) =
                   1401:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1402:                     }
                   1403:                 }
                   1404:             }
                   1405:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1406:             if (@{$offloadto} == 1) {
                   1407:                 $otherserver = $offloadto->[0];
                   1408:             } elsif (@{$offloadto} > 1) {
                   1409:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1410:                     ($otherserver,$lowest_load) =
                   1411:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1412:                 }
                   1413:             }
                   1414:         }
1.1172.2.5  raeburn  1415:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1416:             $is_balancer = 0;
                   1417:             if ($uname ne '' && $udom ne '') {
                   1418:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1419: 
                   1420:                     &appenv({'user.loadbalexempt'     => $lonhost,
                   1421:                              'user.loadbalcheck.time' => time});
                   1422:                 }
1.1129    raeburn  1423:             }
                   1424:         }
                   1425:     }
                   1426:     return ($is_balancer,$otherserver);
                   1427: }
                   1428: 
1.1172.2.12  raeburn  1429: sub check_balancer_result {
                   1430:     my ($result,@hosts) = @_;
                   1431:     my ($is_balancer,$currtargets,$currrules);
                   1432:     if (ref($result) eq 'HASH') {
                   1433:         if ($result->{'lonhost'} ne '') {
                   1434:             my $currbalancer = $result->{'lonhost'};
                   1435:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1436:                 $is_balancer = 1;
                   1437:                 $currtargets = $result->{'targets'};
                   1438:                 $currrules = $result->{'rules'};
                   1439:             }
                   1440:         } else {
                   1441:             foreach my $key (keys(%{$result})) {
                   1442:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1443:                     (ref($result->{$key}) eq 'HASH')) {
                   1444:                     $is_balancer = 1;
                   1445:                     $currrules = $result->{$key}{'rules'};
                   1446:                     $currtargets = $result->{$key}{'targets'};
                   1447:                     last;
                   1448:                 }
                   1449:             }
                   1450:         }
                   1451:     }
                   1452:     return ($is_balancer,$currtargets,$currrules);
                   1453: }
                   1454: 
1.1129    raeburn  1455: sub get_loadbalancer_targets {
                   1456:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1457:     my $offloadto;
1.1172.2.4  raeburn  1458:     if ($rule_in_effect eq 'none') {
                   1459:         return [$perlvar{'lonHostID'}];
                   1460:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1461:         $offloadto = $currtargets;
                   1462:     } else {
                   1463:         if ($rule_in_effect eq 'homeserver') {
                   1464:             my $homeserver = &homeserver($uname,$udom);
                   1465:             if ($homeserver ne 'no_host') {
                   1466:                 $offloadto = [$homeserver];
                   1467:             }
                   1468:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1469:             my %domconfig =
                   1470:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1471:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1472:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1473:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1474:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1475:                     }
                   1476:                 }
                   1477:             } else {
1.1172.2.7  raeburn  1478:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1479:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1480:                 if (&hostname($remotebalancer) ne '') {
                   1481:                     $offloadto = [$remotebalancer];
                   1482:                 }
                   1483:             }
                   1484:         } elsif (&hostname($rule_in_effect) ne '') {
                   1485:             $offloadto = [$rule_in_effect];
                   1486:         }
                   1487:     }
                   1488:     return $offloadto;
                   1489: }
                   1490: 
1.1127    raeburn  1491: sub internet_dom_servers {
                   1492:     my ($dom) = @_;
                   1493:     my (%uniqservers,%servers);
                   1494:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1495:     my @machinedoms = &machine_domains($primaryserver);
                   1496:     foreach my $mdom (@machinedoms) {
                   1497:         my %currservers = %servers;
                   1498:         my %server = &get_servers($mdom);
                   1499:         %servers = (%currservers,%server);
                   1500:     }
                   1501:     my %by_hostname;
                   1502:     foreach my $id (keys(%servers)) {
                   1503:         push(@{$by_hostname{$servers{$id}}},$id);
                   1504:     }
                   1505:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1506:         if (@{$by_hostname{$hostname}} > 1) {
                   1507:             my $match = 0;
                   1508:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1509:                 if (&host_domain($id) eq $dom) {
                   1510:                     $uniqservers{$id} = $hostname;
                   1511:                     $match = 1;
                   1512:                 }
                   1513:             }
                   1514:             unless ($match) {
                   1515:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1516:             }
                   1517:         } else {
                   1518:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1519:         }
                   1520:     }
                   1521:     return %uniqservers;
                   1522: }
                   1523: 
1.1       albertel 1524: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1525: 
1.599     albertel 1526: my %homecache;
1.1       albertel 1527: sub homeserver {
1.230     stredwic 1528:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1529:     my $index="$uname:$udom";
1.426     albertel 1530: 
1.599     albertel 1531:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1532: 
                   1533:     my %servers = &get_servers($udom,'library');
                   1534:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1535:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1536: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1537: 
                   1538: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1539: 	if ($answer eq 'found') {
                   1540: 	    delete($badServerCache{$tryserver}); 
                   1541: 	    return $homecache{$index}=$tryserver;
                   1542: 	} elsif ($answer eq 'no_host') {
                   1543: 	    $badServerCache{$tryserver}=1;
                   1544: 	}
1.1       albertel 1545:     }    
                   1546:     return 'no_host';
1.70      www      1547: }
                   1548: 
                   1549: # ------------------------------------- Find the usernames behind a list of IDs
                   1550: 
                   1551: sub idget {
                   1552:     my ($udom,@ids)=@_;
                   1553:     my %returnhash=();
                   1554:     
1.841     albertel 1555:     my %servers = &get_servers($udom,'library');
                   1556:     foreach my $tryserver (keys(%servers)) {
                   1557: 	my $idlist=join('&',@ids);
                   1558: 	$idlist=~tr/A-Z/a-z/; 
                   1559: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1560: 	my @answer=();
                   1561: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1562: 	    @answer=split(/\&/,$reply);
                   1563: 	}                    ;
                   1564: 	my $i;
                   1565: 	for ($i=0;$i<=$#ids;$i++) {
                   1566: 	    if ($answer[$i]) {
                   1567: 		$returnhash{$ids[$i]}=$answer[$i];
                   1568: 	    } 
                   1569: 	}
                   1570:     } 
1.70      www      1571:     return %returnhash;
                   1572: }
                   1573: 
                   1574: # ------------------------------------- Find the IDs behind a list of usernames
                   1575: 
                   1576: sub idrget {
                   1577:     my ($udom,@unames)=@_;
                   1578:     my %returnhash=();
1.800     albertel 1579:     foreach my $uname (@unames) {
                   1580:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1581:     }
1.70      www      1582:     return %returnhash;
                   1583: }
                   1584: 
                   1585: # ------------------------------- Store away a list of names and associated IDs
                   1586: 
                   1587: sub idput {
                   1588:     my ($udom,%ids)=@_;
                   1589:     my %servers=();
1.800     albertel 1590:     foreach my $uname (keys(%ids)) {
                   1591: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1592:         my $uhom=&homeserver($uname,$udom);
1.70      www      1593:         if ($uhom ne 'no_host') {
1.800     albertel 1594:             my $id=&escape($ids{$uname});
1.70      www      1595:             $id=~tr/A-Z/a-z/;
1.800     albertel 1596:             my $esc_unam=&escape($uname);
1.70      www      1597: 	    if ($servers{$uhom}) {
1.800     albertel 1598: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1599:             } else {
1.800     albertel 1600:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1601:             }
                   1602:         }
1.191     harris41 1603:     }
1.800     albertel 1604:     foreach my $server (keys(%servers)) {
                   1605:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1606:     }
1.344     www      1607: }
                   1608: 
1.1172.2.30  raeburn  1609: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1610: 
                   1611: sub iddel {
                   1612:     my ($udom,$idshashref,$uhome)=@_;
                   1613:     my %result=();
                   1614:     unless (ref($idshashref) eq 'HASH') {
                   1615:         return %result;
                   1616:     }
                   1617:     my %servers=();
                   1618:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1619:         my $uhom;
                   1620:         if ($uhome) {
                   1621:             $uhom = $uhome;
                   1622:         } else {
                   1623:             $uhom=&homeserver($uname,$udom);
                   1624:         }
                   1625:         if ($uhom ne 'no_host') {
                   1626:             if ($servers{$uhom}) {
                   1627:                 $servers{$uhom}.='&'.&escape($id);
                   1628:             } else {
                   1629:                 $servers{$uhom}=&escape($id);
                   1630:             }
                   1631:         }
                   1632:     }
                   1633:     foreach my $server (keys(%servers)) {
                   1634:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1635:     }
                   1636:     return %result;
                   1637: }
                   1638: 
1.1023    raeburn  1639: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1640: sub dump_dom {
1.1165    droeschl 1641:     my ($namespace, $udom, $regexp) = @_;
                   1642: 
                   1643:     $udom ||= $env{'user.domain'};
                   1644: 
                   1645:     return () unless $udom;
                   1646: 
                   1647:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1648: }
                   1649: 
1.1023    raeburn  1650: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1651: 
                   1652: sub get_dom {
1.860     raeburn  1653:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57  raeburn  1654:     return if ($udom eq 'public');
1.806     raeburn  1655:     my $items='';
                   1656:     foreach my $item (@$storearr) {
                   1657:         $items.=&escape($item).'&';
                   1658:     }
                   1659:     $items=~s/\&$//;
1.860     raeburn  1660:     if (!$udom) {
                   1661:         $udom=$env{'user.domain'};
1.1172.2.57  raeburn  1662:         return if ($udom eq 'public');
1.860     raeburn  1663:         if (defined(&domain($udom,'primary'))) {
                   1664:             $uhome=&domain($udom,'primary');
                   1665:         } else {
1.874     albertel 1666:             undef($uhome);
1.860     raeburn  1667:         }
                   1668:     } else {
                   1669:         if (!$uhome) {
                   1670:             if (defined(&domain($udom,'primary'))) {
                   1671:                 $uhome=&domain($udom,'primary');
                   1672:             }
                   1673:         }
                   1674:     }
                   1675:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1676:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1677:         my %returnhash;
1.875     albertel 1678:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1679:             return %returnhash;
                   1680:         }
1.806     raeburn  1681:         my @pairs=split(/\&/,$rep);
                   1682:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1683:             return @pairs;
                   1684:         }
                   1685:         my $i=0;
                   1686:         foreach my $item (@$storearr) {
                   1687:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1688:             $i++;
                   1689:         }
                   1690:         return %returnhash;
                   1691:     } else {
1.880     banghart 1692:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1693:     }
                   1694: }
                   1695: 
                   1696: # -------------------------------------------- put items in domain db files 
                   1697: 
                   1698: sub put_dom {
1.860     raeburn  1699:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1700:     if (!$udom) {
                   1701:         $udom=$env{'user.domain'};
                   1702:         if (defined(&domain($udom,'primary'))) {
                   1703:             $uhome=&domain($udom,'primary');
                   1704:         } else {
1.874     albertel 1705:             undef($uhome);
1.860     raeburn  1706:         }
                   1707:     } else {
                   1708:         if (!$uhome) {
                   1709:             if (defined(&domain($udom,'primary'))) {
                   1710:                 $uhome=&domain($udom,'primary');
                   1711:             }
                   1712:         }
                   1713:     } 
                   1714:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1715:         my $items='';
                   1716:         foreach my $item (keys(%$storehash)) {
                   1717:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1718:         }
                   1719:         $items=~s/\&$//;
                   1720:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1721:     } else {
1.860     raeburn  1722:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1723:     }
                   1724: }
                   1725: 
1.1023    raeburn  1726: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1727: sub newput_dom {
1.1023    raeburn  1728:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1729:     my $result;
                   1730:     if (!$udom) {
                   1731:         $udom=$env{'user.domain'};
                   1732:     }
1.1023    raeburn  1733:     if ($udom) {
                   1734:         my $uname = &get_domainconfiguser($udom);
                   1735:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1736:     }
                   1737:     return $result;
                   1738: }
                   1739: 
1.1023    raeburn  1740: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1741: sub del_dom {
1.1023    raeburn  1742:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1743:     if (ref($storearr) eq 'ARRAY') {
                   1744:         if (!$udom) {
                   1745:             $udom=$env{'user.domain'};
                   1746:         }
1.1023    raeburn  1747:         if ($udom) {
                   1748:             my $uname = &get_domainconfiguser($udom); 
                   1749:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1750:         }
                   1751:     }
                   1752: }
                   1753: 
1.1023    raeburn  1754: # ----------------------------------construct domainconfig user for a domain 
                   1755: sub get_domainconfiguser {
                   1756:     my ($udom) = @_;
                   1757:     return $udom.'-domainconfig';
                   1758: }
                   1759: 
1.837     raeburn  1760: sub retrieve_inst_usertypes {
                   1761:     my ($udom) = @_;
                   1762:     my (%returnhash,@order);
1.989     raeburn  1763:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1764:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1765:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  1766:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1767:     } else {
                   1768:         if (defined(&domain($udom,'primary'))) {
                   1769:             my $uhome=&domain($udom,'primary');
                   1770:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1771:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  1772:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1773:                 return (\%returnhash,\@order);
                   1774:             }
                   1775:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1776:             my @pairs=split(/\&/,$hashitems);
                   1777:             foreach my $item (@pairs) {
                   1778:                 my ($key,$value)=split(/=/,$item,2);
                   1779:                 $key = &unescape($key);
                   1780:                 next if ($key =~ /^error: 2 /);
                   1781:                 $returnhash{$key}=&thaw_unescape($value);
                   1782:             }
                   1783:             my @esc_order = split(/\&/,$orderitems);
                   1784:             foreach my $item (@esc_order) {
                   1785:                 push(@order,&unescape($item));
                   1786:             }
                   1787:         } else {
1.1172.2.44  raeburn  1788:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1789:         }
1.1172.2.44  raeburn  1790:         return (\%returnhash,\@order);
1.837     raeburn  1791:     }
                   1792: }
                   1793: 
1.868     raeburn  1794: sub is_domainimage {
                   1795:     my ($url) = @_;
                   1796:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1797:         if (&domain($1) ne '') {
                   1798:             return '1';
                   1799:         }
                   1800:     }
                   1801:     return;
                   1802: }
                   1803: 
1.899     raeburn  1804: sub inst_directory_query {
                   1805:     my ($srch) = @_;
                   1806:     my $udom = $srch->{'srchdomain'};
                   1807:     my %results;
                   1808:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1809:     my $outcome;
1.899     raeburn  1810:     if ($homeserver ne '') {
1.904     albertel 1811: 	my $queryid=&reply("querysend:instdirsearch:".
                   1812: 			   &escape($srch->{'srchby'}).':'.
                   1813: 			   &escape($srch->{'srchterm'}).':'.
                   1814: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1815: 	my $host=&hostname($homeserver);
                   1816: 	if ($queryid !~/^\Q$host\E\_/) {
                   1817: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1818: 	    return;
                   1819: 	}
                   1820: 	my $response = &get_query_reply($queryid);
                   1821: 	my $maxtries = 5;
                   1822: 	my $tries = 1;
                   1823: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1824: 	    $response = &get_query_reply($queryid);
                   1825: 	    $tries ++;
                   1826: 	}
                   1827: 
                   1828:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1829:             if ($response eq 'unavailable') {
                   1830:                 $outcome = $response;
                   1831:             } else {
                   1832:                 $outcome = 'ok';
                   1833:                 my @matches = split(/\n/,$response);
                   1834:                 foreach my $match (@matches) {
                   1835:                     my ($key,$value) = split(/=/,$match);
                   1836:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1837:                 }
1.899     raeburn  1838:             }
                   1839:         }
                   1840:     }
1.909     raeburn  1841:     return ($outcome,%results);
1.899     raeburn  1842: }
                   1843: 
                   1844: sub usersearch {
                   1845:     my ($srch) = @_;
                   1846:     my $dom = $srch->{'srchdomain'};
                   1847:     my %results;
                   1848:     my %libserv = &all_library();
                   1849:     my $query = 'usersearch';
                   1850:     foreach my $tryserver (keys(%libserv)) {
                   1851:         if (&host_domain($tryserver) eq $dom) {
                   1852:             my $host=&hostname($tryserver);
                   1853:             my $queryid=
1.911     raeburn  1854:                 &reply("querysend:".&escape($query).':'.
                   1855:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1856:                        &escape($srch->{'srchtype'}).':'.
                   1857:                        &escape($srch->{'srchterm'}),$tryserver);
                   1858:             if ($queryid !~/^\Q$host\E\_/) {
                   1859:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1860:                 next;
1.899     raeburn  1861:             }
                   1862:             my $reply = &get_query_reply($queryid);
                   1863:             my $maxtries = 1;
                   1864:             my $tries = 1;
                   1865:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1866:                 $reply = &get_query_reply($queryid);
                   1867:                 $tries ++;
                   1868:             }
                   1869:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1870:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1871:             } else {
1.911     raeburn  1872:                 my @matches;
                   1873:                 if ($reply =~ /\n/) {
                   1874:                     @matches = split(/\n/,$reply);
                   1875:                 } else {
                   1876:                     @matches = split(/\&/,$reply);
                   1877:                 }
1.899     raeburn  1878:                 foreach my $match (@matches) {
                   1879:                     my ($uname,$udom,%userhash);
1.911     raeburn  1880:                     foreach my $entry (split(/:/,$match)) {
                   1881:                         my ($key,$value) =
                   1882:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1883:                         $userhash{$key} = $value;
                   1884:                         if ($key eq 'username') {
                   1885:                             $uname = $value;
                   1886:                         } elsif ($key eq 'domain') {
                   1887:                             $udom = $value;
1.911     raeburn  1888:                         }
1.899     raeburn  1889:                     }
                   1890:                     $results{$uname.':'.$udom} = \%userhash;
                   1891:                 }
                   1892:             }
                   1893:         }
                   1894:     }
                   1895:     return %results;
                   1896: }
                   1897: 
1.912     raeburn  1898: sub get_instuser {
                   1899:     my ($udom,$uname,$id) = @_;
                   1900:     my $homeserver = &domain($udom,'primary');
                   1901:     my ($outcome,%results);
                   1902:     if ($homeserver ne '') {
                   1903:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1904:                            &escape($id).':'.&escape($udom),$homeserver);
                   1905:         my $host=&hostname($homeserver);
                   1906:         if ($queryid !~/^\Q$host\E\_/) {
                   1907:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1908:             return;
                   1909:         }
                   1910:         my $response = &get_query_reply($queryid);
                   1911:         my $maxtries = 5;
                   1912:         my $tries = 1;
                   1913:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1914:             $response = &get_query_reply($queryid);
                   1915:             $tries ++;
                   1916:         }
                   1917:         if (!&error($response) && $response ne 'refused') {
                   1918:             if ($response eq 'unavailable') {
                   1919:                 $outcome = $response;
                   1920:             } else {
                   1921:                 $outcome = 'ok';
                   1922:                 my @matches = split(/\n/,$response);
                   1923:                 foreach my $match (@matches) {
                   1924:                     my ($key,$value) = split(/=/,$match);
                   1925:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1926:                 }
                   1927:             }
                   1928:         }
                   1929:     }
                   1930:     my %userinfo;
                   1931:     if (ref($results{$uname}) eq 'HASH') {
                   1932:         %userinfo = %{$results{$uname}};
                   1933:     } 
                   1934:     return ($outcome,%userinfo);
                   1935: }
                   1936: 
                   1937: sub inst_rulecheck {
1.923     raeburn  1938:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1939:     my %returnhash;
                   1940:     if ($udom ne '') {
                   1941:         if (ref($rules) eq 'ARRAY') {
                   1942:             @{$rules} = map {&escape($_);} (@{$rules});
                   1943:             my $rulestr = join(':',@{$rules});
                   1944:             my $homeserver=&domain($udom,'primary');
                   1945:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1946:                 my $response;
                   1947:                 if ($item eq 'username') {                
                   1948:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1949:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1950:                                               $homeserver));
1.923     raeburn  1951:                 } elsif ($item eq 'id') {
                   1952:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1953:                                               ':'.&escape($id).':'.$rulestr,
                   1954:                                               $homeserver));
1.945     raeburn  1955:                 } elsif ($item eq 'selfcreate') {
                   1956:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1957:                                                &escape($udom).':'.&escape($uname).
                   1958:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1959:                 }
1.912     raeburn  1960:                 if ($response ne 'refused') {
                   1961:                     my @pairs=split(/\&/,$response);
                   1962:                     foreach my $item (@pairs) {
                   1963:                         my ($key,$value)=split(/=/,$item,2);
                   1964:                         $key = &unescape($key);
                   1965:                         next if ($key =~ /^error: 2 /);
                   1966:                         $returnhash{$key}=&thaw_unescape($value);
                   1967:                     }
                   1968:                 }
                   1969:             }
                   1970:         }
                   1971:     }
                   1972:     return %returnhash;
                   1973: }
                   1974: 
                   1975: sub inst_userrules {
1.923     raeburn  1976:     my ($udom,$check) = @_;
1.912     raeburn  1977:     my (%ruleshash,@ruleorder);
                   1978:     if ($udom ne '') {
                   1979:         my $homeserver=&domain($udom,'primary');
                   1980:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1981:             my $response;
                   1982:             if ($check eq 'id') {
                   1983:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1984:                                  $homeserver);
1.943     raeburn  1985:             } elsif ($check eq 'email') {
                   1986:                 $response=&reply('instemailrules:'.&escape($udom),
                   1987:                                  $homeserver);
1.923     raeburn  1988:             } else {
                   1989:                 $response=&reply('instuserrules:'.&escape($udom),
                   1990:                                  $homeserver);
                   1991:             }
1.912     raeburn  1992:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1993:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1994:                 ($response ne 'no_such_host')) {
                   1995:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1996:                 my @pairs=split(/\&/,$hashitems);
                   1997:                 foreach my $item (@pairs) {
                   1998:                     my ($key,$value)=split(/=/,$item,2);
                   1999:                     $key = &unescape($key);
                   2000:                     next if ($key =~ /^error: 2 /);
                   2001:                     $ruleshash{$key}=&thaw_unescape($value);
                   2002:                 }
                   2003:                 my @esc_order = split(/\&/,$orderitems);
                   2004:                 foreach my $item (@esc_order) {
                   2005:                     push(@ruleorder,&unescape($item));
                   2006:                 }
                   2007:             }
                   2008:         }
                   2009:     }
                   2010:     return (\%ruleshash,\@ruleorder);
                   2011: }
                   2012: 
1.976     raeburn  2013: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2014: 
                   2015: sub get_domain_defaults {
1.1172.2.35  raeburn  2016:     my ($domain,$ignore_cache) = @_;
                   2017:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2018:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2019:     unless ($ignore_cache) {
                   2020:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2021:         if (defined($cached)) {
                   2022:             if (ref($result) eq 'HASH') {
                   2023:                 return %{$result};
                   2024:             }
1.943     raeburn  2025:         }
                   2026:     }
                   2027:     my %domdefaults;
                   2028:     my %domconfig =
1.989     raeburn  2029:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2030:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2031:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2032:                                   'requestauthor','selfenrollment',
                   2033:                                   'coursecategories'],$domain);
1.1172.2.41  raeburn  2034:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2035:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2036:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2037:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2038:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2039:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2040:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2041:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  2042:     } else {
                   2043:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2044:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2045:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2046:     }
1.976     raeburn  2047:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2048:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2049:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2050:         } else {
                   2051:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2052:         }
1.1172.2.6  raeburn  2053:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2054:         foreach my $item (@usertools) {
                   2055:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2056:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2057:             }
                   2058:         }
1.1172.2.29  raeburn  2059:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2060:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2061:         }
1.976     raeburn  2062:     }
1.985     raeburn  2063:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2064:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2065:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2066:         }
                   2067:     }
1.1172.2.9  raeburn  2068:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2069:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2070:     }
1.989     raeburn  2071:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2072:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2073:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2074:         }
                   2075:     }
1.1047    raeburn  2076:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2077:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2078:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2079:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2080:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2081:         }
1.1172.2.41  raeburn  2082:         foreach my $type (@coursetypes) {
                   2083:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2084:                 unless ($type eq 'community') {
                   2085:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2086:                 }
                   2087:             }
                   2088:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2089:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2090:             }
1.1172.2.60  raeburn  2091:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2092:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2093:                     $domdefaults{$type.'postsubtimeout'} =
                   2094:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2095:                 }
                   2096:             }
1.1172.2.30  raeburn  2097:         }
1.1047    raeburn  2098:     }
1.1073    raeburn  2099:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2100:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2101:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2102:         }
                   2103:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2104:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2105:         }
1.1172.2.62! raeburn  2106:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
        !          2107:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
        !          2108:         }
1.1073    raeburn  2109:     }
1.1172.2.41  raeburn  2110:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2111:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2112:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2113:                             'approval','limit');
                   2114:             foreach my $type (@coursetypes) {
                   2115:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2116:                     my @mgrdc = ();
                   2117:                     foreach my $item (@settings) {
                   2118:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2119:                             push(@mgrdc,$item);
                   2120:                         }
                   2121:                     }
                   2122:                     if (@mgrdc) {
                   2123:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2124:                     }
                   2125:                 }
                   2126:             }
                   2127:         }
                   2128:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2129:             foreach my $type (@coursetypes) {
                   2130:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2131:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2132:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2133:                     }
                   2134:                 }
                   2135:             }
                   2136:         }
                   2137:     }
1.1172.2.46  raeburn  2138:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2139:         $domdefaults{'catauth'} = 'std';
                   2140:         $domdefaults{'catunauth'} = 'std';
                   2141:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2142:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2143:         }
                   2144:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2145:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2146:         }
                   2147:     }
1.1172.2.23  raeburn  2148:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2149:     return %domdefaults;
                   2150: }
                   2151: 
1.344     www      2152: # --------------------------------------------------- Assign a key to a student
                   2153: 
                   2154: sub assign_access_key {
1.364     www      2155: #
                   2156: # a valid key looks like uname:udom#comments
                   2157: # comments are being appended
                   2158: #
1.498     www      2159:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2160:     $kdom=
1.620     albertel 2161:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2162:     $knum=
1.620     albertel 2163:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2164:     $cdom=
1.620     albertel 2165:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2166:     $cnum=
1.620     albertel 2167:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2168:     $udom=$env{'user.name'} unless (defined($udom));
                   2169:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2170:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2171:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2172:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2173:                                                   # assigned to this person
                   2174:                                                   # - this should not happen,
1.345     www      2175:                                                   # unless something went wrong
                   2176:                                                   # the first time around
                   2177: # ready to assign
1.364     www      2178:         $logentry=$1.'; '.$logentry;
1.496     www      2179:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2180:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2181: # key now belongs to user
1.346     www      2182: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2183:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2184:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2185:                 return 'ok';
                   2186:             } else {
                   2187:                 return 
                   2188:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2189: 	    }
                   2190:         } else {
                   2191:             return 'error: Could not assign key, try again later.';
                   2192:         }
1.364     www      2193:     } elsif (!$existing{$ckey}) {
1.345     www      2194: # the key does not exist
                   2195: 	return 'error: The key does not exist';
                   2196:     } else {
                   2197: # the key is somebody else's
                   2198: 	return 'error: The key is already in use';
                   2199:     }
1.344     www      2200: }
                   2201: 
1.364     www      2202: # ------------------------------------------ put an additional comment on a key
                   2203: 
                   2204: sub comment_access_key {
                   2205: #
                   2206: # a valid key looks like uname:udom#comments
                   2207: # comments are being appended
                   2208: #
                   2209:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2210:     $cdom=
1.620     albertel 2211:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2212:     $cnum=
1.620     albertel 2213:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2214:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2215:     if ($existing{$ckey}) {
                   2216:         $existing{$ckey}.='; '.$logentry;
                   2217: # ready to assign
1.367     www      2218:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2219:                                                  $cdom,$cnum) eq 'ok') {
                   2220: 	    return 'ok';
                   2221:         } else {
                   2222: 	    return 'error: Count not store comment.';
                   2223:         }
                   2224:     } else {
                   2225: # the key does not exist
                   2226: 	return 'error: The key does not exist';
                   2227:     }
                   2228: }
                   2229: 
1.344     www      2230: # ------------------------------------------------------ Generate a set of keys
                   2231: 
                   2232: sub generate_access_keys {
1.364     www      2233:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2234:     $cdom=
1.620     albertel 2235:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2236:     $cnum=
1.620     albertel 2237:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2238:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2239:     unless (($cdom) && ($cnum)) { return 0; }
                   2240:     if ($number>10000) { return 0; }
                   2241:     sleep(2); # make sure don't get same seed twice
                   2242:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2243:     my $total=0;
                   2244:     for (my $i=1;$i<=$number;$i++) {
                   2245:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2246:                   sprintf("%lx",int(100000*rand)).'-'.
                   2247:                   sprintf("%lx",int(100000*rand));
                   2248:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2249:        $newkey=~s/0/h/g; # and also 0 and O
                   2250:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2251:        if ($existing{$newkey}) {
                   2252:            $i--;
                   2253:        } else {
1.364     www      2254: 	  if (&put('accesskeys',
                   2255:               { $newkey => '# generated '.localtime().
1.620     albertel 2256:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2257:                            '; '.$logentry },
                   2258: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2259:               $total++;
                   2260: 	  }
                   2261:        }
                   2262:     }
1.620     albertel 2263:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2264:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2265:     return $total;
                   2266: }
                   2267: 
                   2268: # ------------------------------------------------------- Validate an accesskey
                   2269: 
                   2270: sub validate_access_key {
                   2271:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2272:     $cdom=
1.620     albertel 2273:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2274:     $cnum=
1.620     albertel 2275:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2276:     $udom=$env{'user.domain'} unless (defined($udom));
                   2277:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2278:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2279:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2280: }
                   2281: 
                   2282: # ------------------------------------- Find the section of student in a course
1.652     albertel 2283: sub devalidate_getsection_cache {
                   2284:     my ($udom,$unam,$courseid)=@_;
                   2285:     my $hashid="$udom:$unam:$courseid";
                   2286:     &devalidate_cache_new('getsection',$hashid);
                   2287: }
1.298     matthew  2288: 
1.815     albertel 2289: sub courseid_to_courseurl {
                   2290:     my ($courseid) = @_;
                   2291:     #already url style courseid
                   2292:     return $courseid if ($courseid =~ m{^/});
                   2293: 
                   2294:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2295: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2296: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2297: 	return "/$cdom/$cnum";
                   2298:     }
                   2299: 
                   2300:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2301:     if (exists($courseinfo{'num'})) {
                   2302: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2303:     }
                   2304: 
                   2305:     return undef;
                   2306: }
                   2307: 
1.298     matthew  2308: sub getsection {
                   2309:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2310:     my $cachetime=1800;
1.551     albertel 2311: 
                   2312:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2313:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2314:     if (defined($cached)) { return $result; }
                   2315: 
1.298     matthew  2316:     my %Pending; 
                   2317:     my %Expired;
                   2318:     #
                   2319:     # Each role can either have not started yet (pending), be active, 
                   2320:     #    or have expired.
                   2321:     #
                   2322:     # If there is an active role, we are done.
                   2323:     #
                   2324:     # If there is more than one role which has not started yet, 
                   2325:     #     choose the one which will start sooner
                   2326:     # If there is one role which has not started yet, return it.
                   2327:     #
                   2328:     # If there is more than one expired role, choose the one which ended last.
                   2329:     # If there is a role which has expired, return it.
                   2330:     #
1.815     albertel 2331:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2332:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2333:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2334:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2335:         my $section=$1;
                   2336:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2337:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2338:         my $now=time;
1.548     albertel 2339:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2340:             $Expired{$end}=$section;
                   2341:             next;
                   2342:         }
1.548     albertel 2343:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2344:             $Pending{$start}=$section;
                   2345:             next;
                   2346:         }
1.599     albertel 2347:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2348:     }
                   2349:     #
                   2350:     # Presumedly there will be few matching roles from the above
                   2351:     # loop and the sorting time will be negligible.
                   2352:     if (scalar(keys(%Pending))) {
                   2353:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2354:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2355:     } 
                   2356:     if (scalar(keys(%Expired))) {
                   2357:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2358:         my $time = pop(@sorted);
1.599     albertel 2359:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2360:     }
1.599     albertel 2361:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2362: }
1.70      www      2363: 
1.599     albertel 2364: sub save_cache {
                   2365:     &purge_remembered();
1.722     albertel 2366:     #&Apache::loncommon::validate_page();
1.620     albertel 2367:     undef(%env);
1.780     albertel 2368:     undef($env_loaded);
1.599     albertel 2369: }
1.452     albertel 2370: 
1.599     albertel 2371: my $to_remember=-1;
                   2372: my %remembered;
                   2373: my %accessed;
                   2374: my $kicks=0;
                   2375: my $hits=0;
1.849     albertel 2376: sub make_key {
                   2377:     my ($name,$id) = @_;
1.872     albertel 2378:     if (length($id) > 65 
                   2379: 	&& length(&escape($id)) > 200) {
                   2380: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2381:     }
1.849     albertel 2382:     return &escape($name.':'.$id);
                   2383: }
                   2384: 
1.599     albertel 2385: sub devalidate_cache_new {
                   2386:     my ($name,$id,$debug) = @_;
                   2387:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2388:     $id=&make_key($name,$id);
1.599     albertel 2389:     $memcache->delete($id);
                   2390:     delete($remembered{$id});
                   2391:     delete($accessed{$id});
                   2392: }
                   2393: 
                   2394: sub is_cached_new {
                   2395:     my ($name,$id,$debug) = @_;
1.849     albertel 2396:     $id=&make_key($name,$id);
1.599     albertel 2397:     if (exists($remembered{$id})) {
1.1133    foxr     2398: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2399: 	$accessed{$id}=[&gettimeofday()];
                   2400: 	$hits++;
                   2401: 	return ($remembered{$id},1);
                   2402:     }
                   2403:     my $value = $memcache->get($id);
                   2404:     if (!(defined($value))) {
                   2405: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2406: 	return (undef,undef);
1.416     albertel 2407:     }
1.599     albertel 2408:     if ($value eq '__undef__') {
                   2409: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2410: 	$value=undef;
                   2411:     }
                   2412:     &make_room($id,$value,$debug);
                   2413:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2414:     return ($value,1);
                   2415: }
                   2416: 
                   2417: sub do_cache_new {
                   2418:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2419:     $id=&make_key($name,$id);
1.599     albertel 2420:     my $setvalue=$value;
                   2421:     if (!defined($setvalue)) {
                   2422: 	$setvalue='__undef__';
                   2423:     }
1.623     albertel 2424:     if (!defined($time) ) {
                   2425: 	$time=600;
                   2426:     }
1.599     albertel 2427:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2428:     my $result = $memcache->set($id,$setvalue,$time);
                   2429:     if (! $result) {
1.872     albertel 2430: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2431: 	$memcache->disconnect_all();
1.872     albertel 2432:     }
1.600     albertel 2433:     # need to make a copy of $value
1.919     albertel 2434:     &make_room($id,$value,$debug);
1.599     albertel 2435:     return $value;
                   2436: }
                   2437: 
                   2438: sub make_room {
                   2439:     my ($id,$value,$debug)=@_;
1.919     albertel 2440: 
                   2441:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2442:                                     : $value;
1.599     albertel 2443:     if ($to_remember<0) { return; }
                   2444:     $accessed{$id}=[&gettimeofday()];
                   2445:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2446:     my $to_kick;
                   2447:     my $max_time=0;
                   2448:     foreach my $other (keys(%accessed)) {
                   2449: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2450: 	    $to_kick=$other;
                   2451: 	    $max_time=&tv_interval($accessed{$other});
                   2452: 	}
                   2453:     }
                   2454:     delete($remembered{$to_kick});
                   2455:     delete($accessed{$to_kick});
                   2456:     $kicks++;
                   2457:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2458:     return;
                   2459: }
                   2460: 
1.599     albertel 2461: sub purge_remembered {
1.604     albertel 2462:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2463:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2464:     undef(%remembered);
                   2465:     undef(%accessed);
1.428     albertel 2466: }
1.70      www      2467: # ------------------------------------- Read an entry from a user's environment
                   2468: 
                   2469: sub userenvironment {
                   2470:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2471:     my $items;
                   2472:     foreach my $item (@what) {
                   2473:         $items.=&escape($item).'&';
                   2474:     }
                   2475:     $items=~s/\&$//;
1.70      www      2476:     my %returnhash=();
1.1009    raeburn  2477:     my $uhome = &homeserver($unam,$udom);
                   2478:     unless ($uhome eq 'no_host') {
                   2479:         my @answer=split(/\&/, 
                   2480:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2481:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2482:             return %returnhash;
                   2483:         }
1.1009    raeburn  2484:         my $i;
                   2485:         for ($i=0;$i<=$#what;$i++) {
                   2486: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2487:         }
1.70      www      2488:     }
                   2489:     return %returnhash;
1.1       albertel 2490: }
                   2491: 
1.617     albertel 2492: # ---------------------------------------------------------- Get a studentphoto
                   2493: sub studentphoto {
                   2494:     my ($udom,$unam,$ext) = @_;
                   2495:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2496:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2497:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2498:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2499:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2500:             } else {
                   2501:                 my ($result,$perm_reqd)=
1.707     albertel 2502: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2503:                 if ($result eq 'ok') {
                   2504:                     if (!($perm_reqd eq 'yes')) {
                   2505:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2506:                     }
                   2507:                 }
                   2508:             }
                   2509:         }
                   2510:     } else {
                   2511:         my ($result,$perm_reqd) = 
1.707     albertel 2512: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2513:         if ($result eq 'ok') {
                   2514:             if (!($perm_reqd eq 'yes')) {
                   2515:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2516:             }
                   2517:         }
                   2518:     }
                   2519:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2520: }
                   2521: 
                   2522: sub retrievestudentphoto {
                   2523:     my ($udom,$unam,$ext,$type) = @_;
                   2524:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2525:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2526:     if ($ret eq 'ok') {
                   2527:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2528:         if ($type eq 'thumbnail') {
                   2529:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2530:         }
                   2531:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2532:         return $tokenurl;
                   2533:     } else {
                   2534:         if ($type eq 'thumbnail') {
                   2535:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2536:         } else { 
                   2537:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2538:         }
1.617     albertel 2539:     }
                   2540: }
                   2541: 
1.263     www      2542: # -------------------------------------------------------------------- New chat
                   2543: 
                   2544: sub chatsend {
1.724     raeburn  2545:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2546:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2547:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2548:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2549:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2550: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2551: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2552: }
                   2553: 
                   2554: # ------------------------------------------ Find current version of a resource
                   2555: 
                   2556: sub getversion {
                   2557:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2558:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2559:     return &currentversion(&filelocation('',$fname));
                   2560: }
                   2561: 
                   2562: sub currentversion {
                   2563:     my $fname=shift;
                   2564:     my $author=$fname;
                   2565:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2566:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2567:     my $home=&homeserver($uname,$udom);
1.292     www      2568:     if ($home eq 'no_host') { 
                   2569:         return -1; 
                   2570:     }
1.1112    www      2571:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2572:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2573: 	return -1;
                   2574:     }
1.1112    www      2575:     return $answer;
1.263     www      2576: }
                   2577: 
1.1111    www      2578: #
                   2579: # Return special version number of resource if set by override, empty otherwise
                   2580: #
                   2581: sub usedversion {
                   2582:     my $fname=shift;
                   2583:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2584:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2585:     if ($urlversion) { return $urlversion; }
                   2586:     return '';
                   2587: }
                   2588: 
1.1       albertel 2589: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2590: 
1.1       albertel 2591: sub subscribe {
                   2592:     my $fname=shift;
1.761     raeburn  2593:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2594:     $fname=~s/[\n\r]//g;
1.1       albertel 2595:     my $author=$fname;
                   2596:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2597:     my ($udom,$uname)=split(/\//,$author);
                   2598:     my $home=homeserver($uname,$udom);
1.335     albertel 2599:     if ($home eq 'no_host') {
                   2600:         return 'not_found';
1.1       albertel 2601:     }
                   2602:     my $answer=reply("sub:$fname",$home);
1.64      www      2603:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2604: 	$answer.=' by '.$home;
                   2605:     }
1.1       albertel 2606:     return $answer;
                   2607: }
                   2608:     
1.8       www      2609: # -------------------------------------------------------------- Replicate file
                   2610: 
                   2611: sub repcopy {
                   2612:     my $filename=shift;
1.23      www      2613:     $filename=~s/\/+/\//g;
1.1142    raeburn  2614:     my $londocroot = $perlvar{'lonDocRoot'};
                   2615:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2616:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2617:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2618: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2619: 	return &repcopy_userfile($filename);
                   2620:     }
1.532     albertel 2621:     $filename=~s/[\n\r]//g;
1.8       www      2622:     my $transname="$filename.in.transfer";
1.828     www      2623: # FIXME: this should flock
1.607     raeburn  2624:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2625:     my $remoteurl=subscribe($filename);
1.64      www      2626:     if ($remoteurl =~ /^con_lost by/) {
                   2627: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2628:            return 'unavailable';
1.8       www      2629:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2630: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2631: 	   return 'not_found';
1.64      www      2632:     } elsif ($remoteurl =~ /^rejected by/) {
                   2633: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2634:            return 'forbidden';
1.20      www      2635:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2636:            return 'ok';
1.8       www      2637:     } else {
1.290     www      2638:         my $author=$filename;
                   2639:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2640:         my ($udom,$uname)=split(/\//,$author);
                   2641:         my $home=homeserver($uname,$udom);
                   2642:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2643:            my @parts=split(/\//,$filename);
                   2644:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2645:            if ($path ne "$londocroot/res") {
1.8       www      2646:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2647: 	       return 'bad_request';
1.8       www      2648:            }
                   2649:            my $count;
                   2650:            for ($count=5;$count<$#parts;$count++) {
                   2651:                $path.="/$parts[$count]";
                   2652:                if ((-e $path)!=1) {
                   2653: 		   mkdir($path,0777);
                   2654:                }
                   2655:            }
                   2656:            my $ua=new LWP::UserAgent;
                   2657:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2658:            my $response=$ua->request($request,$transname);
                   2659:            if ($response->is_error()) {
                   2660: 	       unlink($transname);
                   2661:                my $message=$response->status_line;
1.672     albertel 2662:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2663:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2664:                return 'unavailable';
1.8       www      2665:            } else {
1.16      www      2666: 	       if ($remoteurl!~/\.meta$/) {
                   2667:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2668:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2669:                   if ($mresponse->is_error()) {
                   2670: 		      unlink($filename.'.meta');
                   2671:                       &logthis(
1.672     albertel 2672:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2673:                   }
                   2674: 	       }
1.8       www      2675:                rename($transname,$filename);
1.607     raeburn  2676:                return 'ok';
1.8       www      2677:            }
1.290     www      2678:        }
1.8       www      2679:     }
1.330     www      2680: }
                   2681: 
                   2682: # ------------------------------------------------ Get server side include body
                   2683: sub ssi_body {
1.381     albertel 2684:     my ($filelink,%form)=@_;
1.606     matthew  2685:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2686:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2687:     }
1.953     www      2688:     my $output='';
                   2689:     my $response;
1.980     raeburn  2690:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2691:        ($output,$response)=&externalssi($filelink);
1.953     www      2692:     } else {
1.1004    droeschl 2693:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2694:        $filelink .= 'inhibitmenu=yes';
1.953     www      2695:        ($output,$response)=&ssi($filelink,%form);
                   2696:     }
1.778     albertel 2697:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2698:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2699:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2700:     if (wantarray) {
                   2701:         return ($output, $response);
                   2702:     } else {
                   2703:         return $output;
                   2704:     }
1.8       www      2705: }
                   2706: 
1.15      www      2707: # --------------------------------------------------------- Server Side Include
                   2708: 
1.782     albertel 2709: sub absolute_url {
                   2710:     my ($host_name) = @_;
                   2711:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2712:     if ($host_name eq '') {
                   2713: 	$host_name = $ENV{'SERVER_NAME'};
                   2714:     }
                   2715:     return $protocol.$host_name;
                   2716: }
                   2717: 
1.942     foxr     2718: #
                   2719: #   Server side include.
                   2720: # Parameters:
                   2721: #  fn     Possibly encrypted resource name/id.
                   2722: #  form   Hash that describes how the rendering should be done
                   2723: #         and other things.
1.944     foxr     2724: # Returns:
1.950     raeburn  2725: #   Scalar context: The content of the response.
                   2726: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2727: #     
1.15      www      2728: sub ssi {
                   2729: 
1.944     foxr     2730:     my ($fn,%form)=@_;
1.15      www      2731:     my $ua=new LWP::UserAgent;
1.23      www      2732:     my $request;
1.711     albertel 2733: 
                   2734:     $form{'no_update_last_known'}=1;
1.895     albertel 2735:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2736:     if (%form) {
1.782     albertel 2737:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58  raeburn  2738:       $request->content(join('&',map {
                   2739:             my $name = escape($_);
                   2740:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   2741:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   2742:             : &escape($form{$_}) );
                   2743:         } keys(%form)));
1.23      www      2744:     } else {
1.782     albertel 2745:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2746:     }
                   2747: 
1.15      www      2748:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2  raeburn  2749:     my $response= $ua->request($request);
1.944     foxr     2750:     if (wantarray) {
1.1172.2.3  raeburn  2751: 	return ($response->content, $response);
1.944     foxr     2752:     } else {
1.1172.2.3  raeburn  2753: 	return $response->content;
1.942     foxr     2754:     }
1.324     www      2755: }
                   2756: 
                   2757: sub externalssi {
                   2758:     my ($url)=@_;
                   2759:     my $ua=new LWP::UserAgent;
                   2760:     my $request=new HTTP::Request('GET',$url);
                   2761:     my $response=$ua->request($request);
1.954     raeburn  2762:     if (wantarray) {
                   2763:         return ($response->content, $response);
                   2764:     } else {
                   2765:         return $response->content;
                   2766:     }
1.15      www      2767: }
1.254     www      2768: 
1.492     albertel 2769: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2770: 
                   2771: sub allowuploaded {
                   2772:     my ($srcurl,$url)=@_;
                   2773:     $url=&clutter(&declutter($url));
                   2774:     my $dir=$url;
                   2775:     $dir=~s/\/[^\/]+$//;
                   2776:     my %httpref=();
                   2777:     my $httpurl=&hreflocation('',$url);
                   2778:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2779:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2780: }
1.477     raeburn  2781: 
1.1172.2.13  raeburn  2782: #
                   2783: # Determine if the current user should be able to edit a particular resource,
                   2784: # when viewing in course context.
                   2785: # (a) When viewing resource used to determine if "Edit" item is included in
                   2786: #     Functions.
                   2787: # (b) When displaying folder contents in course editor, used to determine if
                   2788: #     "Edit" link will be displayed alongside resource.
                   2789: #
                   2790: #  input: six args -- filename (decluttered), course number, course domain,
                   2791: #                   url, symb (if registered) and group (if this is a group
                   2792: #                   item -- e.g., bulletin board, group page etc.).
                   2793: #  output: array of five scalars --
                   2794: #          $cfile -- url for file editing if editable on current server
                   2795: #          $home -- homeserver of resource (i.e., for author if published,
                   2796: #                                           or course if uploaded.).
                   2797: #          $switchserver --  1 if server switch will be needed.
                   2798: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   2799: #          $forceview -- 1 if icon/link should be to go to view mode
                   2800: #
                   2801: 
                   2802: sub can_edit_resource {
                   2803:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   2804:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   2805: #
                   2806: # For aboutme pages user can only edit his/her own.
                   2807: #
                   2808:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   2809:         my ($sdom,$sname) = ($1,$2);
                   2810:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   2811:             $home = $env{'user.home'};
                   2812:             $cfile = $resurl;
                   2813:             if ($env{'form.forceedit'}) {
                   2814:                 $forceview = 1;
                   2815:             } else {
                   2816:                 $forceedit = 1;
                   2817:             }
                   2818:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2819:         } else {
                   2820:             return;
                   2821:         }
                   2822:     }
                   2823: 
                   2824:     if ($env{'request.course.id'}) {
                   2825:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   2826:         if ($group ne '') {
                   2827: # if this is a group homepage or group bulletin board, check group privs
                   2828:             my $allowed = 0;
                   2829:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   2830:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   2831:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2832:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2833:                     $allowed = 1;
                   2834:                 }
                   2835:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   2836:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2837:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2838:                     $allowed = 1;
                   2839:                 }
                   2840:             }
                   2841:             if ($allowed) {
                   2842:                 $home=&homeserver($cnum,$cdom);
                   2843:                 if ($env{'form.forceedit'}) {
                   2844:                     $forceview = 1;
                   2845:                 } else {
                   2846:                     $forceedit = 1;
                   2847:                 }
                   2848:                 $cfile = $resurl;
                   2849:             } else {
                   2850:                 return;
                   2851:             }
                   2852:         } else {
1.1172.2.15  raeburn  2853:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2854:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   2855:                     return;
                   2856:                 }
                   2857:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  2858: #
                   2859: # No edit allowed where CC has switched to student role.
                   2860: #
                   2861:                 return;
                   2862:             }
                   2863:         }
                   2864:     }
                   2865: 
                   2866:     if ($file ne '') {
                   2867:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   2868:             if (&is_course_upload($file,$cnum,$cdom)) {
                   2869:                 $uploaded = 1;
                   2870:                 $incourse = 1;
                   2871:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   2872:                     $cfile = &hreflocation('',$file);
                   2873:                     if ($env{'form.forceedit'}) {
                   2874:                         $forceview = 1;
                   2875:                     } else {
                   2876:                         $forceedit = 1;
                   2877:                     }
                   2878:                 }
                   2879:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   2880:                 $incourse = 1;
                   2881:                 if ($env{'form.forceedit'}) {
                   2882:                     $forceview = 1;
                   2883:                 } else {
                   2884:                     $forceedit = 1;
                   2885:                 }
                   2886:                 $cfile = $resurl;
                   2887:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   2888:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   2889:                     $incourse = 1;
                   2890:                     if ($env{'form.forceedit'}) {
                   2891:                         $forceview = 1;
                   2892:                     } else {
                   2893:                         $forceedit = 1;
                   2894:                     }
                   2895:                     $cfile = $resurl;
                   2896:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   2897:                     $incourse = 1;
                   2898:                     $cfile = $resurl.'/smpedit';
                   2899:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   2900:                     $incourse = 1;
                   2901:                     if ($env{'form.forceedit'}) {
                   2902:                         $forceview = 1;
                   2903:                     } else {
                   2904:                         $forceedit = 1;
                   2905:                     }
                   2906:                     $cfile = $resurl;
1.1172.2.15  raeburn  2907:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2908:                     $incourse = 1;
                   2909:                     if ($env{'form.forceedit'}) {
                   2910:                         $forceview = 1;
                   2911:                     } else {
                   2912:                         $forceedit = 1;
                   2913:                     }
                   2914:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  2915:                 }
                   2916:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   2917:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   2918:                 if (&is_on_map($template)) {
                   2919:                     $incourse = 1;
                   2920:                     $forceview = 1;
                   2921:                     $cfile = $template;
                   2922:                 }
                   2923:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   2924:                     $incourse = 1;
                   2925:                     if ($env{'form.forceedit'}) {
                   2926:                         $forceview = 1;
                   2927:                     } else {
                   2928:                         $forceedit = 1;
                   2929:                     }
                   2930:                     $cfile = $resurl;
                   2931:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   2932:                 $incourse = 1;
                   2933:                 $forceview = 1;
                   2934:                 if ($symb) {
                   2935:                     my ($map,$id,$res)=&decode_symb($symb);
                   2936:                     $env{'request.symb'} = $symb;
                   2937:                     $cfile = &clutter($res);
                   2938:                 } else {
                   2939:                     $cfile = $env{'form.suppurl'};
                   2940:                     $cfile =~ s{^http://}{};
                   2941:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   2942:                 }
1.1172.2.31  raeburn  2943:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2944:                 if ($env{'form.forceedit'}) {
                   2945:                     $forceview = 1;
                   2946:                 } else {
                   2947:                     $forceedit = 1;
                   2948:                 }
                   2949:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  2950:             }
                   2951:         }
                   2952:         if ($uploaded || $incourse) {
                   2953:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  2954:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  2955:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   2956:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   2957:             # Check that the user has permission to edit this resource
                   2958:             my $setpriv = 1;
                   2959:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   2960:             if (defined($cfudom)) {
                   2961:                 $home=&homeserver($cfuname,$cfudom);
                   2962:                 $cfile=$file;
                   2963:             }
                   2964:         }
                   2965:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   2966:             (($home ne '') && ($home ne 'no_host'))) {
                   2967:             my @ids=&current_machine_ids();
                   2968:             unless (grep(/^\Q$home\E$/,@ids)) {
                   2969:                 $switchserver=1;
                   2970:             }
                   2971:         }
                   2972:     }
                   2973:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2974: }
                   2975: 
                   2976: sub is_course_upload {
                   2977:     my ($file,$cnum,$cdom) = @_;
                   2978:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   2979:     $uploadpath =~ s{^\/}{};
                   2980:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   2981:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   2982:         return 1;
                   2983:     }
                   2984:     return;
                   2985: }
                   2986: 
                   2987: sub in_course {
                   2988:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   2989:     if ($hideprivileged) {
                   2990:         my $skipuser;
1.1172.2.23  raeburn  2991:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   2992:         my @possdoms = ($cdom);
                   2993:         if ($coursehash{'checkforpriv'}) {
                   2994:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   2995:         }
                   2996:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  2997:             $skipuser = 1;
                   2998:             if ($coursehash{'nothideprivileged'}) {
                   2999:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3000:                     my $user;
                   3001:                     if ($item =~ /:/) {
                   3002:                         $user = $item;
                   3003:                     } else {
                   3004:                         $user = join(':',split(/[\@]/,$item));
                   3005:                     }
                   3006:                     if ($user eq $uname.':'.$udom) {
                   3007:                         undef($skipuser);
                   3008:                         last;
                   3009:                     }
                   3010:                 }
                   3011:             }
                   3012:             if ($skipuser) {
                   3013:                 return 0;
                   3014:             }
                   3015:         }
                   3016:     }
                   3017:     $type ||= 'any';
                   3018:     if (!defined($cdom) || !defined($cnum)) {
                   3019:         my $cid  = $env{'request.course.id'};
                   3020:         $cdom = $env{'course.'.$cid.'.domain'};
                   3021:         $cnum = $env{'course.'.$cid.'.num'};
                   3022:     }
                   3023:     my $typesref;
                   3024:     if (($type eq 'any') || ($type eq 'all')) {
                   3025:         $typesref = ['active','previous','future'];
                   3026:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3027:         $typesref = [$type];
                   3028:     }
                   3029:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3030:                               $typesref,undef,[$cdom]);
                   3031:     my ($tmp) = keys(%roles);
                   3032:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3033:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3034:     if (@course_roles > 0) {
                   3035:         return 1;
                   3036:     }
                   3037:     return 0;
                   3038: }
                   3039: 
1.478     albertel 3040: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3041: # input: action, courseID, current domain, intended
1.637     raeburn  3042: #        path to file, source of file, instruction to parse file for objects,
                   3043: #        ref to hash for embedded objects,
                   3044: #        ref to hash for codebase of java objects.
1.1095    raeburn  3045: #        reference to scalar to accommodate mime type determined
                   3046: #          from File::MMagic if $parser = parse.
1.637     raeburn  3047: #
1.485     raeburn  3048: # output: url to file (if action was uploaddoc), 
                   3049: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3050: #
1.478     albertel 3051: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3052: # course.
1.477     raeburn  3053: #
1.478     albertel 3054: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3055: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3056: #          course's home server.
1.477     raeburn  3057: #
1.478     albertel 3058: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3059: #          be copied from $source (current location) to 
                   3060: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3061: #         and will then be copied to
                   3062: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3063: #         course's home server.
1.485     raeburn  3064: #
1.481     raeburn  3065: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3066: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3067: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3068: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3069: #         in course's home server.
1.637     raeburn  3070: #
1.477     raeburn  3071: 
                   3072: sub process_coursefile {
1.1095    raeburn  3073:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3074:         $mimetype)=@_;
1.477     raeburn  3075:     my $fetchresult;
1.638     albertel 3076:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3077:     if ($action eq 'propagate') {
1.638     albertel 3078:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3079: 			     $home);
1.481     raeburn  3080:     } else {
1.477     raeburn  3081:         my $fpath = '';
                   3082:         my $fname = $file;
1.478     albertel 3083:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3084:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3085:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3086:         if ($action eq 'copy') {
                   3087:             if ($source eq '') {
                   3088:                 $fetchresult = 'no source file';
                   3089:                 return $fetchresult;
                   3090:             } else {
                   3091:                 my $destination = $filepath.'/'.$fname;
                   3092:                 rename($source,$destination);
                   3093:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3094:                                  $home);
1.481     raeburn  3095:             }
                   3096:         } elsif ($action eq 'uploaddoc') {
                   3097:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 3098:             print $fh $env{'form.'.$source};
1.481     raeburn  3099:             close($fh);
1.637     raeburn  3100:             if ($parser eq 'parse') {
1.1024    raeburn  3101:                 my $mm = new File::MMagic;
1.1095    raeburn  3102:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3103:                 if ($type eq 'text/html') {
1.1024    raeburn  3104:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3105:                     unless ($parse_result eq 'ok') {
                   3106:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3107:                     }
1.637     raeburn  3108:                 }
1.1095    raeburn  3109:                 if (ref($mimetype)) {
                   3110:                     $$mimetype = $type;
                   3111:                 } 
1.637     raeburn  3112:             }
1.477     raeburn  3113:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3114:                                  $home);
1.481     raeburn  3115:             if ($fetchresult eq 'ok') {
                   3116:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3117:             } else {
                   3118:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3119:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3120:                 return '/adm/notfound.html';
                   3121:             }
1.477     raeburn  3122:         }
                   3123:     }
1.485     raeburn  3124:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3125:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3126:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3127:     }
                   3128:     return $fetchresult;
                   3129: }
                   3130: 
1.637     raeburn  3131: sub build_filepath {
                   3132:     my ($fpath) = @_;
                   3133:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3134:     unless ($fpath eq '') {
                   3135:         my @parts=split('/',$fpath);
                   3136:         foreach my $part (@parts) {
                   3137:             $filepath.= '/'.$part;
                   3138:             if ((-e $filepath)!=1) {
                   3139:                 mkdir($filepath,0777);
                   3140:             }
                   3141:         }
                   3142:     }
                   3143:     return $filepath;
                   3144: }
                   3145: 
                   3146: sub store_edited_file {
1.638     albertel 3147:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3148:     my $file = $primary_url;
                   3149:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3150:     my $fpath = '';
                   3151:     my $fname = $file;
                   3152:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3153:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3154:     my $filepath = &build_filepath($fpath);
                   3155:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3156:     print $fh $content;
                   3157:     close($fh);
1.638     albertel 3158:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3159:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3160: 			  $home);
1.637     raeburn  3161:     if ($$fetchresult eq 'ok') {
                   3162:         return '/uploaded/'.$fpath.'/'.$fname;
                   3163:     } else {
1.638     albertel 3164:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3165: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3166:         return '/adm/notfound.html';
                   3167:     }
                   3168: }
                   3169: 
1.531     albertel 3170: sub clean_filename {
1.831     albertel 3171:     my ($fname,$args)=@_;
1.315     www      3172: # Replace Windows backslashes by forward slashes
1.257     www      3173:     $fname=~s/\\/\//g;
1.831     albertel 3174:     if (!$args->{'keep_path'}) {
                   3175:         # Get rid of everything but the actual filename
                   3176: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3177:     }
1.315     www      3178: # Replace spaces by underscores
                   3179:     $fname=~s/\s+/\_/g;
                   3180: # Replace all other weird characters by nothing
1.831     albertel 3181:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3182: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3183: # numbers
                   3184:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3185:     return $fname;
                   3186: }
1.1051    raeburn  3187: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3188: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3189: # image with the same aspect ratio as the original, but with dimensions which do 
                   3190: # not exceed $resizewidth and $resizeheight.
                   3191:  
1.984     neumanie 3192: sub resizeImage {
1.1051    raeburn  3193:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3194:     my $ima = Image::Magick->new;
                   3195:     my $resized;
                   3196:     if (-e $img_path) {
                   3197:         $ima->Read($img_path);
                   3198:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3199:             my $width = $ima->Get('width');
                   3200:             my $height = $ima->Get('height');
                   3201:             if ($width > $resizewidth) {
                   3202: 	        my $factor = $width/$resizewidth;
                   3203:                 my $newheight = $height/$factor;
                   3204:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3205:                 $resized = 1;
                   3206:             }
                   3207:         }
                   3208:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3209:             my $width = $ima->Get('width');
                   3210:             my $height = $ima->Get('height');
                   3211:             if ($height > $resizeheight) {
                   3212:                 my $factor = $height/$resizeheight;
                   3213:                 my $newwidth = $width/$factor;
                   3214:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3215:                 $resized = 1;
                   3216:             }
                   3217:         }
                   3218:         if ($resized) {
                   3219:             $ima->Write($img_path);
                   3220:         }
                   3221:     }
                   3222:     return;
1.977     amueller 3223: }
                   3224: 
1.608     albertel 3225: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3226: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3227: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3228: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3229: #                                    canceloverwrite, or ''. 
                   3230: #                   if 'coursedoc': upload to the current course
                   3231: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3232: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3233: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3234: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3235: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3236: #        $allfiles - reference to hash for embedded objects
                   3237: #        $codebase - reference to hash for codebase of java objects
                   3238: #        $desuname - username for permanent storage of uploaded file
                   3239: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3240: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3241: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3242: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3243: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3244: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3245: #                    from File::MMagic.
1.858     raeburn  3246: # 
1.686     albertel 3247: # output: url of file in userspace, or error: <message> 
                   3248: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3249: 
1.531     albertel 3250: sub userfileupload {
1.1090    raeburn  3251:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3252:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3253:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3254:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3255:     $fname=&clean_filename($fname);
1.1090    raeburn  3256:     # See if there is anything left
1.257     www      3257:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3258:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3259:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3260:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3261:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3262:         my $now = time;
1.1090    raeburn  3263:         my $filepath;
1.1095    raeburn  3264:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3265:              $filepath = 'tmp/helprequests/'.$now;
                   3266:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3267:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3268:                          '_'.$env{'user.domain'}.'/pending';
                   3269:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3270:             my ($docuname,$docudom);
                   3271:             if ($destudom) {
                   3272:                 $docudom = $destudom;
                   3273:             } else {
                   3274:                 $docudom = $env{'user.domain'};
                   3275:             }
                   3276:             if ($destuname) {
                   3277:                 $docuname = $destuname;
                   3278:             } else {
                   3279:                 $docuname = $env{'user.name'};
                   3280:             }
                   3281:             if (exists($env{'form.group'})) {
                   3282:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3283:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3284:             }
                   3285:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3286:             if ($context eq 'canceloverwrite') {
                   3287:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3288:                 if (-e  $tempfile) {
                   3289:                     my @info = stat($tempfile);
                   3290:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3291:                         unlink($tempfile);
                   3292:                     }
                   3293:                 }
                   3294:                 return;
1.523     raeburn  3295:             }
                   3296:         }
1.1090    raeburn  3297:         # Create the directory if not present
1.741     raeburn  3298:         my @parts=split(/\//,$filepath);
                   3299:         my $fullpath = $perlvar{'lonDaemons'};
                   3300:         for (my $i=0;$i<@parts;$i++) {
                   3301:             $fullpath .= '/'.$parts[$i];
                   3302:             if ((-e $fullpath)!=1) {
                   3303:                 mkdir($fullpath,0777);
                   3304:             }
                   3305:         }
                   3306:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3307:         print $fh $env{'form.'.$formname};
                   3308:         close($fh);
1.1090    raeburn  3309:         if ($context eq 'existingfile') {
                   3310:             my @info = stat($fullpath.'/'.$fname);
                   3311:             return ($fullpath.'/'.$fname,$info[9]);
                   3312:         } else {
                   3313:             return $fullpath.'/'.$fname;
                   3314:         }
1.523     raeburn  3315:     }
1.995     raeburn  3316:     if ($subdir eq 'scantron') {
                   3317:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3318:     } else {
1.995     raeburn  3319:         $fname="$subdir/$fname";
                   3320:     }
1.1090    raeburn  3321:     if ($context eq 'coursedoc') {
1.638     albertel 3322: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3323: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3324:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3325:             return &finishuserfileupload($docuname,$docudom,
                   3326: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3327: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3328:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3329:         } else {
1.1172.2.21  raeburn  3330:             if ($env{'form.folder'}) {
                   3331:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3332:             }
1.638     albertel 3333:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3334: 				       $fname,$formname,$parser,
1.1095    raeburn  3335: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3336:         }
1.719     banghart 3337:     } elsif (defined($destuname)) {
                   3338:         my $docuname=$destuname;
                   3339:         my $docudom=$destudom;
1.860     raeburn  3340: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3341: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3342:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3343:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3344:     } else {
1.638     albertel 3345:         my $docuname=$env{'user.name'};
                   3346:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3347:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3348:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3349:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3350:         }
1.860     raeburn  3351: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3352: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3353:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3354:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3355:     }
1.271     www      3356: }
                   3357: 
                   3358: sub finishuserfileupload {
1.860     raeburn  3359:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3360:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3361:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3362:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3363:   
1.860     raeburn  3364:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3365:     $file=$fname;
                   3366:     if ($fname=~m|/|) {
                   3367:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3368: 	$path.=$fnamepath.'/';
                   3369:     }
1.259     www      3370:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3371:     my $count;
                   3372:     for ($count=4;$count<=$#parts;$count++) {
                   3373:         $filepath.="/$parts[$count]";
                   3374:         if ((-e $filepath)!=1) {
                   3375: 	    mkdir($filepath,0777);
                   3376:         }
                   3377:     }
1.984     neumanie 3378: 
1.258     www      3379: # Save the file
                   3380:     {
1.701     albertel 3381: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3382: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3383: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3384: 	    return '/adm/notfound.html';
                   3385: 	}
1.1090    raeburn  3386:         if ($context eq 'overwrite') {
1.1117    foxr     3387:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3388:             my $target = $filepath.'/'.$file;
                   3389:             if (-e $source) {
                   3390:                 my @info = stat($source);
                   3391:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3392:                     unless (&File::Copy::move($source,$target)) {
                   3393:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3394:                         return "Moving from $source failed";
                   3395:                     }
                   3396:                 } else {
                   3397:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3398:                 }
                   3399:             } else {
                   3400:                 return "Temporary file: $source missing";
                   3401:             }
                   3402:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3403: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3404: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3405: 	    return '/adm/notfound.html';
                   3406: 	}
1.570     albertel 3407: 	close(FH);
1.1051    raeburn  3408:         if ($resizewidth && $resizeheight) {
                   3409:             my $mm = new File::MMagic;
                   3410:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3411:             if ($mime_type =~ m{^image/}) {
                   3412: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3413:             }  
1.977     amueller 3414: 	}
1.258     www      3415:     }
1.1152    raeburn  3416:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3417:         if (ref($mimetype)) {
                   3418:             if ($$mimetype eq '') {
                   3419:                 my $mm = new File::MMagic;
                   3420:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3421:                 $$mimetype = $type;
                   3422:             }
                   3423:         }
                   3424:     }
1.637     raeburn  3425:     if ($parser eq 'parse') {
1.1152    raeburn  3426:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3427:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3428:                                                        $allfiles,$codebase);
                   3429:             unless ($parse_result eq 'ok') {
                   3430:                 &logthis('Failed to parse '.$filepath.$file.
                   3431: 	   	         ' for embedded media: '.$parse_result); 
                   3432:             }
1.637     raeburn  3433:         }
                   3434:     }
1.860     raeburn  3435:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3436:         my $input = $filepath.'/'.$file;
                   3437:         my $output = $filepath.'/'.'tn-'.$file;
                   3438:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3439:         system("convert -sample $thumbsize $input $output");
                   3440:         if (-e $filepath.'/'.'tn-'.$file) {
                   3441:             $fetchthumb  = 1; 
                   3442:         }
                   3443:     }
1.858     raeburn  3444:  
1.259     www      3445: # Notify homeserver to grep it
                   3446: #
1.984     neumanie 3447:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3448:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3449:     if ($fetchresult eq 'ok') {
1.860     raeburn  3450:         if ($fetchthumb) {
                   3451:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3452:             if ($thumbresult ne 'ok') {
                   3453:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3454:                          $docuhome.': '.$thumbresult);
                   3455:             }
                   3456:         }
1.259     www      3457: #
1.258     www      3458: # Return the URL to it
1.494     albertel 3459:         return '/uploaded/'.$path.$file;
1.263     www      3460:     } else {
1.494     albertel 3461:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3462: 		 ': '.$fetchresult);
1.263     www      3463:         return '/adm/notfound.html';
1.858     raeburn  3464:     }
1.493     albertel 3465: }
                   3466: 
1.637     raeburn  3467: sub extract_embedded_items {
1.961     raeburn  3468:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3469:     my @state = ();
1.1164    raeburn  3470:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3471:     my %javafiles = (
                   3472:                       codebase => '',
                   3473:                       code => '',
                   3474:                       archive => ''
                   3475:                     );
                   3476:     my %mediafiles = (
                   3477:                       src => '',
                   3478:                       movie => '',
                   3479:                      );
1.648     raeburn  3480:     my $p;
                   3481:     if ($content) {
                   3482:         $p = HTML::LCParser->new($content);
                   3483:     } else {
1.961     raeburn  3484:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3485:     }
1.641     albertel 3486:     while (my $t=$p->get_token()) {
1.640     albertel 3487: 	if ($t->[0] eq 'S') {
                   3488: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3489: 	    push(@state, $tagname);
1.648     raeburn  3490:             if (lc($tagname) eq 'allow') {
                   3491:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3492:             }
1.640     albertel 3493: 	    if (lc($tagname) eq 'img') {
                   3494: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3495: 	    }
1.886     albertel 3496: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  3497:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   3498: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   3499:                 }
1.886     albertel 3500: 	    }
1.645     raeburn  3501:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3502:                 my $src;
1.645     raeburn  3503:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3504:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3505:                 } else {
1.1164    raeburn  3506:                     if ($attr->{'src'} ne '') {
                   3507:                         $src = $attr->{'src'};
                   3508:                         &add_filetype($allfiles,$src,'src');
                   3509:                     }
                   3510:                 }
                   3511:                 my $text = $p->get_trimmed_text();
                   3512:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3513:                     my @swfargs = split(/,/,$1);
                   3514:                     foreach my $item (@swfargs) {
                   3515:                         $item =~ s/["']//g;
                   3516:                         $item =~ s/^\s+//;
                   3517:                         $item =~ s/\s+$//;
                   3518:                     }
                   3519:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3520:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3521:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3522:                         } else {
                   3523:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3524:                         }
                   3525:                     }
1.645     raeburn  3526:                 }
                   3527:             }
                   3528:             if (lc($tagname) eq 'link') {
                   3529:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3530:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3531:                 }
                   3532:             }
1.640     albertel 3533: 	    if (lc($tagname) eq 'object' ||
                   3534: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3535: 		foreach my $item (keys(%javafiles)) {
                   3536: 		    $javafiles{$item} = '';
                   3537: 		}
1.1164    raeburn  3538:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3539:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3540:                 }
1.640     albertel 3541: 	    }
                   3542: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3543: 		my $name = lc($attr->{'name'});
                   3544: 		foreach my $item (keys(%javafiles)) {
                   3545: 		    if ($name eq $item) {
                   3546: 			$javafiles{$item} = $attr->{'value'};
                   3547: 			last;
                   3548: 		    }
                   3549: 		}
1.1164    raeburn  3550:                 my $pathfrom;
1.640     albertel 3551: 		foreach my $item (keys(%mediafiles)) {
                   3552: 		    if ($name eq $item) {
1.1164    raeburn  3553:                         $pathfrom = $attr->{'value'};
                   3554:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3555: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3556: 			last;
                   3557: 		    }
                   3558: 		}
1.1164    raeburn  3559:                 if ($name eq 'flashvars') {
                   3560:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3561:                 }
                   3562:                 if ($pathfrom ne '') {
                   3563:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3564:                                          $pathfrom);
                   3565:                 }
1.640     albertel 3566: 	    }
                   3567: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3568: 		foreach my $item (keys(%javafiles)) {
                   3569: 		    if ($attr->{$item}) {
                   3570: 			$javafiles{$item} = $attr->{$item};
                   3571: 			last;
                   3572: 		    }
                   3573: 		}
                   3574: 		foreach my $item (keys(%mediafiles)) {
                   3575: 		    if ($attr->{$item}) {
                   3576: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3577: 			last;
                   3578: 		    }
                   3579: 		}
1.1164    raeburn  3580:                 if (lc($tagname) eq 'embed') {
                   3581:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3582:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3583:                                              $attr->{'src'});
                   3584:                     }
                   3585:                 }
1.640     albertel 3586: 	    }
1.1172.2.35  raeburn  3587:             if (lc($tagname) eq 'iframe') {
                   3588:                 my $src = $attr->{'src'} ;
                   3589:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   3590:                     &add_filetype($allfiles,$src,'src');
                   3591:                 } elsif ($src =~ m{^/}) {
                   3592:                     if ($env{'request.course.id'}) {
                   3593:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3594:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3595:                         my $url = &hreflocation('',$fullpath);
                   3596:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   3597:                             my $relpath = $1;
                   3598:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   3599:                                 &add_filetype($allfiles,$1,'src');
                   3600:                             }
                   3601:                         }
                   3602:                     }
                   3603:                 }
                   3604:             }
1.1164    raeburn  3605:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  3606:                 pop(@state);
1.1164    raeburn  3607:             }
1.640     albertel 3608: 	} elsif ($t->[0] eq 'E') {
                   3609: 	    my ($tagname) = ($t->[1]);
                   3610: 	    if ($javafiles{'codebase'} ne '') {
                   3611: 		$javafiles{'codebase'} .= '/';
                   3612: 	    }  
                   3613: 	    if (lc($tagname) eq 'applet' ||
                   3614: 		lc($tagname) eq 'object' ||
                   3615: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3616: 		) {
                   3617: 		foreach my $item (keys(%javafiles)) {
                   3618: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3619: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3620: 			&add_filetype($allfiles,$file,$item);
                   3621: 		    }
                   3622: 		}
                   3623: 	    } 
                   3624: 	    pop @state;
                   3625: 	}
                   3626:     }
1.1164    raeburn  3627:     foreach my $id (sort(keys(%flashvars))) {
                   3628:         if ($shockwave{$id} ne '') {
                   3629:             my @pairs = split(/\&/,$flashvars{$id});
                   3630:             foreach my $pair (@pairs) {
                   3631:                 my ($key,$value) = split(/\=/,$pair);
                   3632:                 if ($key eq 'thumb') {
                   3633:                     &add_filetype($allfiles,$value,$key);
                   3634:                 } elsif ($key eq 'content') {
                   3635:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3636:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3637:                     if ($ext ne '') {
                   3638:                         &add_filetype($allfiles,$path.$value,$ext);
                   3639:                     }
                   3640:                 }
                   3641:             }
                   3642:         }
                   3643:     }
1.637     raeburn  3644:     return 'ok';
                   3645: }
                   3646: 
1.639     albertel 3647: sub add_filetype {
                   3648:     my ($allfiles,$file,$type)=@_;
                   3649:     if (exists($allfiles->{$file})) {
                   3650: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3651: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3652: 	}
                   3653:     } else {
                   3654: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3655:     }
                   3656: }
                   3657: 
1.1164    raeburn  3658: sub embedded_dependency {
                   3659:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3660:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3661:         if (($identifier ne '') &&
                   3662:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3663:             ($pathfrom ne '')) {
                   3664:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3665:             foreach my $dep (@{$related->{$identifier}}) {
                   3666:                 &add_filetype($allfiles,$path.$dep,'object');
                   3667:             }
                   3668:         }
                   3669:     }
                   3670:     return;
                   3671: }
                   3672: 
1.493     albertel 3673: sub removeuploadedurl {
1.984     neumanie 3674:     my ($url)=@_;	
                   3675:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3676:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3677: }
                   3678: 
                   3679: sub removeuserfile {
                   3680:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3681:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3682:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3683:     if ($result eq 'ok') {	
1.798     raeburn  3684:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3685:             my $metafile = $fname.'.meta';
                   3686:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3687: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3688:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3689:             my $sqlresult = 
1.823     albertel 3690:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3691:                                         'portfolio_metadata',$group,
                   3692:                                         'delete');
1.798     raeburn  3693:         }
                   3694:     }
                   3695:     return $result;
1.257     www      3696: }
1.15      www      3697: 
1.530     albertel 3698: sub mkdiruserfile {
                   3699:     my ($docuname,$docudom,$dir)=@_;
                   3700:     my $home=&homeserver($docuname,$docudom);
                   3701:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3702: }
                   3703: 
1.531     albertel 3704: sub renameuserfile {
                   3705:     my ($docuname,$docudom,$old,$new)=@_;
                   3706:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3707:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3708:                         &escape("$old").':'.&escape("$new"),$home);
                   3709:     if ($result eq 'ok') {
                   3710:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3711:             my $oldmeta = $old.'.meta';
                   3712:             my $newmeta = $new.'.meta';
                   3713:             my $metaresult = 
                   3714:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3715: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3716:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3717:             my $sqlresult = 
1.823     albertel 3718:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3719:                                         'portfolio_metadata',$group,
                   3720:                                         'delete');
1.798     raeburn  3721:         }
                   3722:     }
                   3723:     return $result;
1.531     albertel 3724: }
                   3725: 
1.14      www      3726: # ------------------------------------------------------------------------- Log
                   3727: 
                   3728: sub log {
                   3729:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3730:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3731: }
                   3732: 
                   3733: # ------------------------------------------------------------------ Course Log
1.352     www      3734: #
                   3735: # This routine flushes several buffers of non-mission-critical nature
                   3736: #
1.157     www      3737: 
                   3738: sub flushcourselogs {
1.352     www      3739:     &logthis('Flushing log buffers');
                   3740: #
                   3741: # course logs
                   3742: # This is a log of all transactions in a course, which can be used
                   3743: # for data mining purposes
                   3744: #
                   3745: # It also collects the courseid database, which lists last transaction
                   3746: # times and course titles for all courseids
                   3747: #
                   3748:     my %courseidbuffer=();
1.921     raeburn  3749:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3750:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3751: 		          &escape($courselogs{$crsid}),
                   3752: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3753: 	    delete $courselogs{$crsid};
                   3754:         } else {
                   3755:             &logthis('Failed to flush log buffer for '.$crsid);
                   3756:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3757:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3758:                         " exceeded maximum size, deleting.</font>");
                   3759:                delete $courselogs{$crsid};
                   3760:             }
1.352     www      3761:         }
1.920     raeburn  3762:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3763:             'description' => $coursedescrbuf{$crsid},
                   3764:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3765:             'type'        => $coursetypebuf{$crsid},
                   3766:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3767:         };
1.191     harris41 3768:     }
1.352     www      3769: #
                   3770: # Write course id database (reverse lookup) to homeserver of courses 
                   3771: # Is used in pickcourse
                   3772: #
1.840     albertel 3773:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3774:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3775:                                     $courseidbuffer{$crs_home},
                   3776:                                     $crs_home,'timeonly');
1.352     www      3777:     }
                   3778: #
                   3779: # File accesses
                   3780: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3781: #
1.449     matthew  3782:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3783:         if ($entry =~ /___count$/) {
                   3784:             my ($dom,$name);
1.807     albertel 3785:             ($dom,$name,undef)=
1.811     albertel 3786: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3787:             if (! defined($dom) || $dom eq '' || 
                   3788:                 ! defined($name) || $name eq '') {
1.620     albertel 3789:                 my $cid = $env{'request.course.id'};
                   3790:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3791:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3792:             }
1.450     matthew  3793:             my $value = $accesshash{$entry};
                   3794:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3795:             my %temphash=($url => $value);
1.449     matthew  3796:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3797:             if ($result eq 'ok') {
                   3798:                 delete $accesshash{$entry};
                   3799:             }
                   3800:         } else {
1.811     albertel 3801:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3802:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3803:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3804:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3805:                 delete $accesshash{$entry};
                   3806:             }
1.185     www      3807:         }
1.191     harris41 3808:     }
1.352     www      3809: #
                   3810: # Roles
                   3811: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3812: #
1.800     albertel 3813:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3814:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3815: 	    split(/\:/,$entry);
                   3816:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3817:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3818:                 $rudom,$runame) eq 'ok') {
                   3819: 	    delete $userrolehash{$entry};
                   3820:         }
                   3821:     }
1.662     raeburn  3822: #
                   3823: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3824: #
                   3825:     my %domrolebuffer = ();
1.1000    raeburn  3826:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3827:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3828:         if ($domrolebuffer{$rudom}) {
                   3829:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3830:                       '='.&escape($domainrolehash{$entry});
                   3831:         } else {
                   3832:             $domrolebuffer{$rudom}.=&escape($entry).
                   3833:                       '='.&escape($domainrolehash{$entry});
                   3834:         }
                   3835:         delete $domainrolehash{$entry};
                   3836:     }
                   3837:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3838: 	my %servers = &get_servers($dom,'library');
                   3839: 	foreach my $tryserver (keys(%servers)) {
                   3840: 	    unless (&reply('domroleput:'.$dom.':'.
                   3841: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3842: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3843: 	    }
1.662     raeburn  3844:         }
                   3845:     }
1.186     www      3846:     $dumpcount++;
1.157     www      3847: }
                   3848: 
                   3849: sub courselog {
                   3850:     my $what=shift;
1.158     www      3851:     $what=time.':'.$what;
1.620     albertel 3852:     unless ($env{'request.course.id'}) { return ''; }
                   3853:     $coursedombuf{$env{'request.course.id'}}=
                   3854:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3855:     $coursenumbuf{$env{'request.course.id'}}=
                   3856:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3857:     $coursehombuf{$env{'request.course.id'}}=
                   3858:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3859:     $coursedescrbuf{$env{'request.course.id'}}=
                   3860:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3861:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3862:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3863:     $courseownerbuf{$env{'request.course.id'}}=
                   3864:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3865:     $coursetypebuf{$env{'request.course.id'}}=
                   3866:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3867:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3868: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3869:     } else {
1.620     albertel 3870: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3871:     }
1.620     albertel 3872:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3873: 	&flushcourselogs();
                   3874:     }
1.158     www      3875: }
                   3876: 
                   3877: sub courseacclog {
                   3878:     my $fnsymb=shift;
1.620     albertel 3879:     unless ($env{'request.course.id'}) { return ''; }
                   3880:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3881:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3882:         $what.=':POST';
1.583     matthew  3883:         # FIXME: Probably ought to escape things....
1.800     albertel 3884: 	foreach my $key (keys(%env)) {
                   3885:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3886:                 my $formitem = $1;
                   3887:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3888:                     $what.=':'.$formitem.'='.$env{$key};
                   3889:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3890:                     $what.=':'.$formitem.'='.$env{$key};
                   3891:                 }
1.158     www      3892:             }
1.191     harris41 3893:         }
1.583     matthew  3894:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3895:         # FIXME: We should not be depending on a form parameter that someone
                   3896:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3897:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3898:             $what.= ':POST';
                   3899:             # FIXME: Probably ought to escape things....
                   3900:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3901:                                  'crsdiscuss') {
1.620     albertel 3902:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3903:             }
                   3904:         }
1.158     www      3905:     }
                   3906:     &courselog($what);
1.149     www      3907: }
                   3908: 
1.185     www      3909: sub countacc {
                   3910:     my $url=&declutter(shift);
1.458     matthew  3911:     return if (! defined($url) || $url eq '');
1.620     albertel 3912:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3913: #
                   3914: # Mark that this url was used in this course
                   3915: #
1.620     albertel 3916:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3917: #
                   3918: # Increase the access count for this resource in this child process
                   3919: #
1.281     www      3920:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3921:     $accesshash{$key}++;
1.185     www      3922: }
1.349     www      3923: 
1.361     www      3924: sub linklog {
                   3925:     my ($from,$to)=@_;
                   3926:     $from=&declutter($from);
                   3927:     $to=&declutter($to);
                   3928:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3929:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3930: }
1.1160    www      3931: 
                   3932: sub statslog {
                   3933:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   3934:     if ($users<2) { return; }
                   3935:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   3936:             'course'       => $env{'request.course.id'},
                   3937:             'sections'     => '"all"',
                   3938:             'num_students' => $users,
                   3939:             'part'         => $part,
                   3940:             'symb'         => $symb,
                   3941:             'mean_tries'   => $av_attempts,
                   3942:             'deg_of_diff'  => $degdiff});
                   3943:     foreach my $key (keys(%dynstore)) {
                   3944:         $accesshash{$key}=$dynstore{$key};
                   3945:     }
                   3946: }
1.361     www      3947:   
1.349     www      3948: sub userrolelog {
                   3949:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 3950:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      3951:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3952:        $userrolehash
                   3953:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3954:                     =$tend.':'.$tstart;
1.662     raeburn  3955:     }
1.1169    droeschl 3956:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 3957:        $userrolehash
                   3958:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3959:                     =$tend.':'.$tstart;
                   3960:     }
1.1169    droeschl 3961:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  3962:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3963:        $domainrolehash
                   3964:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3965:                     = $tend.':'.$tstart;
                   3966:     }
1.351     www      3967: }
                   3968: 
1.957     raeburn  3969: sub courserolelog {
                   3970:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  3971:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3972:         my $cdom = $1;
                   3973:         my $cnum = $2;
                   3974:         my $sec = $3;
                   3975:         my $namespace = 'rolelog';
                   3976:         my %storehash = (
                   3977:                            role    => $trole,
                   3978:                            start   => $tstart,
                   3979:                            end     => $tend,
                   3980:                            selfenroll => $selfenroll,
                   3981:                            context    => $context,
                   3982:                         );
                   3983:         if ($trole eq 'gr') {
                   3984:             $namespace = 'groupslog';
                   3985:             $storehash{'group'} = $sec;
                   3986:         } else {
                   3987:             $storehash{'section'} = $sec;
                   3988:         }
                   3989:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   3990:                    $domain,$cnum,$cdom);
                   3991:         if (($trole ne 'st') || ($sec ne '')) {
                   3992:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  3993:         }
                   3994:     }
                   3995:     return;
                   3996: }
                   3997: 
1.1172.2.9  raeburn  3998: sub domainrolelog {
                   3999:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4000:     if ($area =~ m{^/($match_domain)/$}) {
                   4001:         my $cdom = $1;
                   4002:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4003:         my $namespace = 'rolelog';
                   4004:         my %storehash = (
                   4005:                            role    => $trole,
                   4006:                            start   => $tstart,
                   4007:                            end     => $tend,
                   4008:                            context => $context,
                   4009:                         );
                   4010:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4011:                    $domain,$domconfiguser,$cdom);
                   4012:     }
                   4013:     return;
                   4014: 
                   4015: }
                   4016: 
                   4017: sub coauthorrolelog {
                   4018:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4019:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4020:         my $audom = $1;
                   4021:         my $auname = $2;
                   4022:         my $namespace = 'rolelog';
                   4023:         my %storehash = (
                   4024:                            role    => $trole,
                   4025:                            start   => $tstart,
                   4026:                            end     => $tend,
                   4027:                            context => $context,
                   4028:                         );
                   4029:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4030:                    $domain,$auname,$audom);
                   4031:     }
                   4032:     return;
                   4033: }
                   4034: 
1.351     www      4035: sub get_course_adv_roles {
1.948     raeburn  4036:     my ($cid,$codes) = @_;
1.620     albertel 4037:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4038:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4039:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4040:     my %nothide=();
1.800     albertel 4041:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4042:         if ($user !~ /:/) {
                   4043: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4044:         } else {
                   4045:             $nothide{$user}=1;
                   4046:         }
1.470     www      4047:     }
1.1172.2.23  raeburn  4048:     my @possdoms = ($coursehash{'domain'});
                   4049:     if ($coursehash{'checkforpriv'}) {
                   4050:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4051:     }
1.351     www      4052:     my %returnhash=();
                   4053:     my %dumphash=
                   4054:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4055:     my $now=time;
1.997     raeburn  4056:     my %privileged;
1.1000    raeburn  4057:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4058: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4059:         if (($tstart) && ($tstart<0)) { next; }
                   4060:         if (($tend) && ($tend<$now)) { next; }
                   4061:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4062:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4063: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4064:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4065:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4066: 	if ($role eq 'cr') { next; }
1.948     raeburn  4067:         if ($codes) {
                   4068:             if ($section) { $role .= ':'.$section; }
                   4069:             if ($returnhash{$role}) {
                   4070:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4071:             } else {
                   4072:                 $returnhash{$role}=$username.':'.$domain;
                   4073:             }
1.351     www      4074:         } else {
1.988     raeburn  4075:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4076:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4077:             if ($returnhash{$key}) {
                   4078: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4079:             } else {
                   4080:                 $returnhash{$key}=$username.':'.$domain;
                   4081:             }
1.351     www      4082:         }
1.948     raeburn  4083:     }
1.400     www      4084:     return %returnhash;
                   4085: }
                   4086: 
                   4087: sub get_my_roles {
1.937     raeburn  4088:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4089:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4090:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4091:     my (%dumphash,%nothide);
1.1086    raeburn  4092:     if ($context eq 'userroles') {
1.1166    raeburn  4093:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4094:     } else {
1.1172.2.23  raeburn  4095:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4096:         if ($hidepriv) {
                   4097:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4098:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4099:                 if ($user !~ /:/) {
                   4100:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4101:                 } else {
                   4102:                     $nothide{$user} = 1;
                   4103:                 }
                   4104:             }
                   4105:         }
1.858     raeburn  4106:     }
1.400     www      4107:     my %returnhash=();
                   4108:     my $now=time;
1.999     raeburn  4109:     my %privileged;
1.800     albertel 4110:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4111:         my ($role,$tend,$tstart);
                   4112:         if ($context eq 'userroles') {
1.1149    raeburn  4113:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4114: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4115:         } else {
                   4116:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4117:         }
1.400     www      4118:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4119:         my $status = 'active';
1.939     raeburn  4120:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4121:             $status = 'previous';
                   4122:         } 
                   4123:         if (($tstart) && ($now<$tstart)) {
                   4124:             $status = 'future';
                   4125:         }
                   4126:         if (ref($types) eq 'ARRAY') {
                   4127:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4128:                 next;
                   4129:             } 
                   4130:         } else {
                   4131:             if ($status ne 'active') {
                   4132:                 next;
                   4133:             }
                   4134:         }
1.867     raeburn  4135:         my ($rolecode,$username,$domain,$section,$area);
                   4136:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  4137:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4138:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4139:         } else {
                   4140:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4141:         }
1.832     raeburn  4142:         if (ref($roledoms) eq 'ARRAY') {
                   4143:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4144:                 next;
                   4145:             }
                   4146:         }
                   4147:         if (ref($roles) eq 'ARRAY') {
                   4148:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4149:                 if ($role =~ /^cr\//) {
                   4150:                     if (!grep(/^cr$/,@{$roles})) {
                   4151:                         next;
                   4152:                     }
1.1104    raeburn  4153:                 } elsif ($role =~ /^gr\//) {
                   4154:                     if (!grep(/^gr$/,@{$roles})) {
                   4155:                         next;
                   4156:                     }
1.922     raeburn  4157:                 } else {
                   4158:                     next;
                   4159:                 }
1.832     raeburn  4160:             }
1.867     raeburn  4161:         }
1.937     raeburn  4162:         if ($hidepriv) {
1.1172.2.23  raeburn  4163:             my @privroles = ('dc','su');
1.999     raeburn  4164:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  4165:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4166:             } else {
1.1172.2.23  raeburn  4167:                 my $possdoms = [$domain];
                   4168:                 if (ref($roledoms) eq 'ARRAY') {
                   4169:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  4170:                 }
1.1172.2.23  raeburn  4171:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4172:                     if (!$nothide{$username.':'.$domain}) {
                   4173:                         next;
                   4174:                     }
                   4175:                 }
1.937     raeburn  4176:             }
                   4177:         }
1.933     raeburn  4178:         if ($withsec) {
                   4179:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4180:                 $tstart.':'.$tend;
                   4181:         } else {
                   4182:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4183:         }
1.832     raeburn  4184:     }
1.373     www      4185:     return %returnhash;
1.399     www      4186: }
                   4187: 
                   4188: # ----------------------------------------------------- Frontpage Announcements
                   4189: #
                   4190: #
                   4191: 
                   4192: sub postannounce {
                   4193:     my ($server,$text)=@_;
1.844     albertel 4194:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4195:     unless ($text=~/\w/) { $text=''; }
                   4196:     return &reply('setannounce:'.&escape($text),$server);
                   4197: }
                   4198: 
                   4199: sub getannounce {
1.448     albertel 4200: 
                   4201:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4202: 	my $announcement='';
1.800     albertel 4203: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4204: 	close($fh);
1.399     www      4205: 	if ($announcement=~/\w/) { 
                   4206: 	    return 
                   4207:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4208:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4209: 	} else {
                   4210: 	    return '';
                   4211: 	}
                   4212:     } else {
                   4213: 	return '';
                   4214:     }
1.351     www      4215: }
1.353     www      4216: 
                   4217: # ---------------------------------------------------------- Course ID routines
                   4218: # Deal with domain's nohist_courseid.db files
                   4219: #
                   4220: 
                   4221: sub courseidput {
1.921     raeburn  4222:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4223:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4224:     my $outcome;
                   4225:     if ($caller eq 'timeonly') {
                   4226:         my $cids = '';
                   4227:         foreach my $item (keys(%$storehash)) {
                   4228:             $cids.=&escape($item).'&';
                   4229:         }
                   4230:         $cids=~s/\&$//;
                   4231:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4232:                           $coursehome);       
                   4233:     } else {
                   4234:         my $items = '';
                   4235:         foreach my $item (keys(%$storehash)) {
                   4236:             $items.= &escape($item).'='.
                   4237:                      &freeze_escape($$storehash{$item}).'&';
                   4238:         }
                   4239:         $items=~s/\&$//;
                   4240:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4241:                           $coursehome);
1.918     raeburn  4242:     }
                   4243:     if ($outcome eq 'unknown_cmd') {
                   4244:         my $what;
                   4245:         foreach my $cid (keys(%$storehash)) {
                   4246:             $what .= &escape($cid).'=';
1.921     raeburn  4247:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4248:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4249:             }
                   4250:             $what =~ s/\:$/&/;
                   4251:         }
                   4252:         $what =~ s/\&$//;  
                   4253:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4254:     } else {
                   4255:         return $outcome;
                   4256:     }
1.353     www      4257: }
                   4258: 
                   4259: sub courseiddump {
1.921     raeburn  4260:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4261:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4262:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  4263:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
                   4264:         $hasuniquecode)=@_;
1.918     raeburn  4265:     my $as_hash = 1;
                   4266:     my %returnhash;
                   4267:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4268:     my %libserv = &all_library();
                   4269:     foreach my $tryserver (keys(%libserv)) {
                   4270:         if ( (  $hostidflag == 1 
                   4271: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4272: 	     || (!defined($hostidflag)) ) {
                   4273: 
1.918     raeburn  4274: 	    if (($domfilter eq '') ||
                   4275: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  4276:                 my $rep;
                   4277:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   4278:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   4279:                         join(":", (&host_domain($tryserver), $sincefilter,
                   4280:                                 &escape($descfilter), &escape($instcodefilter),
                   4281:                                 &escape($ownerfilter), &escape($coursefilter),
                   4282:                                 &escape($typefilter), &escape($regexp_ok),
                   4283:                                 $as_hash, &escape($selfenrollonly),
                   4284:                                 &escape($catfilter), $showhidden, $caller,
                   4285:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   4286:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.38  raeburn  4287:                                 &escape($creationcontext), $domcloner, $hasuniquecode)));
1.1172.2.22  raeburn  4288:                 } else {
                   4289:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4290:                              $sincefilter.':'.&escape($descfilter).':'.
                   4291:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4292:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4293:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4294:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4295:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4296:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4297:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.38  raeburn  4298:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
1.1172.2.22  raeburn  4299:                              $tryserver);
                   4300:                 }
                   4301: 
1.918     raeburn  4302:                 my @pairs=split(/\&/,$rep);
                   4303:                 foreach my $item (@pairs) {
                   4304:                     my ($key,$value)=split(/\=/,$item,2);
                   4305:                     $key = &unescape($key);
                   4306:                     next if ($key =~ /^error: 2 /);
                   4307:                     my $result = &thaw_unescape($value);
                   4308:                     if (ref($result) eq 'HASH') {
                   4309:                         $returnhash{$key}=$result;
                   4310:                     } else {
1.921     raeburn  4311:                         my @responses = split(/:/,$value);
                   4312:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4313:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4314:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4315:                         }
1.1008    raeburn  4316:                     }
1.353     www      4317:                 }
                   4318:             }
                   4319:         }
                   4320:     }
                   4321:     return %returnhash;
                   4322: }
                   4323: 
1.1055    raeburn  4324: sub courselastaccess {
                   4325:     my ($cdom,$cnum,$hostidref) = @_;
                   4326:     my %returnhash;
                   4327:     if ($cdom && $cnum) {
                   4328:         my $chome = &homeserver($cnum,$cdom);
                   4329:         if ($chome ne 'no_host') {
                   4330:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4331:             &extract_lastaccess(\%returnhash,$rep);
                   4332:         }
                   4333:     } else {
                   4334:         if (!$cdom) { $cdom=''; }
                   4335:         my %libserv = &all_library();
                   4336:         foreach my $tryserver (keys(%libserv)) {
                   4337:             if (ref($hostidref) eq 'ARRAY') {
                   4338:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4339:             } 
                   4340:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4341:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4342:                 &extract_lastaccess(\%returnhash,$rep);
                   4343:             }
                   4344:         }
                   4345:     }
                   4346:     return %returnhash;
                   4347: }
                   4348: 
                   4349: sub extract_lastaccess {
                   4350:     my ($returnhash,$rep) = @_;
                   4351:     if (ref($returnhash) eq 'HASH') {
                   4352:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4353:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4354:                  $rep eq '') {
                   4355:             my @pairs=split(/\&/,$rep);
                   4356:             foreach my $item (@pairs) {
                   4357:                 my ($key,$value)=split(/\=/,$item,2);
                   4358:                 $key = &unescape($key);
                   4359:                 next if ($key =~ /^error: 2 /);
                   4360:                 $returnhash->{$key} = &thaw_unescape($value);
                   4361:             }
                   4362:         }
                   4363:     }
                   4364:     return;
                   4365: }
                   4366: 
1.658     raeburn  4367: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4368: 
                   4369: sub dcmailput {
1.685     raeburn  4370:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4371:     my $status = &Apache::lonnet::critical(
1.740     www      4372:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4373:        &escape($message),$server);
1.662     raeburn  4374:     return $status;
                   4375: }
                   4376: 
1.658     raeburn  4377: sub dcmaildump {
                   4378:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4379:     my %returnhash=();
1.846     albertel 4380: 
                   4381:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4382:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4383:                                                          &escape($enddate).':';
                   4384: 	my @esc_senders=map { &escape($_)} @$senders;
                   4385: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4386: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4387:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4388:             if (($key) && ($value)) {
                   4389:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4390:             }
                   4391:         }
                   4392:     }
                   4393:     return %returnhash;
                   4394: }
1.662     raeburn  4395: # ---------------------------------------------------------- Domain roles
                   4396: 
                   4397: sub get_domain_roles {
                   4398:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4399:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4400:         $startdate = '.';
                   4401:     }
1.1018    raeburn  4402:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4403:         $enddate = '.';
                   4404:     }
1.922     raeburn  4405:     my $rolelist;
                   4406:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  4407:         $rolelist = join('&',@{$roles});
1.922     raeburn  4408:     }
1.662     raeburn  4409:     my %personnel = ();
1.841     albertel 4410: 
                   4411:     my %servers = &get_servers($dom,'library');
                   4412:     foreach my $tryserver (keys(%servers)) {
                   4413: 	%{$personnel{$tryserver}}=();
                   4414: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4415: 					    &escape($startdate).':'.
                   4416: 					    &escape($enddate).':'.
                   4417: 					    &escape($rolelist), $tryserver))) {
                   4418: 	    my ($key,$value) = split(/\=/,$line,2);
                   4419: 	    if (($key) && ($value)) {
                   4420: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4421: 	    }
                   4422: 	}
1.662     raeburn  4423:     }
                   4424:     return %personnel;
                   4425: }
1.658     raeburn  4426: 
1.1057    www      4427: # ----------------------------------------------------------- Interval timing 
1.149     www      4428: 
1.1153    www      4429: {
                   4430: # Caches needed for speedup of navmaps
                   4431: # We don't want to cache this for very long at all (5 seconds at most)
                   4432: # 
                   4433: # The user for whom we cache
                   4434: my $cachedkey='';
                   4435: # The cached times for this user
                   4436: my %cachedtimes=();
                   4437: # When this was last done
                   4438: my $cachedtime=();
                   4439: 
                   4440: sub load_all_first_access {
1.1154    raeburn  4441:     my ($uname,$udom)=@_;
1.1156    www      4442:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  4443:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4444:         return;
                   4445:     }
                   4446:     $cachedtime=time;
                   4447:     $cachedkey=$uname.':'.$udom;
                   4448:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4449: }
                   4450: 
1.504     albertel 4451: sub get_first_access {
1.1162    raeburn  4452:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4453:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4454:     if ($argsymb) { $symb=$argsymb; }
                   4455:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4456:     if ($argmap) { $map = $argmap; }
1.926     albertel 4457:     if ($type eq 'course') {
                   4458: 	$res='course';
                   4459:     } elsif ($type eq 'map') {
1.588     albertel 4460: 	$res=&symbread($map);
                   4461:     } else {
                   4462: 	$res=$symb;
                   4463:     }
1.1153    www      4464:     &load_all_first_access($uname,$udom);
                   4465:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4466: }
                   4467: 
                   4468: sub set_first_access {
1.1162    raeburn  4469:     my ($type,$interval)=@_;
1.790     albertel 4470:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4471:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4472:     if ($type eq 'course') {
                   4473: 	$res='course';
                   4474:     } elsif ($type eq 'map') {
1.588     albertel 4475: 	$res=&symbread($map);
                   4476:     } else {
                   4477: 	$res=$symb;
                   4478:     }
1.1153    www      4479:     $cachedkey='';
1.1162    raeburn  4480:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4481:     if (!$firstaccess) {
1.1162    raeburn  4482:         my $start = time;
                   4483: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4484:                           $udom,$uname);
                   4485:         if ($putres eq 'ok') {
                   4486:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4487:                  $udom,$uname); 
                   4488:             &appenv(
                   4489:                      {
                   4490:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4491:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4492:                      }
                   4493:                   );
                   4494:         }
                   4495:         return $putres;
1.505     albertel 4496:     }
                   4497:     return 'already_set';
1.504     albertel 4498: }
1.1153    www      4499: }
1.1172.2.32  raeburn  4500: 
                   4501: sub checkout {
                   4502:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   4503:     my $now=time;
                   4504:     my $lonhost=$perlvar{'lonHostID'};
                   4505:     my $infostr=&escape(
                   4506:                  'CHECKOUTTOKEN&'.
                   4507:                  $tuname.'&'.
                   4508:                  $tudom.'&'.
                   4509:                  $tcrsid.'&'.
                   4510:                  $symb.'&'.
                   4511:                  $now.'&'.$ENV{'REMOTE_ADDR'});
                   4512:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   4513:     if ($token=~/^error\:/) {
                   4514:         &logthis("<font color=\"blue\">WARNING: ".
                   4515:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4516:                  "</font>");
                   4517:         return '';
                   4518:     }
                   4519: 
                   4520:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   4521:     $token=~tr/a-z/A-Z/;
                   4522: 
                   4523:     my %infohash=('resource.0.outtoken' => $token,
                   4524:                   'resource.0.checkouttime' => $now,
                   4525:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
                   4526: 
                   4527:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   4528:        return '';
                   4529:     } else {
                   4530:         &logthis("<font color=\"blue\">WARNING: ".
                   4531:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4532:                  "</font>");
                   4533:     }
                   4534: 
                   4535:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   4536:                          &escape('Checkout '.$infostr.' - '.
                   4537:                                                  $token)) ne 'ok') {
                   4538:         return '';
                   4539:     } else {
                   4540:         &logthis("<font color=\"blue\">WARNING: ".
                   4541:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4542:                  "</font>");
                   4543:     }
                   4544:     return $token;
                   4545: }
                   4546: 
                   4547: # ------------------------------------------------------------ Check in an item
                   4548: 
                   4549: sub checkin {
                   4550:     my $token=shift;
                   4551:     my $now=time;
                   4552:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   4553:     $lonhost=~tr/A-Z/a-z/;
                   4554:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   4555:     $dtoken=~s/\W/\_/g;
                   4556:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   4557:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   4558: 
                   4559:     unless (($tuname) && ($tudom)) {
                   4560:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   4561:         return '';
                   4562:     }
                   4563: 
                   4564:     unless (&allowed('mgr',$tcrsid)) {
                   4565:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   4566:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   4567:         return '';
                   4568:     }
                   4569: 
                   4570:     my %infohash=('resource.0.intoken' => $token,
                   4571:                   'resource.0.checkintime' => $now,
                   4572:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
                   4573: 
                   4574:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   4575:        return '';
                   4576:     }
                   4577: 
                   4578:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   4579:                          &escape('Checkin - '.$token)) ne 'ok') {
                   4580:         return '';
                   4581:     }
                   4582: 
                   4583:     return ($symb,$tuname,$tudom,$tcrsid);
                   4584: }
                   4585: 
1.110     www      4586: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4587: 
                   4588: sub expirespread {
                   4589:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4590:     my $cid=$env{'request.course.id'}; 
1.110     www      4591:     if ($cid) {
                   4592:        my $now=time;
                   4593:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4594:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4595:                             $env{'course.'.$cid.'.num'}.
1.110     www      4596: 	        	    ':nohist_expirationdates:'.
                   4597:                             &escape($key).'='.$now,
1.620     albertel 4598:                             $env{'course.'.$cid.'.home'})
1.110     www      4599:     }
                   4600:     return 'ok';
1.14      www      4601: }
                   4602: 
1.109     www      4603: # ----------------------------------------------------- Devalidate Spreadsheets
                   4604: 
                   4605: sub devalidate {
1.325     www      4606:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4607:     my $cid=$env{'request.course.id'}; 
1.109     www      4608:     if ($cid) {
1.391     matthew  4609:         # delete the stored spreadsheets for
                   4610:         # - the student level sheet of this user in course's homespace
                   4611:         # - the assessment level sheet for this resource 
                   4612:         #   for this user in user's homespace
1.553     albertel 4613: 	# - current conditional state info
1.325     www      4614: 	my $key=$uname.':'.$udom.':';
1.109     www      4615:         my $status=
1.299     matthew  4616: 	    &del('nohist_calculatedsheets',
1.391     matthew  4617: 		 [$key.'studentcalc:'],
1.620     albertel 4618: 		 $env{'course.'.$cid.'.domain'},
                   4619: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4620: 		.' '.
                   4621: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4622: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4623:         unless ($status eq 'ok ok') {
                   4624:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4625:                     $uname.' at '.$udom.' for '.
1.109     www      4626: 		    $symb.': '.$status);
1.133     albertel 4627:         }
1.553     albertel 4628: 	&delenv('user.state.'.$cid);
1.109     www      4629:     }
                   4630: }
                   4631: 
1.265     albertel 4632: sub get_scalar {
                   4633:     my ($string,$end) = @_;
                   4634:     my $value;
                   4635:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4636: 	$value = $1;
                   4637:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4638: 	$value = $1;
                   4639:     }
                   4640:     return &unescape($value);
                   4641: }
                   4642: 
                   4643: sub array2str {
                   4644:   my (@array) = @_;
                   4645:   my $result=&arrayref2str(\@array);
                   4646:   $result=~s/^__ARRAY_REF__//;
                   4647:   $result=~s/__END_ARRAY_REF__$//;
                   4648:   return $result;
                   4649: }
                   4650: 
1.204     albertel 4651: sub arrayref2str {
                   4652:   my ($arrayref) = @_;
1.265     albertel 4653:   my $result='__ARRAY_REF__';
1.204     albertel 4654:   foreach my $elem (@$arrayref) {
1.265     albertel 4655:     if(ref($elem) eq 'ARRAY') {
                   4656:       $result.=&arrayref2str($elem).'&';
                   4657:     } elsif(ref($elem) eq 'HASH') {
                   4658:       $result.=&hashref2str($elem).'&';
                   4659:     } elsif(ref($elem)) {
                   4660:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4661:     } else {
                   4662:       $result.=&escape($elem).'&';
                   4663:     }
                   4664:   }
                   4665:   $result=~s/\&$//;
1.265     albertel 4666:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4667:   return $result;
                   4668: }
                   4669: 
1.168     albertel 4670: sub hash2str {
1.204     albertel 4671:   my (%hash) = @_;
                   4672:   my $result=&hashref2str(\%hash);
1.265     albertel 4673:   $result=~s/^__HASH_REF__//;
                   4674:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4675:   return $result;
                   4676: }
                   4677: 
                   4678: sub hashref2str {
                   4679:   my ($hashref)=@_;
1.265     albertel 4680:   my $result='__HASH_REF__';
1.800     albertel 4681:   foreach my $key (sort(keys(%$hashref))) {
                   4682:     if (ref($key) eq 'ARRAY') {
                   4683:       $result.=&arrayref2str($key).'=';
                   4684:     } elsif (ref($key) eq 'HASH') {
                   4685:       $result.=&hashref2str($key).'=';
                   4686:     } elsif (ref($key)) {
1.265     albertel 4687:       $result.='=';
1.800     albertel 4688:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4689:     } else {
1.1132    raeburn  4690: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4691:     }
                   4692: 
1.800     albertel 4693:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4694:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4695:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4696:       $result.=&hashref2str($hashref->{$key}).'&';
                   4697:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4698:        $result.='&';
1.800     albertel 4699:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4700:     } else {
1.800     albertel 4701:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4702:     }
                   4703:   }
1.168     albertel 4704:   $result=~s/\&$//;
1.265     albertel 4705:   $result .= '__END_HASH_REF__';
1.168     albertel 4706:   return $result;
                   4707: }
                   4708: 
                   4709: sub str2hash {
1.265     albertel 4710:     my ($string)=@_;
                   4711:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4712:     return %$hash;
                   4713: }
                   4714: 
                   4715: sub str2hashref {
1.168     albertel 4716:   my ($string) = @_;
1.265     albertel 4717: 
                   4718:   my %hash;
                   4719: 
                   4720:   if($string !~ /^__HASH_REF__/) {
                   4721:       if (! ($string eq '' || !defined($string))) {
                   4722: 	  $hash{'error'}='Not hash reference';
                   4723:       }
                   4724:       return (\%hash, $string);
                   4725:   }
                   4726: 
                   4727:   $string =~ s/^__HASH_REF__//;
                   4728: 
                   4729:   while($string !~ /^__END_HASH_REF__/) {
                   4730:       #key
                   4731:       my $key='';
                   4732:       if($string =~ /^__HASH_REF__/) {
                   4733:           ($key, $string)=&str2hashref($string);
                   4734:           if(defined($key->{'error'})) {
                   4735:               $hash{'error'}='Bad data';
                   4736:               return (\%hash, $string);
                   4737:           }
                   4738:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4739:           ($key, $string)=&str2arrayref($string);
                   4740:           if($key->[0] eq 'Array reference error') {
                   4741:               $hash{'error'}='Bad data';
                   4742:               return (\%hash, $string);
                   4743:           }
                   4744:       } else {
                   4745:           $string =~ s/^(.*?)=//;
1.267     albertel 4746: 	  $key=&unescape($1);
1.265     albertel 4747:       }
                   4748:       $string =~ s/^=//;
                   4749: 
                   4750:       #value
                   4751:       my $value='';
                   4752:       if($string =~ /^__HASH_REF__/) {
                   4753:           ($value, $string)=&str2hashref($string);
                   4754:           if(defined($value->{'error'})) {
                   4755:               $hash{'error'}='Bad data';
                   4756:               return (\%hash, $string);
                   4757:           }
                   4758:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4759:           ($value, $string)=&str2arrayref($string);
                   4760:           if($value->[0] eq 'Array reference error') {
                   4761:               $hash{'error'}='Bad data';
                   4762:               return (\%hash, $string);
                   4763:           }
                   4764:       } else {
                   4765: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4766:       }
                   4767:       $string =~ s/^&//;
                   4768: 
                   4769:       $hash{$key}=$value;
1.204     albertel 4770:   }
1.265     albertel 4771: 
                   4772:   $string =~ s/^__END_HASH_REF__//;
                   4773: 
                   4774:   return (\%hash, $string);
1.204     albertel 4775: }
                   4776: 
                   4777: sub str2array {
1.265     albertel 4778:     my ($string)=@_;
                   4779:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4780:     return @$array;
                   4781: }
                   4782: 
                   4783: sub str2arrayref {
1.204     albertel 4784:   my ($string) = @_;
1.265     albertel 4785:   my @array;
                   4786: 
                   4787:   if($string !~ /^__ARRAY_REF__/) {
                   4788:       if (! ($string eq '' || !defined($string))) {
                   4789: 	  $array[0]='Array reference error';
                   4790:       }
                   4791:       return (\@array, $string);
                   4792:   }
                   4793: 
                   4794:   $string =~ s/^__ARRAY_REF__//;
                   4795: 
                   4796:   while($string !~ /^__END_ARRAY_REF__/) {
                   4797:       my $value='';
                   4798:       if($string =~ /^__HASH_REF__/) {
                   4799:           ($value, $string)=&str2hashref($string);
                   4800:           if(defined($value->{'error'})) {
                   4801:               $array[0] ='Array reference error';
                   4802:               return (\@array, $string);
                   4803:           }
                   4804:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4805:           ($value, $string)=&str2arrayref($string);
                   4806:           if($value->[0] eq 'Array reference error') {
                   4807:               $array[0] ='Array reference error';
                   4808:               return (\@array, $string);
                   4809:           }
                   4810:       } else {
                   4811: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4812:       }
                   4813:       $string =~ s/^&//;
                   4814: 
                   4815:       push(@array, $value);
1.191     harris41 4816:   }
1.265     albertel 4817: 
                   4818:   $string =~ s/^__END_ARRAY_REF__//;
                   4819: 
                   4820:   return (\@array, $string);
1.168     albertel 4821: }
                   4822: 
1.167     albertel 4823: # -------------------------------------------------------------------Temp Store
                   4824: 
1.168     albertel 4825: sub tmpreset {
                   4826:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4827:   if (!$symb) {
                   4828:     $symb=&symbread();
1.620     albertel 4829:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4830:   }
                   4831:   $symb=escape($symb);
                   4832: 
1.620     albertel 4833:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4834:   $namespace=~s/\//\_/g;
                   4835:   $namespace=~s/\W//g;
                   4836: 
1.620     albertel 4837:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4838:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4839:   if ($domain eq 'public' && $stuname eq 'public') {
                   4840:       $stuname=$ENV{'REMOTE_ADDR'};
                   4841:   }
1.1117    foxr     4842:   my $path=LONCAPA::tempdir();
1.168     albertel 4843:   my %hash;
                   4844:   if (tie(%hash,'GDBM_File',
                   4845: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4846: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4847:     foreach my $key (keys(%hash)) {
1.180     albertel 4848:       if ($key=~ /:$symb/) {
1.168     albertel 4849: 	delete($hash{$key});
                   4850:       }
                   4851:     }
                   4852:   }
                   4853: }
                   4854: 
1.167     albertel 4855: sub tmpstore {
1.168     albertel 4856:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4857: 
                   4858:   if (!$symb) {
                   4859:     $symb=&symbread();
1.620     albertel 4860:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4861:   }
                   4862:   $symb=escape($symb);
                   4863: 
                   4864:   if (!$namespace) {
                   4865:     # I don't think we would ever want to store this for a course.
                   4866:     # it seems this will only be used if we don't have a course.
1.620     albertel 4867:     #$namespace=$env{'request.course.id'};
1.168     albertel 4868:     #if (!$namespace) {
1.620     albertel 4869:       $namespace=$env{'request.state'};
1.168     albertel 4870:     #}
                   4871:   }
                   4872:   $namespace=~s/\//\_/g;
                   4873:   $namespace=~s/\W//g;
1.620     albertel 4874:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4875:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4876:   if ($domain eq 'public' && $stuname eq 'public') {
                   4877:       $stuname=$ENV{'REMOTE_ADDR'};
                   4878:   }
1.168     albertel 4879:   my $now=time;
                   4880:   my %hash;
1.1117    foxr     4881:   my $path=LONCAPA::tempdir();
1.168     albertel 4882:   if (tie(%hash,'GDBM_File',
                   4883: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4884: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4885:     $hash{"version:$symb"}++;
                   4886:     my $version=$hash{"version:$symb"};
                   4887:     my $allkeys=''; 
                   4888:     foreach my $key (keys(%$storehash)) {
                   4889:       $allkeys.=$key.':';
1.591     albertel 4890:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4891:     }
                   4892:     $hash{"$version:$symb:timestamp"}=$now;
                   4893:     $allkeys.='timestamp';
                   4894:     $hash{"$version:keys:$symb"}=$allkeys;
                   4895:     if (untie(%hash)) {
                   4896:       return 'ok';
                   4897:     } else {
                   4898:       return "error:$!";
                   4899:     }
                   4900:   } else {
                   4901:     return "error:$!";
                   4902:   }
                   4903: }
1.167     albertel 4904: 
1.168     albertel 4905: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4906: 
1.168     albertel 4907: sub tmprestore {
                   4908:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4909: 
1.168     albertel 4910:   if (!$symb) {
                   4911:     $symb=&symbread();
1.620     albertel 4912:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4913:   }
                   4914:   $symb=escape($symb);
                   4915: 
1.620     albertel 4916:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4917: 
1.620     albertel 4918:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4919:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4920:   if ($domain eq 'public' && $stuname eq 'public') {
                   4921:       $stuname=$ENV{'REMOTE_ADDR'};
                   4922:   }
1.168     albertel 4923:   my %returnhash;
                   4924:   $namespace=~s/\//\_/g;
                   4925:   $namespace=~s/\W//g;
                   4926:   my %hash;
1.1117    foxr     4927:   my $path=LONCAPA::tempdir();
1.168     albertel 4928:   if (tie(%hash,'GDBM_File',
                   4929: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4930: 	  &GDBM_READER(),0640)) {
1.168     albertel 4931:     my $version=$hash{"version:$symb"};
                   4932:     $returnhash{'version'}=$version;
                   4933:     my $scope;
                   4934:     for ($scope=1;$scope<=$version;$scope++) {
                   4935:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4936:       my @keys=split(/:/,$vkeys);
                   4937:       my $key;
                   4938:       $returnhash{"$scope:keys"}=$vkeys;
                   4939:       foreach $key (@keys) {
1.591     albertel 4940: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4941: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4942:       }
                   4943:     }
1.168     albertel 4944:     if (!(untie(%hash))) {
                   4945:       return "error:$!";
                   4946:     }
                   4947:   } else {
                   4948:     return "error:$!";
                   4949:   }
                   4950:   return %returnhash;
1.167     albertel 4951: }
                   4952: 
1.9       www      4953: # ----------------------------------------------------------------------- Store
                   4954: 
                   4955: sub store {
1.124     www      4956:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4957:     my $home='';
                   4958: 
1.168     albertel 4959:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4960: 
1.213     www      4961:     $symb=&symbclean($symb);
1.122     albertel 4962:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4963: 
1.620     albertel 4964:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4965:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4966: 
                   4967:     &devalidate($symb,$stuname,$domain);
1.109     www      4968: 
                   4969:     $symb=escape($symb);
1.187     www      4970:     if (!$namespace) { 
1.620     albertel 4971:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4972:           return ''; 
                   4973:        } 
                   4974:     }
1.620     albertel 4975:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4976: 
                   4977:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4978:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4979: 
1.12      www      4980:     my $namevalue='';
1.800     albertel 4981:     foreach my $key (keys(%$storehash)) {
                   4982:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4983:     }
1.12      www      4984:     $namevalue=~s/\&$//;
1.187     www      4985:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4986:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4987: }
                   4988: 
1.47      www      4989: # -------------------------------------------------------------- Critical Store
                   4990: 
                   4991: sub cstore {
1.124     www      4992:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4993:     my $home='';
                   4994: 
1.168     albertel 4995:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4996: 
1.213     www      4997:     $symb=&symbclean($symb);
1.122     albertel 4998:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4999: 
1.620     albertel 5000:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5001:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5002: 
                   5003:     &devalidate($symb,$stuname,$domain);
1.109     www      5004: 
                   5005:     $symb=escape($symb);
1.187     www      5006:     if (!$namespace) { 
1.620     albertel 5007:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5008:           return ''; 
                   5009:        } 
                   5010:     }
1.620     albertel 5011:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5012: 
                   5013:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5014:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5015: 
1.47      www      5016:     my $namevalue='';
1.800     albertel 5017:     foreach my $key (keys(%$storehash)) {
                   5018:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5019:     }
1.47      www      5020:     $namevalue=~s/\&$//;
1.187     www      5021:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5022:     return critical
                   5023:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      5024: }
                   5025: 
1.9       www      5026: # --------------------------------------------------------------------- Restore
                   5027: 
                   5028: sub restore {
1.124     www      5029:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5030:     my $home='';
                   5031: 
1.168     albertel 5032:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5033: 
1.122     albertel 5034:     if (!$symb) {
1.1172.2.26  raeburn  5035:         return if ($namespace eq 'courserequests');
                   5036:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5037:     } else {
1.1172.2.26  raeburn  5038:         unless ($namespace eq 'courserequests') {
                   5039:             $symb=&escape(&symbclean($symb));
                   5040:         }
1.122     albertel 5041:     }
1.188     www      5042:     if (!$namespace) { 
1.620     albertel 5043:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5044:           return ''; 
                   5045:        } 
                   5046:     }
1.620     albertel 5047:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5048:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5049:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5050:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5051: 
1.12      www      5052:     my %returnhash=();
1.800     albertel 5053:     foreach my $line (split(/\&/,$answer)) {
                   5054: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5055:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5056:     }
1.75      www      5057:     my $version;
                   5058:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5059:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5060:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5061:        }
1.75      www      5062:     }
1.13      www      5063:     return %returnhash;
1.34      www      5064: }
                   5065: 
                   5066: # ---------------------------------------------------------- Course Description
1.1118    foxr     5067: #
                   5068: #  
1.34      www      5069: 
                   5070: sub coursedescription {
1.731     albertel 5071:     my ($courseid,$args)=@_;
1.34      www      5072:     $courseid=~s/^\///;
1.49      www      5073:     $courseid=~s/\_/\//g;
1.34      www      5074:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5075:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5076:     my $normalid=$cdomain.'_'.$cnum;
                   5077:     # need to always cache even if we get errors otherwise we keep 
                   5078:     # trying and trying and trying to get the course description.
                   5079:     my %envhash=();
                   5080:     my %returnhash=();
1.731     albertel 5081:     
                   5082:     my $expiretime=600;
                   5083:     if ($env{'request.course.id'} eq $normalid) {
                   5084: 	$expiretime=120;
                   5085:     }
                   5086: 
                   5087:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5088:     if (!$args->{'freshen_cache'}
                   5089: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5090: 	foreach my $key (keys(%env)) {
                   5091: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5092: 	    my ($setting) = $1;
                   5093: 	    $returnhash{$setting} = $env{$key};
                   5094: 	}
                   5095: 	return %returnhash;
                   5096:     }
                   5097: 
1.1118    foxr     5098:     # get the data again
                   5099: 
1.731     albertel 5100:     if (!$args->{'one_time'}) {
                   5101: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5102:     }
1.811     albertel 5103: 
1.34      www      5104:     if ($chome ne 'no_host') {
1.302     albertel 5105:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5106:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5107: 	   my $username = $env{'user.name'}; # Defult username
                   5108: 	   if(defined $args->{'user'}) {
                   5109: 	       $username = $args->{'user'};
                   5110: 	   }
1.129     albertel 5111:            $returnhash{'home'}= $chome;
                   5112: 	   $returnhash{'domain'} = $cdomain;
                   5113: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5114:            if (!defined($returnhash{'type'})) {
                   5115:                $returnhash{'type'} = 'Course';
                   5116:            }
1.130     albertel 5117:            while (my ($name,$value) = each %returnhash) {
1.53      www      5118:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5119:            }
1.270     www      5120:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5121:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5122: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5123:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5124:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5125:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5126:        }
                   5127:     }
1.731     albertel 5128:     if (!$args->{'one_time'}) {
1.949     raeburn  5129: 	&appenv(\%envhash);
1.731     albertel 5130:     }
1.302     albertel 5131:     return %returnhash;
1.461     www      5132: }
                   5133: 
1.1080    raeburn  5134: sub update_released_required {
                   5135:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5136:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5137:         $cid = $env{'request.course.id'};
                   5138:         $cdom = $env{'course.'.$cid.'.domain'};
                   5139:         $cnum = $env{'course.'.$cid.'.num'};
                   5140:         $chome = $env{'course.'.$cid.'.home'};
                   5141:     }
                   5142:     if ($needsrelease) {
                   5143:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5144:         my $needsupdate;
                   5145:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5146:             $needsupdate = 1;
                   5147:         } else {
                   5148:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5149:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5150:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5151:                 $needsupdate = 1;
                   5152:             }
                   5153:         }
                   5154:         if ($needsupdate) {
                   5155:             my %needshash = (
                   5156:                              'internal.releaserequired' => $needsrelease,
                   5157:                             );
                   5158:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5159:             if ($putresult eq 'ok') {
                   5160:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5161:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5162:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5163:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5164:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5165:                 }
                   5166:             }
                   5167:         }
                   5168:     }
                   5169:     return;
                   5170: }
                   5171: 
1.461     www      5172: # -------------------------------------------------See if a user is privileged
                   5173: 
                   5174: sub privileged {
1.1172.2.23  raeburn  5175:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5176:     my $now = time;
1.1172.2.23  raeburn  5177:     my $roles;
                   5178:     if (ref($possroles) eq 'ARRAY') {
                   5179:         $roles = $possroles;
                   5180:     } else {
                   5181:         $roles = ['dc','su'];
                   5182:     }
                   5183:     if (ref($possdomains) eq 'ARRAY') {
                   5184:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5185:         foreach my $dom (@{$possdomains}) {
                   5186:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5187:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5188:                 foreach my $role (@{$roles}) {
                   5189:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5190:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5191:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5192:                             return 1 unless (($end && $end < $now) ||
                   5193:                                              ($start && $start > $now));
                   5194:                         }
                   5195:                     }
                   5196:                 }
                   5197:             }
                   5198:         }
                   5199:     } else {
                   5200:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5201:         my $now = time;
1.1170    droeschl 5202: 
1.1172.2.58  raeburn  5203:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5204:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  5205:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   5206:                 return 1 unless ($tend && $tend < $now)
                   5207:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5208:             }
1.1172.2.23  raeburn  5209:         }
                   5210:     }
1.461     www      5211:     return 0;
1.9       www      5212: }
1.1       albertel 5213: 
1.1172.2.23  raeburn  5214: sub privileged_by_domain {
                   5215:     my ($domains,$roles) = @_;
                   5216:     my %privileged = ();
                   5217:     my $cachetime = 60*60*24;
                   5218:     my $now = time;
                   5219:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5220:         return %privileged;
                   5221:     }
                   5222:     foreach my $dom (@{$domains}) {
                   5223:         next if (ref($privileged{$dom}) eq 'HASH');
                   5224:         my $needroles;
                   5225:         foreach my $role (@{$roles}) {
                   5226:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5227:             if (defined($cached)) {
                   5228:                 if (ref($result) eq 'HASH') {
                   5229:                     $privileged{$dom}{$role} = $result;
                   5230:                 }
                   5231:             } else {
                   5232:                 $needroles = 1;
                   5233:             }
                   5234:         }
                   5235:         if ($needroles) {
                   5236:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5237:             $privileged{$dom} = {};
                   5238:             foreach my $server (keys(%dompersonnel)) {
                   5239:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5240:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5241:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5242:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5243:                         next if ($end && $end < $now);
                   5244:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   5245:                             $dompersonnel{$server}{$item};
                   5246:                     }
                   5247:                 }
                   5248:             }
                   5249:             if (ref($privileged{$dom}) eq 'HASH') {
                   5250:                 foreach my $role (@{$roles}) {
                   5251:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5252:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5253:                     } else {
                   5254:                         my %hash = ();
                   5255:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5256:                     }
                   5257:                 }
                   5258:             }
                   5259:         }
                   5260:     }
                   5261:     return %privileged;
                   5262: }
                   5263: 
1.103     harris41 5264: # -------------------------------------------------------- Get user privileges
1.11      www      5265: 
                   5266: sub rolesinit {
1.1169    droeschl 5267:     my ($domain, $username) = @_;
                   5268:     my %userroles = ('user.login.time' => time);
                   5269:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5270: 
                   5271:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5272:     # also, blocking can be triggered by an activating timer
                   5273:     # it's saved in the user's %env.
                   5274:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5275:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5276:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5277:         %timerintchk, %timerintenv);
                   5278: 
1.1162    raeburn  5279:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5280:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5281:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5282:     }
1.1169    droeschl 5283: 
1.1162    raeburn  5284:     foreach my $key (keys(%timerinterval)) {
                   5285:         my ($cid,$rest) = split(/\0/,$key);
                   5286:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5287:     }
1.1169    droeschl 5288: 
1.11      www      5289:     my %allroles=();
1.1162    raeburn  5290:     my %allgroups=();
1.11      www      5291: 
1.1172.2.58  raeburn  5292:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5293:         my $role = $rolesdump{$area};
                   5294:         $area =~ s/\_\w\w$//;
                   5295: 
                   5296:         my ($trole, $tend, $tstart, $group_privs);
                   5297: 
                   5298:         if ($role =~ /^cr/) {
                   5299:         # Custom role, defined by a user 
                   5300:         # e.g., user.role.cr/msu/smith/mynewrole
                   5301:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5302:                 $trole = $1;
                   5303:                 ($tend, $tstart) = split('_', $2);
                   5304:             } else {
                   5305:                 $trole = $role;
                   5306:             }
                   5307:         } elsif ($role =~ m|^gr/|) {
                   5308:         # Role of member in a group, defined within a course/community
                   5309:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5310:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5311:             next if $tstart eq '-1';
                   5312:             ($trole, $group_privs) = split(/\//, $trole);
                   5313:             $group_privs = &unescape($group_privs);
                   5314:         } else {
                   5315:         # Just a normal role, defined in roles.tab
                   5316:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5317:         }
                   5318: 
                   5319:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5320:                  $username);
                   5321:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5322: 
                   5323:         # role expired or not available yet?
                   5324:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5325:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5326: 
                   5327:         next if $area eq '' or $trole eq '';
                   5328: 
                   5329:         my $spec = "$trole.$area";
                   5330:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5331: 
                   5332:         if ($trole =~ /^cr\//) {
                   5333:         # Custom role, defined by a user
                   5334:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5335:         } elsif ($trole eq 'gr') {
                   5336:         # Role of a member in a group, defined within a course/community
                   5337:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5338:             next;
                   5339:         } else {
                   5340:         # Normal role, defined in roles.tab
                   5341:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5342:         }
                   5343: 
                   5344:         my $cid = $tdomain.'_'.$trest;
                   5345:         unless ($firstaccchk{$cid}) {
                   5346:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5347:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5348:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5349:                         $coursetimerstarts{$cid}{$item}; 
                   5350:                 }
                   5351:             }
                   5352:             $firstaccchk{$cid} = 1;
                   5353:         }
                   5354:         unless ($timerintchk{$cid}) {
                   5355:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5356:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5357:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5358:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5359:                 }
1.12      www      5360:             }
1.1169    droeschl 5361:             $timerintchk{$cid} = 1;
1.191     harris41 5362:         }
1.11      www      5363:     }
1.1169    droeschl 5364: 
                   5365:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5366:         \%allroles, \%allgroups);
                   5367:     $env{'user.adv'} = $userroles{'user.adv'};
                   5368: 
1.1162    raeburn  5369:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5370: }
                   5371: 
1.567     raeburn  5372: sub set_arearole {
1.1172.2.19  raeburn  5373:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5374:     unless ($nolog) {
1.567     raeburn  5375: # log the associated role with the area
1.1172.2.19  raeburn  5376:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5377:     }
1.743     albertel 5378:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5379: }
                   5380: 
                   5381: sub custom_roleprivs {
                   5382:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5383:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  5384:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5385:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5386:         my ($rdummy,$roledef)=
                   5387:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5388:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5389:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5390:             if (defined($syspriv)) {
1.1043    raeburn  5391:                 if ($trest =~ /^$match_community$/) {
                   5392:                     $syspriv =~ s/bre\&S//; 
                   5393:                 }
1.567     raeburn  5394:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5395:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5396:             }
                   5397:             if ($tdomain ne '') {
                   5398:                 if (defined($dompriv)) {
                   5399:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5400:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5401:                 }
                   5402:                 if (($trest ne '') && (defined($coursepriv))) {
                   5403:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5404:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5405:                 }
                   5406:             }
                   5407:         }
                   5408:     }
                   5409: }
                   5410: 
1.678     raeburn  5411: sub group_roleprivs {
                   5412:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5413:     my $access = 1;
                   5414:     my $now = time;
                   5415:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5416:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5417:     if ($access) {
1.811     albertel 5418:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5419:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5420:     }
                   5421: }
1.567     raeburn  5422: 
                   5423: sub standard_roleprivs {
                   5424:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5425:     if (defined($pr{$trole.':s'})) {
                   5426:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5427:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5428:     }
                   5429:     if ($tdomain ne '') {
                   5430:         if (defined($pr{$trole.':d'})) {
                   5431:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5432:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5433:         }
                   5434:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5435:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5436:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5437:         }
                   5438:     }
                   5439: }
                   5440: 
                   5441: sub set_userprivs {
1.1064    raeburn  5442:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5443:     my $author=0;
                   5444:     my $adv=0;
1.678     raeburn  5445:     my %grouproles = ();
                   5446:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5447:         my @groupkeys; 
1.1000    raeburn  5448:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5449:             push(@groupkeys,$role);
                   5450:         }
                   5451:         if (ref($groups_roles) eq 'HASH') {
                   5452:             foreach my $key (keys(%{$groups_roles})) {
                   5453:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5454:                     push(@groupkeys,$key);
                   5455:                 }
                   5456:             }
                   5457:         }
                   5458:         if (@groupkeys > 0) {
                   5459:             foreach my $role (@groupkeys) {
                   5460:                 my ($trole,$area,$sec,$extendedarea);
                   5461:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5462:                     $trole = $1;
                   5463:                     $area = $2;
                   5464:                     $sec = $3;
                   5465:                     $extendedarea = $area.$sec;
                   5466:                     if (exists($$allgroups{$area})) {
                   5467:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5468:                             my $spec = $trole.'.'.$extendedarea;
                   5469:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5470:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5471:                         }
1.678     raeburn  5472:                     }
                   5473:                 }
                   5474:             }
                   5475:         }
                   5476:     }
1.800     albertel 5477:     foreach my $group (keys(%grouproles)) {
                   5478:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5479:     }
1.800     albertel 5480:     foreach my $role (keys(%{$allroles})) {
                   5481:         my %thesepriv;
1.941     raeburn  5482:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5483:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5484:             if ($item ne '') {
                   5485:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5486:                 if ($restrictions eq '') {
                   5487:                     $thesepriv{$privilege}='F';
                   5488:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5489:                     $thesepriv{$privilege}.=$restrictions;
                   5490:                 }
                   5491:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5492:             }
                   5493:         }
                   5494:         my $thesestr='';
1.1104    raeburn  5495:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5496: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5497: 	}
                   5498:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5499:     }
                   5500:     return ($author,$adv);
                   5501: }
                   5502: 
1.994     raeburn  5503: sub role_status {
1.1104    raeburn  5504:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5505:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  5506:         my ($one,$two) = split(m{\./},$rolekey,2);
                   5507:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  5508:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  5509:             $$where = '/'.$two;
1.994     raeburn  5510:             $$trolecode=$$role.'.'.$$where;
                   5511:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5512:             $$tstatus='is';
1.1104    raeburn  5513:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5514:                 $$tstatus='future';
1.1034    raeburn  5515:                 if ($$tstart<$now) {
                   5516:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5517:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5518:                             my (%allroles,%allgroups,$group_privs,
                   5519:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5520:                             my %userroles = (
                   5521:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5522:                             );
1.1064    raeburn  5523:                             @rolecodes = ('cm'); 
1.1002    raeburn  5524:                             my $spec=$$role.'.'.$$where;
                   5525:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5526:                             if ($$role =~ /^cr\//) {
                   5527:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5528:                                 push(@rolecodes,'cr');
1.1002    raeburn  5529:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5530:                                 push(@rolecodes,$$role);
1.1002    raeburn  5531:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5532:                                                     $env{'user.name'});
1.1064    raeburn  5533:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5534:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5535:                                 $group_privs = &unescape($group_privs);
                   5536:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5537:                                 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  5538:                                 &get_groups_roles($tdomain,$trest,
                   5539:                                                   \%course_roles,\@rolecodes,
                   5540:                                                   \%groups_roles);
1.1002    raeburn  5541:                             } else {
1.1064    raeburn  5542:                                 push(@rolecodes,$$role);
1.1002    raeburn  5543:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5544:                             }
1.1064    raeburn  5545:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5546:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5547:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5548:                         }
                   5549:                     }
1.1034    raeburn  5550:                     $$tstatus = 'is';
1.1002    raeburn  5551:                 }
1.994     raeburn  5552:             }
                   5553:             if ($$tend) {
1.1104    raeburn  5554:                 if ($$tend<$update) {
1.994     raeburn  5555:                     $$tstatus='expired';
                   5556:                 } elsif ($$tend<$now) {
                   5557:                     $$tstatus='will_not';
                   5558:                 }
                   5559:             }
                   5560:         }
                   5561:     }
                   5562: }
                   5563: 
1.1104    raeburn  5564: sub get_groups_roles {
                   5565:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5566:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5567:                   (ref($rolecodes) eq 'ARRAY') && 
                   5568:                   (ref($groups_roles) eq 'HASH')); 
                   5569:     if (keys(%{$cdom_courseroles}) > 0) {
                   5570:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5571:         if ($cdom ne '' && $cnum ne '') {
                   5572:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5573:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5574:                     my $crsrole = $1;
                   5575:                     my $crssec = $2;
                   5576:                     if ($crsrole =~ /^cr/) {
                   5577:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5578:                             push(@{$rolecodes},'cr');
                   5579:                         }
                   5580:                     } else {
                   5581:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5582:                             push(@{$rolecodes},$crsrole);
                   5583:                         }
                   5584:                     }
                   5585:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5586:                     if ($crssec ne '') {
                   5587:                         $rolekey .= "/$crssec";
                   5588:                     }
                   5589:                     $rolekey .= './';
                   5590:                     $groups_roles->{$rolekey} = $rolecodes;
                   5591:                 }
                   5592:             }
                   5593:         }
                   5594:     }
                   5595:     return;
                   5596: }
                   5597: 
                   5598: sub delete_env_groupprivs {
                   5599:     my ($where,$courseroles,$possroles) = @_;
                   5600:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5601:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5602:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5603:         %{$courseroles->{$udom}} =
                   5604:             &get_my_roles('','','userroles',['active'],
                   5605:                           $possroles,[$udom],1);
                   5606:     }
                   5607:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5608:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5609:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5610:             my $area = '/'.$cdom.'/'.$cnum;
                   5611:             my $privkey = "user.priv.$crsrole.$area";
                   5612:             if ($crssec ne '') {
                   5613:                 $privkey .= '/'.$crssec;
                   5614:             }
                   5615:             $privkey .= ".$area/$group";
                   5616:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5617:         }
                   5618:     }
                   5619:     return;
                   5620: }
                   5621: 
1.994     raeburn  5622: sub check_adhoc_privs {
1.1104    raeburn  5623:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5624:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.9  raeburn  5625:     my $setprivs;
1.994     raeburn  5626:     if ($env{$cckey}) {
                   5627:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5628:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5629:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5630:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9  raeburn  5631:             $setprivs = 1;
1.994     raeburn  5632:         }
                   5633:     } else {
1.1088    raeburn  5634:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9  raeburn  5635:         $setprivs = 1;
1.994     raeburn  5636:     }
1.1172.2.9  raeburn  5637:     return $setprivs;
1.994     raeburn  5638: }
                   5639: 
                   5640: sub set_adhoc_privileges {
                   5641: # role can be cc or ca
1.1088    raeburn  5642:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5643:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5644:     my $spec = $role.'.'.$area;
                   5645:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  5646:                                   $env{'user.name'},1);
1.994     raeburn  5647:     my %ccrole = ();
                   5648:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5649:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5650:     &appenv(\%userroles,[$role,'cm']);
                   5651:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5652:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5653:         &appenv( {'request.role'        => $spec,
                   5654:                   'request.role.domain' => $dcdom,
                   5655:                   'request.course.sec'  => ''
                   5656:                  }
                   5657:                );
                   5658:         my $tadv=0;
                   5659:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5660:         &appenv({'request.role.adv'    => $tadv});
                   5661:     }
1.994     raeburn  5662: }
                   5663: 
1.12      www      5664: # --------------------------------------------------------------- get interface
                   5665: 
                   5666: sub get {
1.131     albertel 5667:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5668:    my $items='';
1.800     albertel 5669:    foreach my $item (@$storearr) {
                   5670:        $items.=&escape($item).'&';
1.191     harris41 5671:    }
1.12      www      5672:    $items=~s/\&$//;
1.620     albertel 5673:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5674:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5675:    my $uhome=&homeserver($uname,$udomain);
                   5676: 
1.133     albertel 5677:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5678:    my @pairs=split(/\&/,$rep);
1.273     albertel 5679:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5680:      return @pairs;
                   5681:    }
1.15      www      5682:    my %returnhash=();
1.42      www      5683:    my $i=0;
1.800     albertel 5684:    foreach my $item (@$storearr) {
                   5685:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5686:       $i++;
1.191     harris41 5687:    }
1.15      www      5688:    return %returnhash;
1.27      www      5689: }
                   5690: 
                   5691: # --------------------------------------------------------------- del interface
                   5692: 
                   5693: sub del {
1.133     albertel 5694:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5695:    my $items='';
1.800     albertel 5696:    foreach my $item (@$storearr) {
                   5697:        $items.=&escape($item).'&';
1.191     harris41 5698:    }
1.984     neumanie 5699: 
1.27      www      5700:    $items=~s/\&$//;
1.620     albertel 5701:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5702:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5703:    my $uhome=&homeserver($uname,$udomain);
                   5704:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5705: }
                   5706: 
                   5707: # -------------------------------------------------------------- dump interface
                   5708: 
1.1172.2.22  raeburn  5709: sub unserialize {
                   5710:     my ($rep, $escapedkeys) = @_;
                   5711: 
                   5712:     return {} if $rep =~ /^error/;
                   5713: 
                   5714:     my %returnhash=();
                   5715:     foreach my $item (split(/\&/,$rep)) {
                   5716:         my ($key, $value) = split(/=/, $item, 2);
                   5717:         $key = unescape($key) unless $escapedkeys;
                   5718:         next if $key =~ /^error: 2 /;
                   5719:         $returnhash{$key} = &thaw_unescape($value);
                   5720:     }
                   5721:     return \%returnhash;
                   5722: }
                   5723: 
                   5724: # see Lond::dump_with_regexp
                   5725: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5726: sub dump {
1.1172.2.22  raeburn  5727:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5728:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5729:     if (!$uname) { $uname=$env{'user.name'}; }
                   5730:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5731: 
1.1172.2.55  raeburn  5732:     if ($regexp) {
                   5733:         $regexp=&escape($regexp);
                   5734:     } else {
                   5735:         $regexp='.';
                   5736:     }
1.1172.2.22  raeburn  5737:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   5738:         # user is hosted on this machine
1.1172.2.55  raeburn  5739:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  5740:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  5741:         return %{&unserialize($reply, $escapedkeys)};
                   5742:     }
1.1166    raeburn  5743:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5744:     my @pairs=split(/\&/,$rep);
                   5745:     my %returnhash=();
1.1098    foxr     5746:     if (!($rep =~ /^error/ )) {
                   5747: 	foreach my $item (@pairs) {
                   5748: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  5749:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     5750: 	    next if ($key =~ /^error: 2 /);
                   5751: 	    $returnhash{$key}=&thaw_unescape($value);
                   5752: 	}
1.755     albertel 5753:     }
                   5754:     return %returnhash;
1.407     www      5755: }
                   5756: 
1.1098    foxr     5757: 
1.717     albertel 5758: # --------------------------------------------------------- dumpstore interface
                   5759: 
                   5760: sub dumpstore {
                   5761:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  5762:    # same as dump but keys must be escaped. They may contain colon separated
                   5763:    # lists of values that may themself contain colons (e.g. symbs).
                   5764:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5765: }
                   5766: 
1.407     www      5767: # -------------------------------------------------------------- keys interface
                   5768: 
                   5769: sub getkeys {
                   5770:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5771:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5772:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5773:    my $uhome=&homeserver($uname,$udomain);
                   5774:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5775:    my @keyarray=();
1.800     albertel 5776:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5777:       next if ($key =~ /^error: 2 /);
1.800     albertel 5778:       push(@keyarray,&unescape($key));
1.407     www      5779:    }
                   5780:    return @keyarray;
1.318     matthew  5781: }
                   5782: 
1.319     matthew  5783: # --------------------------------------------------------------- currentdump
                   5784: sub currentdump {
1.328     matthew  5785:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5786:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5787:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5788:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5789:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  5790:    my $rep;
                   5791: 
                   5792:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   5793:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   5794:                    $courseid)));
                   5795:    } else {
                   5796:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   5797:    }
                   5798: 
1.318     matthew  5799:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5800:    #
1.318     matthew  5801:    my %returnhash=();
1.319     matthew  5802:    #
                   5803:    if ($rep eq "unknown_cmd") { 
                   5804:        # an old lond will not know currentdump
                   5805:        # Do a dump and make it look like a currentdump
1.822     albertel 5806:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5807:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5808:        my %hash = @tmp;
                   5809:        @tmp=();
1.424     matthew  5810:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5811:    } else {
                   5812:        my @pairs=split(/\&/,$rep);
1.800     albertel 5813:        foreach my $pair (@pairs) {
                   5814:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5815:            my ($symb,$param) = split(/:/,$key);
                   5816:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5817:                                                         &thaw_unescape($value);
1.319     matthew  5818:        }
1.191     harris41 5819:    }
1.12      www      5820:    return %returnhash;
1.424     matthew  5821: }
                   5822: 
                   5823: sub convert_dump_to_currentdump{
                   5824:     my %hash = %{shift()};
                   5825:     my %returnhash;
                   5826:     # Code ripped from lond, essentially.  The only difference
                   5827:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5828:     # we might run in to problems with parameter names =~ /^v\./
                   5829:     while (my ($key,$value) = each(%hash)) {
                   5830:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5831: 	$symb  = &unescape($symb);
                   5832: 	$param = &unescape($param);
1.424     matthew  5833:         next if ($v eq 'version' || $symb eq 'keys');
                   5834:         next if (exists($returnhash{$symb}) &&
                   5835:                  exists($returnhash{$symb}->{$param}) &&
                   5836:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5837:         $returnhash{$symb}->{$param}=$value;
                   5838:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5839:     }
                   5840:     #
                   5841:     # Remove all of the keys in the hashes which keep track of
                   5842:     # the version of the parameter.
                   5843:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5844:         # use a foreach because we are going to delete from the hash.
                   5845:         foreach my $key (keys(%$param_hash)) {
                   5846:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5847:         }
                   5848:     }
                   5849:     return \%returnhash;
1.12      www      5850: }
                   5851: 
1.627     albertel 5852: # ------------------------------------------------------ critical inc interface
                   5853: 
                   5854: sub cinc {
                   5855:     return &inc(@_,'critical');
                   5856: }
                   5857: 
1.449     matthew  5858: # --------------------------------------------------------------- inc interface
                   5859: 
                   5860: sub inc {
1.627     albertel 5861:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5862:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5863:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5864:     my $uhome=&homeserver($uname,$udomain);
                   5865:     my $items='';
                   5866:     if (! ref($store)) {
                   5867:         # got a single value, so use that instead
                   5868:         $items = &escape($store).'=&';
                   5869:     } elsif (ref($store) eq 'SCALAR') {
                   5870:         $items = &escape($$store).'=&';        
                   5871:     } elsif (ref($store) eq 'ARRAY') {
                   5872:         $items = join('=&',map {&escape($_);} @{$store});
                   5873:     } elsif (ref($store) eq 'HASH') {
                   5874:         while (my($key,$value) = each(%{$store})) {
                   5875:             $items.= &escape($key).'='.&escape($value).'&';
                   5876:         }
                   5877:     }
                   5878:     $items=~s/\&$//;
1.627     albertel 5879:     if ($critical) {
                   5880: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5881:     } else {
                   5882: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5883:     }
1.449     matthew  5884: }
                   5885: 
1.12      www      5886: # --------------------------------------------------------------- put interface
                   5887: 
                   5888: sub put {
1.134     albertel 5889:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5890:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5891:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5892:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5893:    my $items='';
1.800     albertel 5894:    foreach my $item (keys(%$storehash)) {
                   5895:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5896:    }
1.12      www      5897:    $items=~s/\&$//;
1.134     albertel 5898:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5899: }
                   5900: 
1.631     albertel 5901: # ------------------------------------------------------------ newput interface
                   5902: 
                   5903: sub newput {
                   5904:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5905:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5906:    if (!$uname) { $uname=$env{'user.name'}; }
                   5907:    my $uhome=&homeserver($uname,$udomain);
                   5908:    my $items='';
                   5909:    foreach my $key (keys(%$storehash)) {
                   5910:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5911:    }
                   5912:    $items=~s/\&$//;
                   5913:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5914: }
                   5915: 
                   5916: # ---------------------------------------------------------  putstore interface
                   5917: 
1.524     raeburn  5918: sub putstore {
1.1172.2.59  raeburn  5919:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 5920:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5921:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5922:    my $uhome=&homeserver($uname,$udomain);
                   5923:    my $items='';
1.715     albertel 5924:    foreach my $key (keys(%$storehash)) {
                   5925:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5926:    }
1.715     albertel 5927:    $items=~s/\&$//;
1.716     albertel 5928:    my $esc_symb=&escape($symb);
                   5929:    my $esc_v=&escape($version);
1.715     albertel 5930:    my $reply =
1.716     albertel 5931:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5932: 	      $uhome);
1.1172.2.59  raeburn  5933:    if (($tolog) && ($reply eq 'ok')) {
                   5934:        my $namevalue='';
                   5935:        foreach my $key (keys(%{$storehash})) {
                   5936:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   5937:        }
                   5938:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   5939:                      '&host='.&escape($perlvar{'lonHostID'}).
                   5940:                      '&version='.$esc_v.
                   5941:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   5942:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   5943:    }
1.715     albertel 5944:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5945:        # gfall back to way things use to be done
1.715     albertel 5946:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5947: 			    $uname);
1.524     raeburn  5948:    }
1.715     albertel 5949:    return $reply;
                   5950: }
                   5951: 
                   5952: sub old_putstore {
1.716     albertel 5953:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5954:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5955:     if (!$uname) { $uname=$env{'user.name'}; }
                   5956:     my $uhome=&homeserver($uname,$udomain);
                   5957:     my %newstorehash;
1.800     albertel 5958:     foreach my $item (keys(%$storehash)) {
                   5959: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5960: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5961:     }
                   5962:     my $items='';
                   5963:     my %allitems = ();
1.800     albertel 5964:     foreach my $item (keys(%newstorehash)) {
                   5965: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5966: 	    my $key = $1.':keys:'.$2;
                   5967: 	    $allitems{$key} .= $3.':';
                   5968: 	}
1.800     albertel 5969: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5970:     }
1.800     albertel 5971:     foreach my $item (keys(%allitems)) {
                   5972: 	$allitems{$item} =~ s/\:$//;
                   5973: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5974:     }
                   5975:     $items=~s/\&$//;
                   5976:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5977: }
                   5978: 
1.47      www      5979: # ------------------------------------------------------ critical put interface
                   5980: 
                   5981: sub cput {
1.134     albertel 5982:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5983:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5984:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5985:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5986:    my $items='';
1.800     albertel 5987:    foreach my $item (keys(%$storehash)) {
                   5988:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5989:    }
1.47      www      5990:    $items=~s/\&$//;
1.134     albertel 5991:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5992: }
                   5993: 
                   5994: # -------------------------------------------------------------- eget interface
                   5995: 
                   5996: sub eget {
1.133     albertel 5997:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5998:    my $items='';
1.800     albertel 5999:    foreach my $item (@$storearr) {
                   6000:        $items.=&escape($item).'&';
1.191     harris41 6001:    }
1.12      www      6002:    $items=~s/\&$//;
1.620     albertel 6003:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6004:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6005:    my $uhome=&homeserver($uname,$udomain);
                   6006:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6007:    my @pairs=split(/\&/,$rep);
                   6008:    my %returnhash=();
1.42      www      6009:    my $i=0;
1.800     albertel 6010:    foreach my $item (@$storearr) {
                   6011:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6012:       $i++;
1.191     harris41 6013:    }
1.12      www      6014:    return %returnhash;
                   6015: }
                   6016: 
1.667     albertel 6017: # ------------------------------------------------------------ tmpput interface
                   6018: sub tmpput {
1.802     raeburn  6019:     my ($storehash,$server,$context)=@_;
1.667     albertel 6020:     my $items='';
1.800     albertel 6021:     foreach my $item (keys(%$storehash)) {
                   6022: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6023:     }
                   6024:     $items=~s/\&$//;
1.802     raeburn  6025:     if (defined($context)) {
                   6026:         $items .= ':'.&escape($context);
                   6027:     }
1.667     albertel 6028:     return &reply("tmpput:$items",$server);
                   6029: }
                   6030: 
                   6031: # ------------------------------------------------------------ tmpget interface
                   6032: sub tmpget {
1.688     albertel 6033:     my ($token,$server)=@_;
                   6034:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6035:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6036:     my %returnhash;
                   6037:     foreach my $item (split(/\&/,$rep)) {
                   6038: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  6039:         next if ($key =~ /^error: 2 /);
1.667     albertel 6040: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6041:     }
                   6042:     return %returnhash;
                   6043: }
                   6044: 
1.1113    raeburn  6045: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6046: sub tmpdel {
                   6047:     my ($token,$server)=@_;
                   6048:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6049:     return &reply("tmpdel:$token",$server);
                   6050: }
                   6051: 
1.1172.2.13  raeburn  6052: # ------------------------------------------------------------ get_timebased_id
                   6053: 
                   6054: sub get_timebased_id {
                   6055:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6056:         $maxtries) = @_;
                   6057:     my ($newid,$error,$dellock);
                   6058:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   6059:         return ('','ok','invalid call to get suffix');
                   6060:     }
                   6061: 
                   6062: # set defaults for any optional args for which values were not supplied
                   6063:     if ($who eq '') {
                   6064:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6065:     }
                   6066:     if (!$locktries) {
                   6067:         $locktries = 3;
                   6068:     }
                   6069:     if (!$maxtries) {
                   6070:         $maxtries = 10;
                   6071:     }
                   6072: 
                   6073:     if (($cdom eq '') || ($cnum eq '')) {
                   6074:         if ($env{'request.course.id'}) {
                   6075:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6076:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6077:         }
                   6078:         if (($cdom eq '') || ($cnum eq '')) {
                   6079:             return ('','ok','call to get suffix not in course context');
                   6080:         }
                   6081:     }
                   6082: 
                   6083: # construct locking item
                   6084:     my $lockhash = {
                   6085:                       $prefix."\0".'locked_'.$keyid => $who,
                   6086:                    };
                   6087:     my $tries = 0;
                   6088: 
                   6089: # attempt to get lock on nohist_$namespace file
                   6090:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6091:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6092:         $tries ++;
                   6093:         sleep 1;
                   6094:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6095:     }
                   6096: 
                   6097: # attempt to get unique identifier, based on current timestamp
                   6098:     if ($gotlock eq 'ok') {
                   6099:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6100:         my $id = time;
                   6101:         $newid = $id;
1.1172.2.56  raeburn  6102:         if ($idtype eq 'addcode') {
                   6103:             $newid .= &sixnum_code();
                   6104:         }
1.1172.2.13  raeburn  6105:         my $idtries = 0;
                   6106:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6107:             if ($idtype eq 'concat') {
                   6108:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  6109:             } elsif ($idtype eq 'addcode') {
                   6110:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  6111:             } else {
                   6112:                 $newid ++;
                   6113:             }
                   6114:             $idtries ++;
                   6115:         }
                   6116:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6117:             my %new_item =  (
                   6118:                               $prefix."\0".$newid => $who,
                   6119:                             );
                   6120:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6121:                                                  $cdom,$cnum);
                   6122:             if ($putresult ne 'ok') {
                   6123:                 undef($newid);
                   6124:                 $error = 'error saving new item: '.$putresult;
                   6125:             }
                   6126:         } else {
1.1172.2.56  raeburn  6127:              undef($newid);
1.1172.2.13  raeburn  6128:              $error = ('error: no unique suffix available for the new item ');
                   6129:         }
                   6130: #  remove lock
                   6131:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6132:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6133:     } else {
                   6134:         $error = "error: could not obtain lockfile\n";
                   6135:         $dellock = 'ok';
1.1172.2.58  raeburn  6136:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6137:             $dellock = 'nolock';
                   6138:         }
1.1172.2.13  raeburn  6139:     }
                   6140:     return ($newid,$dellock,$error);
                   6141: }
                   6142: 
1.1172.2.56  raeburn  6143: sub sixnum_code {
                   6144:     my $code;
                   6145:     for (0..6) {
                   6146:         $code .= int( rand(9) );
                   6147:     }
                   6148:     return $code;
                   6149: }
                   6150: 
1.765     albertel 6151: # -------------------------------------------------- portfolio access checking
                   6152: 
                   6153: sub portfolio_access {
1.766     albertel 6154:     my ($requrl) = @_;
1.765     albertel 6155:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   6156:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  6157:     if ($result) {
                   6158:         my %setters;
                   6159:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6160:             my ($startblock,$endblock) =
                   6161:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6162:             if ($startblock && $endblock) {
                   6163:                 return 'B';
                   6164:             }
                   6165:         } else {
                   6166:             my ($startblock,$endblock) =
                   6167:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6168:             if ($startblock && $endblock) {
                   6169:                 return 'B';
                   6170:             }
                   6171:         }
                   6172:     }
1.765     albertel 6173:     if ($result eq 'ok') {
1.766     albertel 6174:        return 'F';
1.765     albertel 6175:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6176:        return 'A';
1.765     albertel 6177:     }
1.766     albertel 6178:     return '';
1.765     albertel 6179: }
                   6180: 
                   6181: sub get_portfolio_access {
1.767     albertel 6182:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   6183: 
                   6184:     if (!ref($access_hash)) {
                   6185: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6186: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6187: 						   $file_name);
                   6188: 	$access_hash = $access_controls{$file_name};
                   6189:     }
                   6190: 
1.765     albertel 6191:     my ($public,$guest,@domains,@users,@courses,@groups);
                   6192:     my $now = time;
                   6193:     if (ref($access_hash) eq 'HASH') {
                   6194:         foreach my $key (keys(%{$access_hash})) {
                   6195:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6196:             if ($start > $now) {
                   6197:                 next;
                   6198:             }
                   6199:             if ($end && $end<$now) {
                   6200:                 next;
                   6201:             }
                   6202:             if ($scope eq 'public') {
                   6203:                 $public = $key;
                   6204:                 last;
                   6205:             } elsif ($scope eq 'guest') {
                   6206:                 $guest = $key;
                   6207:             } elsif ($scope eq 'domains') {
                   6208:                 push(@domains,$key);
                   6209:             } elsif ($scope eq 'users') {
                   6210:                 push(@users,$key);
                   6211:             } elsif ($scope eq 'course') {
                   6212:                 push(@courses,$key);
                   6213:             } elsif ($scope eq 'group') {
                   6214:                 push(@groups,$key);
                   6215:             }
                   6216:         }
                   6217:         if ($public) {
                   6218:             return 'ok';
                   6219:         }
                   6220:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6221:             if ($guest) {
                   6222:                 return $guest;
                   6223:             }
                   6224:         } else {
                   6225:             if (@domains > 0) {
                   6226:                 foreach my $domkey (@domains) {
                   6227:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6228:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6229:                             return 'ok';
                   6230:                         }
                   6231:                     }
                   6232:                 }
                   6233:             }
                   6234:             if (@users > 0) {
                   6235:                 foreach my $userkey (@users) {
1.865     raeburn  6236:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6237:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6238:                             if (ref($item) eq 'HASH') {
                   6239:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6240:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6241:                                     return 'ok';
                   6242:                                 }
                   6243:                             }
                   6244:                         }
                   6245:                     } 
1.765     albertel 6246:                 }
                   6247:             }
                   6248:             my %roleshash;
                   6249:             my @courses_and_groups = @courses;
                   6250:             push(@courses_and_groups,@groups); 
                   6251:             if (@courses_and_groups > 0) {
                   6252:                 my (%allgroups,%allroles); 
                   6253:                 my ($start,$end,$role,$sec,$group);
                   6254:                 foreach my $envkey (%env) {
1.1060    raeburn  6255:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6256:                         my $cid = $2.'_'.$3; 
                   6257:                         if ($1 eq 'gr') {
                   6258:                             $group = $4;
                   6259:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6260:                         } else {
                   6261:                             if ($4 eq '') {
                   6262:                                 $sec = 'none';
                   6263:                             } else {
                   6264:                                 $sec = $4;
                   6265:                             }
                   6266:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6267:                         }
1.811     albertel 6268:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6269:                         my $cid = $2.'_'.$3;
                   6270:                         if ($4 eq '') {
                   6271:                             $sec = 'none';
                   6272:                         } else {
                   6273:                             $sec = $4;
                   6274:                         }
                   6275:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6276:                     }
                   6277:                 }
                   6278:                 if (keys(%allroles) == 0) {
                   6279:                     return;
                   6280:                 }
                   6281:                 foreach my $key (@courses_and_groups) {
                   6282:                     my %content = %{$$access_hash{$key}};
                   6283:                     my $cnum = $content{'number'};
                   6284:                     my $cdom = $content{'domain'};
                   6285:                     my $cid = $cdom.'_'.$cnum;
                   6286:                     if (!exists($allroles{$cid})) {
                   6287:                         next;
                   6288:                     }    
                   6289:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6290:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6291:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6292:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6293:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6294:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6295:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6296:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6297:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6298:                                         if (grep/^all$/,@sections) {
                   6299:                                             return 'ok';
                   6300:                                         } else {
                   6301:                                             if (grep/^$sec$/,@sections) {
                   6302:                                                 return 'ok';
                   6303:                                             }
                   6304:                                         }
                   6305:                                     }
                   6306:                                 }
                   6307:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6308:                                     if (grep/^none$/,@groups) {
                   6309:                                         return 'ok';
                   6310:                                     }
                   6311:                                 } else {
                   6312:                                     if (grep/^all$/,@groups) {
                   6313:                                         return 'ok';
                   6314:                                     } 
                   6315:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6316:                                         if (grep/^$group$/,@groups) {
                   6317:                                             return 'ok';
                   6318:                                         }
                   6319:                                     }
                   6320:                                 } 
                   6321:                             }
                   6322:                         }
                   6323:                     }
                   6324:                 }
                   6325:             }
                   6326:             if ($guest) {
                   6327:                 return $guest;
                   6328:             }
                   6329:         }
                   6330:     }
                   6331:     return;
                   6332: }
                   6333: 
                   6334: sub course_group_datechecker {
                   6335:     my ($dates,$now,$status) = @_;
                   6336:     my ($start,$end) = split(/\./,$dates);
                   6337:     if (!$start && !$end) {
                   6338:         return 'ok';
                   6339:     }
                   6340:     if (grep/^active$/,@{$status}) {
                   6341:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6342:             return 'ok';
                   6343:         }
                   6344:     }
                   6345:     if (grep/^previous$/,@{$status}) {
                   6346:         if ($end > $now ) {
                   6347:             return 'ok';
                   6348:         }
                   6349:     }
                   6350:     if (grep/^future$/,@{$status}) {
                   6351:         if ($start > $now) {
                   6352:             return 'ok';
                   6353:         }
                   6354:     }
                   6355:     return; 
                   6356: }
                   6357: 
                   6358: sub parse_portfolio_url {
                   6359:     my ($url) = @_;
                   6360: 
                   6361:     my ($type,$udom,$unum,$group,$file_name);
                   6362:     
1.823     albertel 6363:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6364: 	$type = 1;
                   6365:         $udom = $1;
                   6366:         $unum = $2;
                   6367:         $file_name = $3;
1.823     albertel 6368:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6369: 	$type = 2;
                   6370:         $udom = $1;
                   6371:         $unum = $2;
                   6372:         $group = $3;
                   6373:         $file_name = $3.'/'.$4;
                   6374:     }
                   6375:     if (wantarray) {
                   6376: 	return ($type,$udom,$unum,$file_name,$group);
                   6377:     }
                   6378:     return $type;
                   6379: }
                   6380: 
                   6381: sub is_portfolio_url {
                   6382:     my ($url) = @_;
                   6383:     return scalar(&parse_portfolio_url($url));
                   6384: }
                   6385: 
1.798     raeburn  6386: sub is_portfolio_file {
                   6387:     my ($file) = @_;
1.820     raeburn  6388:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6389:         return 1;
                   6390:     }
                   6391:     return;
                   6392: }
                   6393: 
1.976     raeburn  6394: sub usertools_access {
1.1084    raeburn  6395:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6396:     my ($access,%tools);
                   6397:     if ($context eq '') {
                   6398:         $context = 'tools';
                   6399:     }
                   6400:     if ($context eq 'requestcourses') {
                   6401:         %tools = (
                   6402:                       official   => 1,
                   6403:                       unofficial => 1,
1.1006    raeburn  6404:                       community  => 1,
1.1172.2.37  raeburn  6405:                       textbook   => 1,
1.985     raeburn  6406:                  );
1.1172.2.9  raeburn  6407:     } elsif ($context eq 'requestauthor') {
                   6408:         %tools = (
                   6409:                       requestauthor => 1,
                   6410:                  );
1.985     raeburn  6411:     } else {
                   6412:         %tools = (
                   6413:                       aboutme   => 1,
                   6414:                       blog      => 1,
1.1172.2.6  raeburn  6415:                       webdav    => 1,
1.985     raeburn  6416:                       portfolio => 1,
                   6417:                  );
                   6418:     }
1.976     raeburn  6419:     return if (!defined($tools{$tool}));
                   6420: 
1.1172.2.35  raeburn  6421:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6422:         $udom = $env{'user.domain'};
                   6423:         $uname = $env{'user.name'};
                   6424:     }
                   6425: 
1.978     raeburn  6426:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6427:         if ($action ne 'reload') {
1.985     raeburn  6428:             if ($context eq 'requestcourses') {
                   6429:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  6430:             } elsif ($context eq 'requestauthor') {
                   6431:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6432:             } else {
                   6433:                 return $env{'environment.availabletools.'.$tool};
                   6434:             }
                   6435:         }
1.976     raeburn  6436:     }
                   6437: 
1.1172.2.9  raeburn  6438:     my ($toolstatus,$inststatus,$envkey);
                   6439:     if ($context eq 'requestauthor') {
                   6440:         $envkey = $context;
                   6441:     } else {
                   6442:         $envkey = $context.'.'.$tool;
                   6443:     }
1.976     raeburn  6444: 
1.985     raeburn  6445:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6446:          ($action ne 'reload')) {
1.1172.2.9  raeburn  6447:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6448:         $inststatus = $env{'environment.inststatus'};
                   6449:     } else {
1.1084    raeburn  6450:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  6451:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6452:             $inststatus = $userenvref->{'inststatus'};
                   6453:         } else {
1.1172.2.9  raeburn  6454:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6455:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6456:             $inststatus = $userenv{'inststatus'};
                   6457:         }
1.976     raeburn  6458:     }
                   6459: 
                   6460:     if ($toolstatus ne '') {
                   6461:         if ($toolstatus) {
                   6462:             $access = 1;
                   6463:         } else {
                   6464:             $access = 0;
                   6465:         }
                   6466:         return $access;
                   6467:     }
                   6468: 
1.1084    raeburn  6469:     my ($is_adv,%domdef);
                   6470:     if (ref($is_advref) eq 'HASH') {
                   6471:         $is_adv = $is_advref->{'is_adv'};
                   6472:     } else {
                   6473:         $is_adv = &is_advanced_user($udom,$uname);
                   6474:     }
                   6475:     if (ref($domdefref) eq 'HASH') {
                   6476:         %domdef = %{$domdefref};
                   6477:     } else {
                   6478:         %domdef = &get_domain_defaults($udom);
                   6479:     }
1.976     raeburn  6480:     if (ref($domdef{$tool}) eq 'HASH') {
                   6481:         if ($is_adv) {
                   6482:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6483:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6484:                     $access = 1;
                   6485:                 } else {
                   6486:                     $access = 0;
                   6487:                 }
                   6488:                 return $access;
                   6489:             }
                   6490:         }
                   6491:         if ($inststatus ne '') {
                   6492:             my ($hasaccess,$hasnoaccess);
                   6493:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6494:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6495:                     if ($domdef{$tool}{$affiliation}) {
                   6496:                         $hasaccess = 1;
                   6497:                     } else {
                   6498:                         $hasnoaccess = 1;
                   6499:                     }
                   6500:                 }
                   6501:             }
                   6502:             if ($hasaccess || $hasnoaccess) {
                   6503:                 if ($hasaccess) {
                   6504:                     $access = 1;
                   6505:                 } elsif ($hasnoaccess) {
                   6506:                     $access = 0; 
                   6507:                 }
                   6508:                 return $access;
                   6509:             }
                   6510:         } else {
                   6511:             if ($domdef{$tool}{'default'} ne '') {
                   6512:                 if ($domdef{$tool}{'default'}) {
                   6513:                     $access = 1;
                   6514:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6515:                     $access = 0;
                   6516:                 }
                   6517:                 return $access;
                   6518:             }
                   6519:         }
                   6520:     } else {
1.1172.2.6  raeburn  6521:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6522:             $access = 1;
                   6523:         } else {
                   6524:             $access = 0;
                   6525:         }
1.976     raeburn  6526:         return $access;
                   6527:     }
                   6528: }
                   6529: 
1.1050    raeburn  6530: sub is_course_owner {
                   6531:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6532:     if (($udom eq '') || ($uname eq '')) {
                   6533:         $udom = $env{'user.domain'};
                   6534:         $uname = $env{'user.name'};
                   6535:     }
                   6536:     unless (($udom eq '') || ($uname eq '')) {
                   6537:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6538:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6539:                 return 1;
                   6540:             } else {
                   6541:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6542:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6543:                     return 1;
                   6544:                 }
                   6545:             }
                   6546:         }
                   6547:     }
                   6548:     return;
                   6549: }
                   6550: 
1.976     raeburn  6551: sub is_advanced_user {
                   6552:     my ($udom,$uname) = @_;
1.1085    raeburn  6553:     if ($udom ne '' && $uname ne '') {
                   6554:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6555:             if (wantarray) {
                   6556:                 return ($env{'user.adv'},$env{'user.author'});
                   6557:             } else {
                   6558:                 return $env{'user.adv'};
                   6559:             }
1.1085    raeburn  6560:         }
                   6561:     }
1.976     raeburn  6562:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6563:     my %allroles;
1.1128    raeburn  6564:     my ($is_adv,$is_author);
1.976     raeburn  6565:     foreach my $role (keys(%roleshash)) {
                   6566:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6567:         my $area = '/'.$tdomain.'/'.$trest;
                   6568:         if ($sec ne '') {
                   6569:             $area .= '/'.$sec;
                   6570:         }
                   6571:         if (($area ne '') && ($trole ne '')) {
                   6572:             my $spec=$trole.'.'.$area;
                   6573:             if ($trole =~ /^cr\//) {
                   6574:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6575:             } elsif ($trole ne 'gr') {
                   6576:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6577:             }
1.1128    raeburn  6578:             if ($trole eq 'au') {
                   6579:                 $is_author = 1;
                   6580:             }
1.976     raeburn  6581:         }
                   6582:     }
                   6583:     foreach my $role (keys(%allroles)) {
                   6584:         last if ($is_adv);
                   6585:         foreach my $item (split(/:/,$allroles{$role})) {
                   6586:             if ($item ne '') {
                   6587:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6588:                 if ($privilege eq 'adv') {
                   6589:                     $is_adv = 1;
                   6590:                     last;
                   6591:                 }
                   6592:             }
                   6593:         }
                   6594:     }
1.1128    raeburn  6595:     if (wantarray) {
                   6596:         return ($is_adv,$is_author);
                   6597:     }
1.976     raeburn  6598:     return $is_adv;
                   6599: }
1.798     raeburn  6600: 
1.1035    raeburn  6601: sub check_can_request {
1.1036    raeburn  6602:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6603:     my $canreq = 0;
                   6604:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6605:     my @options = ('approval','validate','autolimit');
                   6606:     my $optregex = join('|',@options);
                   6607:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6608:         foreach my $type (@{$types}) {
                   6609:             if (&usertools_access($env{'user.name'},
                   6610:                                   $env{'user.domain'},
                   6611:                                   $type,undef,'requestcourses')) {
                   6612:                 $canreq ++;
1.1036    raeburn  6613:                 if (ref($request_domains) eq 'HASH') {
                   6614:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6615:                 }
1.1035    raeburn  6616:                 if ($dom eq $env{'user.domain'}) {
                   6617:                     $can_request->{$type} = 1;
                   6618:                 }
                   6619:             }
                   6620:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6621:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6622:                 if (@curr > 0) {
1.1036    raeburn  6623:                     foreach my $item (@curr) {
                   6624:                         if (ref($request_domains) eq 'HASH') {
                   6625:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6626:                             if ($otherdom ne '') {
                   6627:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6628:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6629:                                         push(@{$request_domains->{$type}},$otherdom);
                   6630:                                     }
                   6631:                                 } else {
                   6632:                                     push(@{$request_domains->{$type}},$otherdom);
                   6633:                                 }
                   6634:                             }
                   6635:                         }
                   6636:                     }
                   6637:                     unless($dom eq $env{'user.domain'}) {
                   6638:                         $canreq ++;
1.1035    raeburn  6639:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6640:                             $can_request->{$type} = 1;
                   6641:                         }
                   6642:                     }
                   6643:                 }
                   6644:             }
                   6645:         }
                   6646:     }
                   6647:     return $canreq;
                   6648: }
                   6649: 
1.341     www      6650: # ---------------------------------------------- Custom access rule evaluation
                   6651: 
                   6652: sub customaccess {
                   6653:     my ($priv,$uri)=@_;
1.807     albertel 6654:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6655:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6656:     $udom = &LONCAPA::clean_domain($udom);
                   6657:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6658:     my $access=0;
1.800     albertel 6659:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6660: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6661: 	if ($type eq 'user') {
                   6662: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6663: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6664: 		if ($tdom) {
                   6665: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6666: 		}
1.896     albertel 6667: 		if ($tuname) {
                   6668: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6669: 		}
                   6670: 		$access=($effect eq 'allow');
                   6671: 		last;
                   6672: 	    }
                   6673: 	} else {
                   6674: 	    if ($role) {
                   6675: 		if ($role ne $urole) { next; }
                   6676: 	    }
                   6677: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6678: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6679: 		if ($tdom) {
                   6680: 		    if ($tdom ne $udom) { next; }
                   6681: 		}
                   6682: 		if ($tcrs) {
                   6683: 		    if ($tcrs ne $ucrs) { next; }
                   6684: 		}
                   6685: 		if ($tsec) {
                   6686: 		    if ($tsec ne $usec) { next; }
                   6687: 		}
                   6688: 		$access=($effect eq 'allow');
                   6689: 		last;
                   6690: 	    }
                   6691: 	    if ($realm eq '' && $role eq '') {
                   6692: 		$access=($effect eq 'allow');
                   6693: 	    }
1.402     bowersj2 6694: 	}
1.341     www      6695:     }
                   6696:     return $access;
                   6697: }
                   6698: 
1.103     harris41 6699: # ------------------------------------------------- Check for a user privilege
1.12      www      6700: 
                   6701: sub allowed {
1.810     raeburn  6702:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 6703:     my $ver_orguri=$uri;
1.439     www      6704:     $uri=&deversion($uri);
1.152     www      6705:     my $orguri=$uri;
1.52      www      6706:     $uri=&declutter($uri);
1.809     raeburn  6707: 
1.810     raeburn  6708:     if ($priv eq 'evb') {
                   6709: # Evade communication block restrictions for specified role in a course
                   6710:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6711:             return $1;
                   6712:         } else {
                   6713:             return;
                   6714:         }
                   6715:     }
                   6716: 
1.620     albertel 6717:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6718: # Free bre access to adm and meta resources
1.775     albertel 6719:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6720: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6721: 	&& ($priv eq 'bre')) {
1.14      www      6722: 	return 'F';
1.159     www      6723:     }
                   6724: 
1.545     banghart 6725: # Free bre access to user's own portfolio contents
1.714     raeburn  6726:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6727:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6728: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6729:         my %setters;
                   6730:         my ($startblock,$endblock) = 
                   6731:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6732:         if ($startblock && $endblock) {
                   6733:             return 'B';
                   6734:         } else {
                   6735:             return 'F';
                   6736:         }
1.545     banghart 6737:     }
                   6738: 
1.762     raeburn  6739: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6740:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6741:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6742:         if (exists($env{'request.course.id'})) {
                   6743:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6744:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6745:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6746:                 my $courseprivid=$env{'request.course.id'};
                   6747:                 $courseprivid=~s/\_/\//;
                   6748:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6749:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6750:                     return $1; 
1.762     raeburn  6751:                 } else {
                   6752:                     if ($env{'request.course.sec'}) {
                   6753:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6754:                     }
                   6755:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6756:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6757:                         return $2;
                   6758:                     }
1.714     raeburn  6759:                 }
                   6760:             }
                   6761:         }
                   6762:     }
                   6763: 
1.159     www      6764: # Free bre to public access
                   6765: 
                   6766:     if ($priv eq 'bre') {
1.238     www      6767:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6768: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6769:            return 'F'; 
                   6770:         }
1.238     www      6771:         if ($copyright eq 'priv') {
                   6772:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6773: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6774: 		return '';
                   6775:             }
                   6776:         }
                   6777:         if ($copyright eq 'domain') {
                   6778:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6779: 	    unless (($env{'user.domain'} eq $1) ||
                   6780:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6781: 		return '';
                   6782:             }
1.262     matthew  6783:         }
1.620     albertel 6784:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6785:             # Library role, so allow browsing of resources in this domain.
                   6786:             return 'F';
1.238     www      6787:         }
1.341     www      6788:         if ($copyright eq 'custom') {
                   6789: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6790:         }
1.14      www      6791:     }
1.264     matthew  6792:     # Domain coordinator is trying to create a course
1.620     albertel 6793:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6794:         # uri is the requested domain in this case.
                   6795:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6796:         # a role of dc for the domain in question.
1.620     albertel 6797:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6798:     }
1.29      www      6799: 
1.52      www      6800:     my $thisallowed='';
                   6801:     my $statecond=0;
                   6802:     my $courseprivid='';
                   6803: 
1.1039    raeburn  6804:     my $ownaccess;
1.1043    raeburn  6805:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6806:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6807:         if ($uri eq '') {
                   6808:             $ownaccess = 1;
                   6809:         } else {
                   6810:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6811:                 my $udom = $env{'user.domain'};
                   6812:                 my $uname = $env{'user.name'};
                   6813:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6814:                     $ownaccess = 1;
1.1040    raeburn  6815:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6816:                     unless ($uri =~ m{\.\./}) {
                   6817:                         $ownaccess = 1;
                   6818:                     }
                   6819:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6820:                     my $now = time;
                   6821:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6822:                         my $adom = $1;
                   6823:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6824:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6825:                                 my ($start,$end) = split('.',$env{$key});
                   6826:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6827:                                     $ownaccess = 1;
                   6828:                                     last;
                   6829:                                 }
                   6830:                             }
                   6831:                         }
                   6832:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6833:                         my $adom = $1;
                   6834:                         my $aname = $2;
1.1042    raeburn  6835:                         foreach my $role ('ca','aa') { 
                   6836:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6837:                                 my ($start,$end) =
                   6838:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6839:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6840:                                     $ownaccess = 1;
                   6841:                                     last;
                   6842:                                 }
1.1039    raeburn  6843:                             }
                   6844:                         }
                   6845:                     }
                   6846:                 }
                   6847:             }
                   6848:         }
                   6849:     }
                   6850: 
1.52      www      6851: # Course
                   6852: 
1.620     albertel 6853:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6854:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6855:             $thisallowed.=$1;
                   6856:         }
1.52      www      6857:     }
1.29      www      6858: 
1.52      www      6859: # Domain
                   6860: 
1.620     albertel 6861:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6862:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6863:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6864:             $thisallowed.=$1;
                   6865:         }
1.12      www      6866:     }
1.52      www      6867: 
1.1141    raeburn  6868: # User who is not author or co-author might still be able to edit
                   6869: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6870:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6871:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6872:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6873:             $thisallowed.=$1;
                   6874:         }
                   6875:     }
                   6876: 
1.52      www      6877: # Course: uri itself is a course
1.66      www      6878:     my $courseuri=$uri;
                   6879:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6880:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6881: 
1.620     albertel 6882:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6883:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6884:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6885:             $thisallowed.=$1;
                   6886:         }
1.12      www      6887:     }
1.29      www      6888: 
1.665     albertel 6889: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6890: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6891:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6892: 	$thisallowed='';
1.671     raeburn  6893:         my ($match)=&is_on_map($uri);
                   6894:         if ($match) {
                   6895:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6896:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6897:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6898:                 if (@blockers > 0) {
                   6899:                     $thisallowed = 'B';
                   6900:                 } else {
                   6901:                     $thisallowed.=$1;
                   6902:                 }
1.671     raeburn  6903:             }
                   6904:         } else {
1.705     albertel 6905:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6906:             if ($refuri) {
                   6907:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6908:                     $thisallowed='F';
1.671     raeburn  6909:                 } else {
                   6910:                     $refuri=&declutter($refuri);
                   6911:                     my ($match) = &is_on_map($refuri);
                   6912:                     if ($match) {
1.1162    raeburn  6913:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6914:                         if (@blockers > 0) {
                   6915:                             $thisallowed = 'B';
                   6916:                         } else {
                   6917:                             $thisallowed='F';
                   6918:                         }
1.671     raeburn  6919:                     }
1.669     raeburn  6920:                 }
1.671     raeburn  6921:             }
                   6922:         }
1.314     www      6923:     }
1.492     albertel 6924: 
1.766     albertel 6925:     if ($priv eq 'bre'
                   6926: 	&& $thisallowed ne 'F' 
                   6927: 	&& $thisallowed ne '2'
                   6928: 	&& &is_portfolio_url($uri)) {
                   6929: 	$thisallowed = &portfolio_access($uri);
                   6930:     }
                   6931:     
1.52      www      6932: # Full access at system, domain or course-wide level? Exit.
1.29      www      6933:     if ($thisallowed=~/F/) {
                   6934: 	return 'F';
                   6935:     }
                   6936: 
1.52      www      6937: # If this is generating or modifying users, exit with special codes
1.29      www      6938: 
1.643     www      6939:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6940: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6941: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6942: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6943: 	    unless ($auname) { return $thisallowed; }
                   6944: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6945: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6946: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6947: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6948: 	}
1.52      www      6949: 	return $thisallowed;
                   6950:     }
                   6951: #
1.103     harris41 6952: # Gathered so far: system, domain and course wide privileges
1.52      www      6953: #
                   6954: # Course: See if uri or referer is an individual resource that is part of 
                   6955: # the course
                   6956: 
1.620     albertel 6957:     if ($env{'request.course.id'}) {
1.232     www      6958: 
1.620     albertel 6959:        $courseprivid=$env{'request.course.id'};
                   6960:        if ($env{'request.course.sec'}) {
                   6961:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6962:        }
                   6963:        $courseprivid=~s/\_/\//;
                   6964:        my $checkreferer=1;
1.232     www      6965:        my ($match,$cond)=&is_on_map($uri);
                   6966:        if ($match) {
                   6967:            $statecond=$cond;
1.620     albertel 6968:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6969:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6970:                my $value = $1;
                   6971:                if ($priv eq 'bre') {
                   6972:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6973:                    if (@blockers > 0) {
                   6974:                        $thisallowed = 'B';
                   6975:                    } else {
                   6976:                        $thisallowed.=$value;
                   6977:                    }
                   6978:                } else {
                   6979:                    $thisallowed.=$value;
                   6980:                }
1.52      www      6981:                $checkreferer=0;
                   6982:            }
1.29      www      6983:        }
1.83      www      6984:        
1.148     www      6985:        if ($checkreferer) {
1.620     albertel 6986: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6987:             unless ($refuri) {
1.800     albertel 6988:                 foreach my $key (keys(%env)) {
                   6989: 		    if ($key=~/^httpref\..*\*/) {
                   6990: 			my $pattern=$key;
1.156     www      6991:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6992:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6993:                         $pattern=~s/\//\\\//g;
1.152     www      6994:                         if ($orguri=~/$pattern/) {
1.800     albertel 6995: 			    $refuri=$env{$key};
1.148     www      6996:                         }
                   6997:                     }
1.191     harris41 6998:                 }
1.148     www      6999:             }
1.232     www      7000: 
1.148     www      7001:          if ($refuri) { 
1.152     www      7002: 	  $refuri=&declutter($refuri);
1.232     www      7003:           my ($match,$cond)=&is_on_map($refuri);
                   7004:             if ($match) {
                   7005:               my $refstatecond=$cond;
1.620     albertel 7006:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7007:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7008:                   my $value = $1;
                   7009:                   if ($priv eq 'bre') {
                   7010:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7011:                       if (@blockers > 0) {
                   7012:                           $thisallowed = 'B';
                   7013:                       } else {
                   7014:                           $thisallowed.=$value;
                   7015:                       }
                   7016:                   } else {
                   7017:                       $thisallowed.=$value;
                   7018:                   }
1.53      www      7019:                   $uri=$refuri;
                   7020:                   $statecond=$refstatecond;
1.52      www      7021:               }
                   7022:           }
1.148     www      7023:         }
1.29      www      7024:        }
1.52      www      7025:    }
1.29      www      7026: 
1.52      www      7027: #
1.103     harris41 7028: # Gathered now: all privileges that could apply, and condition number
1.52      www      7029: # 
                   7030: #
                   7031: # Full or no access?
                   7032: #
1.29      www      7033: 
1.52      www      7034:     if ($thisallowed=~/F/) {
                   7035: 	return 'F';
                   7036:     }
1.29      www      7037: 
1.52      www      7038:     unless ($thisallowed) {
                   7039:         return '';
                   7040:     }
1.29      www      7041: 
1.52      www      7042: # Restrictions exist, deal with them
                   7043: #
                   7044: #   C:according to course preferences
                   7045: #   R:according to resource settings
                   7046: #   L:unless locked
                   7047: #   X:according to user session state
                   7048: #
                   7049: 
                   7050: # Possibly locked functionality, check all courses
1.54      www      7051: # Locks might take effect only after 10 minutes cache expiration for other
                   7052: # courses, and 2 minutes for current course
1.52      www      7053: 
                   7054:     my $envkey;
                   7055:     if ($thisallowed=~/L/) {
1.1000    raeburn  7056:         foreach $envkey (keys(%env)) {
1.54      www      7057:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7058:                my $courseid=$2;
                   7059:                my $roleid=$1.'.'.$2;
1.92      www      7060:                $courseid=~s/^\///;
1.54      www      7061:                my $expiretime=600;
1.620     albertel 7062:                if ($env{'request.role'} eq $roleid) {
1.54      www      7063: 		  $expiretime=120;
                   7064:                }
                   7065: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7066:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7067:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7068: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7069:                }
1.620     albertel 7070:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7071:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7072: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7073:                        &log($env{'user.domain'},$env{'user.name'},
                   7074:                             $env{'user.home'},
1.57      www      7075:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7076:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7077:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7078: 		       return '';
                   7079:                    }
                   7080:                }
1.620     albertel 7081:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7082:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7083: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7084:                        &log($env{'user.domain'},$env{'user.name'},
                   7085:                             $env{'user.home'},
1.57      www      7086:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7087:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7088:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7089: 		       return '';
                   7090:                    }
                   7091:                }
                   7092: 	   }
1.29      www      7093:        }
1.52      www      7094:     }
                   7095:    
                   7096: #
                   7097: # Rest of the restrictions depend on selected course
                   7098: #
                   7099: 
1.620     albertel 7100:     unless ($env{'request.course.id'}) {
1.766     albertel 7101: 	if ($thisallowed eq 'A') {
                   7102: 	    return 'A';
1.814     raeburn  7103:         } elsif ($thisallowed eq 'B') {
                   7104:             return 'B';
1.766     albertel 7105: 	} else {
                   7106: 	    return '1';
                   7107: 	}
1.52      www      7108:     }
1.29      www      7109: 
1.52      www      7110: #
                   7111: # Now user is definitely in a course
                   7112: #
1.53      www      7113: 
                   7114: 
                   7115: # Course preferences
                   7116: 
                   7117:    if ($thisallowed=~/C/) {
1.620     albertel 7118:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7119:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7120:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7121: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  7122: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7123: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7124: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7125: 			$env{'request.course.id'});
                   7126: 	   }
1.237     www      7127:            return '';
                   7128:        }
                   7129: 
1.620     albertel 7130:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7131: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  7132: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7133: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7134: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7135: 			$env{'request.course.id'});
                   7136: 	   }
1.54      www      7137:            return '';
                   7138:        }
1.53      www      7139:    }
                   7140: 
                   7141: # Resource preferences
                   7142: 
                   7143:    if ($thisallowed=~/R/) {
1.620     albertel 7144:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7145:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7146: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7147: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7148: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7149: 	   }
                   7150: 	   return '';
1.54      www      7151:        }
1.53      www      7152:    }
1.30      www      7153: 
1.246     www      7154: # Restricted by state or randomout?
1.30      www      7155: 
1.52      www      7156:    if ($thisallowed=~/X/) {
1.620     albertel 7157:       if ($env{'acc.randomout'}) {
1.579     albertel 7158: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7159:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7160:             return ''; 
                   7161:          }
1.247     www      7162:       }
                   7163:       if (&condval($statecond)) {
1.52      www      7164: 	 return '2';
                   7165:       } else {
                   7166:          return '';
                   7167:       }
                   7168:    }
1.30      www      7169: 
1.766     albertel 7170:     if ($thisallowed eq 'A') {
                   7171: 	return 'A';
1.814     raeburn  7172:     } elsif ($thisallowed eq 'B') {
                   7173:         return 'B';
1.766     albertel 7174:     }
1.52      www      7175:    return 'F';
1.232     www      7176: }
1.1162    raeburn  7177: 
1.1172.2.13  raeburn  7178: # ------------------------------------------- Check construction space access
                   7179: 
                   7180: sub constructaccess {
                   7181:     my ($url,$setpriv)=@_;
                   7182: 
                   7183: # We do not allow editing of previous versions of files
                   7184:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7185: 
                   7186: # Get username and domain from URL
                   7187:     my ($ownername,$ownerdomain,$ownerhome);
                   7188: 
                   7189:     ($ownerdomain,$ownername) =
                   7190:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
                   7191: 
                   7192: # The URL does not really point to any authorspace, forget it
                   7193:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7194: 
                   7195: # Now we need to see if the user has access to the authorspace of
                   7196: # $ownername at $ownerdomain
                   7197: 
                   7198:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7199: # Real author for this?
                   7200:        $ownerhome = $env{'user.home'};
                   7201:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7202:           return ($ownername,$ownerdomain,$ownerhome);
                   7203:        }
                   7204:     } else {
                   7205: # Co-author for this?
                   7206:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7207:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7208:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7209:             return ($ownername,$ownerdomain,$ownerhome);
                   7210:         }
                   7211:     }
                   7212: 
                   7213: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7214: # we might as well leave
                   7215:    unless ($setpriv) { return ''; }
                   7216: 
                   7217: # Backdoor access?
                   7218:     my $allowed=&allowed('eco',$ownerdomain);
                   7219: # Nope
                   7220:     unless ($allowed) { return ''; }
                   7221: # Looks like we may have access, but could be locked by the owner of the construction space
                   7222:     if ($allowed eq 'U') {
                   7223:         my %blocked=&get('environment',['domcoord.author'],
                   7224:                          $ownerdomain,$ownername);
                   7225: # Is blocked by owner
                   7226:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7227:     }
                   7228:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7229: # Grant temporary access
                   7230:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  7231:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  7232:         if (!$update) { $update = $then; }
                   7233:         my $refresh=$env{'user.refresh.time'};
                   7234:         if (!$refresh) { $refresh = $update; }
                   7235:         my $now = time;
                   7236:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7237:                            $now,'ca','constructaccess');
                   7238:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7239:         return($ownername,$ownerdomain,$ownerhome);
                   7240:     }
                   7241: # No business here
                   7242:     return '';
                   7243: }
                   7244: 
1.1162    raeburn  7245: sub get_comm_blocks {
                   7246:     my ($cdom,$cnum) = @_;
                   7247:     if ($cdom eq '' || $cnum eq '') {
                   7248:         return unless ($env{'request.course.id'});
                   7249:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7250:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7251:     }
                   7252:     my %commblocks;
                   7253:     my $hashid=$cdom.'_'.$cnum;
                   7254:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7255:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7256:         %commblocks = %{$blocksref};
                   7257:     } else {
                   7258:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7259:         my $cachetime = 600;
                   7260:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7261:     }
                   7262:     return %commblocks;
                   7263: }
                   7264: 
                   7265: sub has_comm_blocking {
                   7266:     my ($priv,$symb,$uri,$blocks) = @_;
                   7267:     return unless ($env{'request.course.id'});
                   7268:     return unless ($priv eq 'bre');
                   7269:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7270:     my %commblocks;
                   7271:     if (ref($blocks) eq 'HASH') {
                   7272:         %commblocks = %{$blocks};
                   7273:     } else {
                   7274:         %commblocks = &get_comm_blocks();
                   7275:     }
                   7276:     return unless (keys(%commblocks) > 0);
                   7277:     if (!$symb) { $symb=&symbread($uri,1); }
                   7278:     my ($map,$resid,undef)=&decode_symb($symb);
                   7279:     my %tocheck = (
                   7280:                     maps      => $map,
                   7281:                     resources => $symb,
                   7282:                   );
                   7283:     my @blockers;
                   7284:     my $now = time;
1.1163    raeburn  7285:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1162    raeburn  7286:     foreach my $block (keys(%commblocks)) {
                   7287:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7288:             my ($start,$end) = ($1,$2);
                   7289:             if ($start <= $now && $end >= $now) {
                   7290:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7291:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7292:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7293:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
                   7294:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7295:                                     push(@blockers,$block);
                   7296:                                 }
                   7297:                             }
                   7298:                         }
                   7299:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7300:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
                   7301:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
                   7302:                                     push(@blockers,$block);
                   7303:                                 }
                   7304:                             }
                   7305:                         }
                   7306:                     }
                   7307:                 }
                   7308:             }
                   7309:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7310:             my $item = $1;
1.1163    raeburn  7311:             my @to_test;
1.1162    raeburn  7312:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7313:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7314:                     my $check_interval;
                   7315:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
                   7316:                         my @interval;
                   7317:                         my $type = 'map';
                   7318:                         if ($item eq 'course') {
                   7319:                             $type = 'course';
                   7320:                             @interval=&EXT("resource.0.interval");
                   7321:                         } else {
                   7322:                             if ($item =~ /___\d+___/) {
                   7323:                                 $type = 'resource';
                   7324:                                 @interval=&EXT("resource.0.interval",$item);
1.1163    raeburn  7325:                                 if (ref($navmap)) {                        
                   7326:                                     my $res = $navmap->getBySymb($item); 
                   7327:                                     push(@to_test,$res);
                   7328:                                 }
1.1162    raeburn  7329:                             } else {
                   7330:                                 my $mapsymb = &symbread($item,1);
                   7331:                                 if ($mapsymb) {
                   7332:                                     if (ref($navmap)) {
                   7333:                                         my $mapres = $navmap->getBySymb($mapsymb);
1.1163    raeburn  7334:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
                   7335:                                         foreach my $res (@to_test) {
1.1162    raeburn  7336:                                             my $symb = $res->symb();
                   7337:                                             next if ($symb eq $mapsymb);
                   7338:                                             if ($symb ne '') {
                   7339:                                                 @interval=&EXT("resource.0.interval",$symb);
                   7340:                                                 last;
                   7341:                                             }
                   7342:                                         }
                   7343:                                     }
                   7344:                                 }
                   7345:                             }
                   7346:                         }
                   7347:                         if ($interval[0] =~ /\d+/) {
                   7348:                             my $first_access;
                   7349:                             if ($type eq 'resource') {
                   7350:                                 $first_access=&get_first_access($interval[1],$item);
                   7351:                             } elsif ($type eq 'map') {
                   7352:                                 $first_access=&get_first_access($interval[1],undef,$item);
                   7353:                             } else {
                   7354:                                 $first_access=&get_first_access($interval[1]);
                   7355:                             }
                   7356:                             if ($first_access) {
                   7357:                                 my $timesup = $first_access+$interval[0];
                   7358:                                 if ($timesup > $now) {
1.1163    raeburn  7359:                                     foreach my $res (@to_test) {
                   7360:                                         if ($res->is_problem()) {
                   7361:                                             if ($res->completable()) {
                   7362:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7363:                                                     push(@blockers,$block);
                   7364:                                                 }
                   7365:                                                 last;
                   7366:                                             }
                   7367:                                         }
1.1162    raeburn  7368:                                     }
                   7369:                                 }
                   7370:                             }
                   7371:                         }
                   7372:                     }
                   7373:                 }
                   7374:             }
                   7375:         }
                   7376:     }
                   7377:     return @blockers;
                   7378: }
                   7379: 
                   7380: sub check_docs_block {
                   7381:     my ($docsblock,$tocheck) =@_;
                   7382:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
                   7383:         return;
                   7384:     }
                   7385:     if (ref($docsblock->{'maps'}) eq 'HASH') {
                   7386:         if ($tocheck->{'maps'}) {
                   7387:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
                   7388:                 return 1;
                   7389:             }
                   7390:         }
                   7391:     }
                   7392:     if (ref($docsblock->{'resources'}) eq 'HASH') {
                   7393:         if ($tocheck->{'resources'}) {
                   7394:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
                   7395:                 return 1;
                   7396:             }
                   7397:         }
                   7398:     }
                   7399:     return;
                   7400: }
                   7401: 
1.1133    foxr     7402: #
                   7403: #   Removes the versino from a URI and
                   7404: #   splits it in to its filename and path to the filename.
                   7405: #   Seems like File::Basename could have done this more clearly.
                   7406: #   Parameters:
                   7407: #      $uri   - input URI
                   7408: #   Returns:
                   7409: #     Two element list consisting of 
                   7410: #     $pathname  - the URI up to and excluding the trailing /
                   7411: #     $filename  - The part of the URI following the last /
                   7412: #  NOTE:
                   7413: #    Another realization of this is simply:
                   7414: #    use File::Basename;
                   7415: #    ...
                   7416: #    $uri = shift;
                   7417: #    $filename = basename($uri);
                   7418: #    $path     = dirname($uri);
                   7419: #    return ($filename, $path);
                   7420: #
                   7421: #     The implementation below is probably faster however.
                   7422: #
1.710     albertel 7423: sub split_uri_for_cond {
                   7424:     my $uri=&deversion(&declutter(shift));
                   7425:     my @uriparts=split(/\//,$uri);
                   7426:     my $filename=pop(@uriparts);
                   7427:     my $pathname=join('/',@uriparts);
                   7428:     return ($pathname,$filename);
                   7429: }
1.232     www      7430: # --------------------------------------------------- Is a resource on the map?
                   7431: 
                   7432: sub is_on_map {
1.710     albertel 7433:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7434:     #Trying to find the conditional for the file
1.620     albertel 7435:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7436: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7437:     if ($match) {
1.289     bowersj2 7438: 	return (1,$1);
                   7439:     } else {
1.434     www      7440: 	return (0,0);
1.289     bowersj2 7441:     }
1.12      www      7442: }
                   7443: 
1.427     www      7444: # --------------------------------------------------------- Get symb from alias
                   7445: 
                   7446: sub get_symb_from_alias {
                   7447:     my $symb=shift;
                   7448:     my ($map,$resid,$url)=&decode_symb($symb);
                   7449: # Already is a symb
                   7450:     if ($url) { return $symb; }
                   7451: # Must be an alias
                   7452:     my $aliassymb='';
                   7453:     my %bighash;
1.620     albertel 7454:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7455:                             &GDBM_READER(),0640)) {
                   7456:         my $rid=$bighash{'mapalias_'.$symb};
                   7457: 	if ($rid) {
                   7458: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7459: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7460: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7461: 	}
                   7462:         untie %bighash;
                   7463:     }
                   7464:     return $aliassymb;
                   7465: }
                   7466: 
1.12      www      7467: # ----------------------------------------------------------------- Define Role
                   7468: 
                   7469: sub definerole {
                   7470:   if (allowed('mcr','/')) {
                   7471:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7472:     foreach my $role (split(':',$sysrole)) {
                   7473: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7474:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7475:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7476: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7477:                return "refused:s:$crole&$cqual"; 
                   7478:             }
                   7479:         }
1.191     harris41 7480:     }
1.800     albertel 7481:     foreach my $role (split(':',$domrole)) {
                   7482: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7483:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7484:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7485: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7486:                return "refused:d:$crole&$cqual"; 
                   7487:             }
                   7488:         }
1.191     harris41 7489:     }
1.800     albertel 7490:     foreach my $role (split(':',$courole)) {
                   7491: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7492:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7493:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7494: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7495:                return "refused:c:$crole&$cqual"; 
                   7496:             }
                   7497:         }
1.191     harris41 7498:     }
1.620     albertel 7499:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7500:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7501: 	        "rolesdef_$rolename=".
                   7502:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7503:     return reply($command,$env{'user.home'});
1.12      www      7504:   } else {
                   7505:     return 'refused';
                   7506:   }
1.105     harris41 7507: }
                   7508: 
                   7509: # ---------------- Make a metadata query against the network of library servers
                   7510: 
                   7511: sub metadata_query {
1.1172.2.33  raeburn  7512:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 7513:     my %rhash;
1.845     albertel 7514:     my %libserv = &all_library();
1.244     matthew  7515:     my @server_list = (defined($server_array) ? @$server_array
                   7516:                                               : keys(%libserv) );
                   7517:     for my $server (@server_list) {
1.1172.2.33  raeburn  7518:         my $domains = '';
                   7519:         if (ref($domains_hash) eq 'HASH') {
                   7520:             $domains = $domains_hash->{$server};    
                   7521:         }
1.118     harris41 7522: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  7523: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 7524: 	    $rhash{$server}=$reply;
                   7525: 	}
                   7526: 	else {
                   7527: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  7528: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 7529: 			     $server);
                   7530: 	    $rhash{$server}=$reply;
                   7531: 	}
1.112     harris41 7532:     }
1.118     harris41 7533:     return \%rhash;
1.240     www      7534: }
                   7535: 
                   7536: # ----------------------------------------- Send log queries and wait for reply
                   7537: 
                   7538: sub log_query {
                   7539:     my ($uname,$udom,$query,%filters)=@_;
                   7540:     my $uhome=&homeserver($uname,$udom);
                   7541:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7542:     my $uhost=&hostname($uhome);
1.800     albertel 7543:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7544:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7545:                        $uhome);
1.479     albertel 7546:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7547:     return get_query_reply($queryid);
                   7548: }
                   7549: 
1.818     raeburn  7550: # -------------------------- Update MySQL table for portfolio file
                   7551: 
                   7552: sub update_portfolio_table {
1.821     raeburn  7553:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7554:     if ($group ne '') {
                   7555:         $file_name =~s /^\Q$group\E//;
                   7556:     }
1.818     raeburn  7557:     my $homeserver = &homeserver($uname,$udom);
                   7558:     my $queryid=
1.821     raeburn  7559:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7560:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7561:     my $reply = &get_query_reply($queryid);
                   7562:     return $reply;
                   7563: }
                   7564: 
1.899     raeburn  7565: # -------------------------- Update MySQL allusers table
                   7566: 
                   7567: sub update_allusers_table {
                   7568:     my ($uname,$udom,$names) = @_;
                   7569:     my $homeserver = &homeserver($uname,$udom);
                   7570:     my $queryid=
                   7571:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7572:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7573:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7574:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7575:                'generation='.&escape($names->{'generation'}).'%%'.
                   7576:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7577:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7578:     return;
1.899     raeburn  7579: }
                   7580: 
1.508     raeburn  7581: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7582: 
                   7583: sub fetch_enrollment_query {
1.511     raeburn  7584:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  7585:     my $homeserver;
1.547     raeburn  7586:     my $maxtries = 1;
1.508     raeburn  7587:     if ($context eq 'automated') {
                   7588:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  7589:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7590:     } else {
                   7591:         $homeserver = &homeserver($cnum,$dom);
                   7592:     }
1.838     albertel 7593:     my $host=&hostname($homeserver);
1.506     raeburn  7594:     my $cmd = '';
1.1000    raeburn  7595:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7596:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7597:     }
                   7598:     $cmd =~ s/%%$//;
                   7599:     $cmd = &escape($cmd);
                   7600:     my $query = 'fetchenrollment';
1.620     albertel 7601:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7602:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7603:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7604:         return 'error: '.$queryid;
                   7605:     }
1.506     raeburn  7606:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7607:     my $tries = 1;
                   7608:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7609:         $reply = &get_query_reply($queryid);
                   7610:         $tries ++;
                   7611:     }
1.526     raeburn  7612:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7613:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7614:     } else {
1.901     albertel 7615:         my @responses = split(/:/,$reply);
1.515     raeburn  7616:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7617:             foreach my $line (@responses) {
                   7618:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7619:                 $$replyref{$key} = $value;
                   7620:             }
                   7621:         } else {
1.1117    foxr     7622:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7623:             foreach my $line (@responses) {
                   7624:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7625:                 $$replyref{$key} = $value;
                   7626:                 if ($value > 0) {
1.800     albertel 7627:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7628:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7629:                         my $destname = $pathname.'/'.$filename;
                   7630:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7631:                         if ($xml_classlist =~ /^error/) {
                   7632:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7633:                         } else {
1.506     raeburn  7634:                             if ( open(FILE,">$destname") ) {
                   7635:                                 print FILE &unescape($xml_classlist);
                   7636:                                 close(FILE);
1.526     raeburn  7637:                             } else {
                   7638:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7639:                             }
                   7640:                         }
                   7641:                     }
                   7642:                 }
                   7643:             }
                   7644:         }
                   7645:         return 'ok';
                   7646:     }
                   7647:     return 'error';
                   7648: }
                   7649: 
1.242     www      7650: sub get_query_reply {
                   7651:     my $queryid=shift;
1.1117    foxr     7652:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7653:     my $reply='';
                   7654:     for (1..100) {
                   7655: 	sleep 2;
                   7656:         if (-e $replyfile.'.end') {
1.448     albertel 7657: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7658: 		$reply = join('',<$fh>);
                   7659: 		close($fh);
1.240     www      7660: 	   } else { return 'error: reply_file_error'; }
1.242     www      7661:            return &unescape($reply);
                   7662: 	}
1.240     www      7663:     }
1.242     www      7664:     return 'timeout:'.$queryid;
1.240     www      7665: }
                   7666: 
                   7667: sub courselog_query {
1.241     www      7668: #
                   7669: # possible filters:
                   7670: # url: url or symb
                   7671: # username
                   7672: # domain
                   7673: # action: view, submit, grade
                   7674: # start: timestamp
                   7675: # end: timestamp
                   7676: #
1.240     www      7677:     my (%filters)=@_;
1.620     albertel 7678:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7679:     if ($filters{'url'}) {
                   7680: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7681:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7682:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7683:     }
1.620     albertel 7684:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7685:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7686:     return &log_query($cname,$cdom,'courselog',%filters);
                   7687: }
                   7688: 
                   7689: sub userlog_query {
1.858     raeburn  7690: #
                   7691: # possible filters:
                   7692: # action: log check role
                   7693: # start: timestamp
                   7694: # end: timestamp
                   7695: #
1.240     www      7696:     my ($uname,$udom,%filters)=@_;
                   7697:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7698: }
                   7699: 
1.506     raeburn  7700: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7701: 
                   7702: sub auto_run {
1.508     raeburn  7703:     my ($cnum,$cdom) = @_;
1.876     raeburn  7704:     my $response = 0;
                   7705:     my $settings;
                   7706:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7707:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7708:         $settings = $domconfig{'autoenroll'};
                   7709:         if ($settings->{'run'} eq '1') {
                   7710:             $response = 1;
                   7711:         }
                   7712:     } else {
1.934     raeburn  7713:         my $homeserver;
                   7714:         if (&is_course($cdom,$cnum)) {
                   7715:             $homeserver = &homeserver($cnum,$cdom);
                   7716:         } else {
                   7717:             $homeserver = &domain($cdom,'primary');
                   7718:         }
                   7719:         if ($homeserver ne 'no_host') {
                   7720:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7721:         }
1.876     raeburn  7722:     }
1.506     raeburn  7723:     return $response;
                   7724: }
1.776     albertel 7725: 
1.506     raeburn  7726: sub auto_get_sections {
1.508     raeburn  7727:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7728:     my $homeserver;
                   7729:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7730:         $homeserver = &homeserver($cnum,$cdom);
                   7731:     }
                   7732:     if (!defined($homeserver)) { 
                   7733:         if ($cdom =~ /^$match_domain$/) {
                   7734:             $homeserver = &domain($cdom,'primary');
                   7735:         }
                   7736:     }
                   7737:     my @secs;
                   7738:     if (defined($homeserver)) {
                   7739:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7740:         unless ($response eq 'refused') {
                   7741:             @secs = split(/:/,$response);
                   7742:         }
1.506     raeburn  7743:     }
                   7744:     return @secs;
                   7745: }
1.776     albertel 7746: 
1.506     raeburn  7747: sub auto_new_course {
1.1099    raeburn  7748:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7749:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7750:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7751:     return $response;
                   7752: }
1.776     albertel 7753: 
1.506     raeburn  7754: sub auto_validate_courseID {
1.508     raeburn  7755:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7756:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7757:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7758:     return $response;
                   7759: }
1.776     albertel 7760: 
1.1007    raeburn  7761: sub auto_validate_instcode {
1.1020    raeburn  7762:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7763:     my ($homeserver,$response);
                   7764:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7765:         $homeserver = &homeserver($cnum,$cdom);
                   7766:     }
                   7767:     if (!defined($homeserver)) {
                   7768:         if ($cdom =~ /^$match_domain$/) {
                   7769:             $homeserver = &domain($cdom,'primary');
                   7770:         }
                   7771:     }
1.1065    raeburn  7772:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7773:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  7774:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   7775:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  7776: }
                   7777: 
1.506     raeburn  7778: sub auto_create_password {
1.873     raeburn  7779:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7780:     my ($homeserver,$response);
1.506     raeburn  7781:     my $create_passwd = 0;
                   7782:     my $authchk = '';
1.873     raeburn  7783:     if ($udom =~ /^$match_domain$/) {
                   7784:         $homeserver = &domain($udom,'primary');
                   7785:     }
                   7786:     if ($homeserver eq '') {
                   7787:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7788:             $homeserver = &homeserver($cnum,$cdom);
                   7789:         }
                   7790:     }
                   7791:     if ($homeserver eq '') {
                   7792:         $authchk = 'nodomain';
1.506     raeburn  7793:     } else {
1.873     raeburn  7794:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   7795:         if ($response eq 'refused') {
                   7796:             $authchk = 'refused';
                   7797:         } else {
1.901     albertel 7798:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  7799:         }
1.506     raeburn  7800:     }
                   7801:     return ($authparam,$create_passwd,$authchk);
                   7802: }
                   7803: 
1.706     raeburn  7804: sub auto_photo_permission {
                   7805:     my ($cnum,$cdom,$students) = @_;
                   7806:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 7807:     my ($outcome,$perm_reqd,$conditions) = 
                   7808: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 7809:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7810: 	return (undef,undef);
                   7811:     }
1.706     raeburn  7812:     return ($outcome,$perm_reqd,$conditions);
                   7813: }
                   7814: 
                   7815: sub auto_checkphotos {
                   7816:     my ($uname,$udom,$pid) = @_;
                   7817:     my $homeserver = &homeserver($uname,$udom);
                   7818:     my ($result,$resulttype);
                   7819:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 7820: 				   &escape($uname).':'.&escape($pid),
                   7821: 				   $homeserver));
1.709     albertel 7822:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7823: 	return (undef,undef);
                   7824:     }
1.706     raeburn  7825:     if ($outcome) {
                   7826:         ($result,$resulttype) = split(/:/,$outcome);
                   7827:     } 
                   7828:     return ($result,$resulttype);
                   7829: }
                   7830: 
                   7831: sub auto_photochoice {
                   7832:     my ($cnum,$cdom) = @_;
                   7833:     my $homeserver = &homeserver($cnum,$cdom);
                   7834:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 7835: 						       &escape($cdom),
                   7836: 						       $homeserver)));
1.709     albertel 7837:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7838: 	return (undef,undef);
                   7839:     }
1.706     raeburn  7840:     return ($update,$comment);
                   7841: }
                   7842: 
                   7843: sub auto_photoupdate {
                   7844:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   7845:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 7846:     my $host=&hostname($homeserver);
1.706     raeburn  7847:     my $cmd = '';
                   7848:     my $maxtries = 1;
1.800     albertel 7849:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   7850:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  7851:     }
                   7852:     $cmd =~ s/%%$//;
                   7853:     $cmd = &escape($cmd);
                   7854:     my $query = 'institutionalphotos';
                   7855:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7856:     unless ($queryid=~/^\Q$host\E\_/) {
                   7857:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7858:         return 'error: '.$queryid;
                   7859:     }
                   7860:     my $reply = &get_query_reply($queryid);
                   7861:     my $tries = 1;
                   7862:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7863:         $reply = &get_query_reply($queryid);
                   7864:         $tries ++;
                   7865:     }
                   7866:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7867:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7868:     } else {
                   7869:         my @responses = split(/:/,$reply);
                   7870:         my $outcome = shift(@responses); 
                   7871:         foreach my $item (@responses) {
                   7872:             my ($key,$value) = split(/=/,$item);
                   7873:             $$photo{$key} = $value;
                   7874:         }
                   7875:         return $outcome;
                   7876:     }
                   7877:     return 'error';
                   7878: }
                   7879: 
1.521     raeburn  7880: sub auto_instcode_format {
1.793     albertel 7881:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7882: 	$cat_order) = @_;
1.521     raeburn  7883:     my $courses = '';
1.772     raeburn  7884:     my @homeservers;
1.521     raeburn  7885:     if ($caller eq 'global') {
1.841     albertel 7886: 	my %servers = &get_servers($codedom,'library');
                   7887: 	foreach my $tryserver (keys(%servers)) {
                   7888: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7889: 		push(@homeservers,$tryserver);
                   7890: 	    }
1.584     raeburn  7891:         }
1.1022    raeburn  7892:     } elsif ($caller eq 'requests') {
                   7893:         if ($codedom =~ /^$match_domain$/) {
                   7894:             my $chome = &domain($codedom,'primary');
                   7895:             unless ($chome eq 'no_host') {
                   7896:                 push(@homeservers,$chome);
                   7897:             }
                   7898:         }
1.521     raeburn  7899:     } else {
1.772     raeburn  7900:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7901:     }
1.793     albertel 7902:     foreach my $code (keys(%{$instcodes})) {
                   7903:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7904:     }
                   7905:     chop($courses);
1.772     raeburn  7906:     my $ok_response = 0;
                   7907:     my $response;
                   7908:     while (@homeservers > 0 && $ok_response == 0) {
                   7909:         my $server = shift(@homeservers); 
                   7910:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7911:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7912:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7913: 		split(/:/,$response);
1.772     raeburn  7914:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7915:             push(@{$codetitles},&str2array($codetitles_str));
                   7916:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   7917:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   7918:             $ok_response = 1;
                   7919:         }
                   7920:     }
                   7921:     if ($ok_response) {
1.521     raeburn  7922:         return 'ok';
1.772     raeburn  7923:     } else {
                   7924:         return $response;
1.521     raeburn  7925:     }
                   7926: }
                   7927: 
1.792     raeburn  7928: sub auto_instcode_defaults {
                   7929:     my ($domain,$returnhash,$code_order) = @_;
                   7930:     my @homeservers;
1.841     albertel 7931: 
                   7932:     my %servers = &get_servers($domain,'library');
                   7933:     foreach my $tryserver (keys(%servers)) {
                   7934: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7935: 	    push(@homeservers,$tryserver);
                   7936: 	}
1.792     raeburn  7937:     }
1.841     albertel 7938: 
1.792     raeburn  7939:     my $response;
1.841     albertel 7940:     foreach my $server (@homeservers) {
1.792     raeburn  7941:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 7942:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   7943: 	
                   7944: 	foreach my $pair (split(/\&/,$response)) {
                   7945: 	    my ($name,$value)=split(/\=/,$pair);
                   7946: 	    if ($name eq 'code_order') {
                   7947: 		@{$code_order} = split(/\&/,&unescape($value));
                   7948: 	    } else {
                   7949: 		$returnhash->{&unescape($name)}=&unescape($value);
                   7950: 	    }
                   7951: 	}
                   7952: 	return 'ok';
1.792     raeburn  7953:     }
1.841     albertel 7954: 
                   7955:     return $response;
1.1003    raeburn  7956: }
                   7957: 
                   7958: sub auto_possible_instcodes {
1.1007    raeburn  7959:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   7960:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   7961:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   7962:         return;
                   7963:     }
1.1003    raeburn  7964:     my (@homeservers,$uhome);
                   7965:     if (defined(&domain($domain,'primary'))) {
                   7966:         $uhome=&domain($domain,'primary');
                   7967:         push(@homeservers,&domain($domain,'primary'));
                   7968:     } else {
                   7969:         my %servers = &get_servers($domain,'library');
                   7970:         foreach my $tryserver (keys(%servers)) {
                   7971:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7972:                 push(@homeservers,$tryserver);
                   7973:             }
                   7974:         }
                   7975:     }
                   7976:     my $response;
                   7977:     foreach my $server (@homeservers) {
                   7978:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   7979:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  7980:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   7981:             split(':',$response);
                   7982:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   7983:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  7984:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  7985:             my ($name,$value)=split('=',$item);
                   7986:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7987:         }
                   7988:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  7989:             my ($name,$value)=split('=',$item);
                   7990:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7991:         }
                   7992:         return 'ok';
                   7993:     }
                   7994:     return $response;
                   7995: }
1.792     raeburn  7996: 
1.1010    raeburn  7997: sub auto_courserequest_checks {
                   7998:     my ($dom) = @_;
1.1020    raeburn  7999:     my ($homeserver,%validations);
                   8000:     if ($dom =~ /^$match_domain$/) {
                   8001:         $homeserver = &domain($dom,'primary');
                   8002:     }
                   8003:     unless ($homeserver eq 'no_host') {
                   8004:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8005:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8006:             my @items = split(/&/,$response);
                   8007:             foreach my $item (@items) {
                   8008:                 my ($key,$value) = split('=',$item);
                   8009:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8010:             }
                   8011:         }
                   8012:     }
1.1010    raeburn  8013:     return %validations; 
                   8014: }
                   8015: 
1.1020    raeburn  8016: sub auto_courserequest_validation {
1.1172.2.43  raeburn  8017:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8018:     my ($homeserver,$response);
                   8019:     if ($dom =~ /^$match_domain$/) {
                   8020:         $homeserver = &domain($dom,'primary');
                   8021:     }
1.1172.2.43  raeburn  8022:     unless ($homeserver eq 'no_host') {
                   8023:         my $customdata;
                   8024:         if (ref($custominfo) eq 'HASH') {
                   8025:             $customdata = &freeze_escape($custominfo);
                   8026:         }
1.1020    raeburn  8027:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8028:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  8029:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8030:                                     $customdata,$homeserver));
1.1020    raeburn  8031:     }
                   8032:     return $response;
                   8033: }
                   8034: 
1.777     albertel 8035: sub auto_validate_class_sec {
1.918     raeburn  8036:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8037:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8038:     my $ownerlist;
                   8039:     if (ref($owners) eq 'ARRAY') {
                   8040:         $ownerlist = join(',',@{$owners});
                   8041:     } else {
                   8042:         $ownerlist = $owners;
                   8043:     }
1.773     raeburn  8044:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8045:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8046:     return $response;
                   8047: }
                   8048: 
1.1172.2.38  raeburn  8049: sub auto_crsreq_update {
                   8050:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  8051:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  8052:     my ($homeserver,%crsreqresponse);
                   8053:     if ($cdom =~ /^$match_domain$/) {
                   8054:         $homeserver = &domain($cdom,'primary');
                   8055:     }
                   8056:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8057:         my $info;
                   8058:         if (ref($inbound) eq 'HASH') {
                   8059:             $info = &freeze_escape($inbound);
                   8060:         }
                   8061:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8062:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8063:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  8064:                             &escape($title).':'.&escape($code).':'.
                   8065:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  8066:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8067:             my @items = split(/&/,$response);
                   8068:             foreach my $item (@items) {
                   8069:                 my ($key,$value) = split('=',$item);
                   8070:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8071:             }
                   8072:         }
                   8073:     }
                   8074:     return \%crsreqresponse;
                   8075: }
                   8076: 
1.679     raeburn  8077: # ------------------------------------------------------- Course Group routines
                   8078: 
                   8079: sub get_coursegroups {
1.809     raeburn  8080:     my ($cdom,$cnum,$group,$namespace) = @_;
                   8081:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  8082: }
                   8083: 
1.679     raeburn  8084: sub modify_coursegroup {
                   8085:     my ($cdom,$cnum,$groupsettings) = @_;
                   8086:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   8087: }
                   8088: 
1.809     raeburn  8089: sub toggle_coursegroup_status {
                   8090:     my ($cdom,$cnum,$group,$action) = @_;
                   8091:     my ($from_namespace,$to_namespace);
                   8092:     if ($action eq 'delete') {
                   8093:         $from_namespace = 'coursegroups';
                   8094:         $to_namespace = 'deleted_groups';
                   8095:     } else {
                   8096:         $from_namespace = 'deleted_groups';
                   8097:         $to_namespace = 'coursegroups';
                   8098:     }
                   8099:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  8100:     if (my $tmp = &error(%curr_group)) {
                   8101:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   8102:         return ('read error',$tmp);
                   8103:     } else {
                   8104:         my %savedsettings = %curr_group; 
1.809     raeburn  8105:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  8106:         my $deloutcome;
                   8107:         if ($result eq 'ok') {
1.809     raeburn  8108:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  8109:         } else {
                   8110:             return ('write error',$result);
                   8111:         }
                   8112:         if ($deloutcome eq 'ok') {
                   8113:             return 'ok';
                   8114:         } else {
                   8115:             return ('delete error',$deloutcome);
                   8116:         }
                   8117:     }
                   8118: }
                   8119: 
1.679     raeburn  8120: sub modify_group_roles {
1.957     raeburn  8121:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  8122:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   8123:     my $role = 'gr/'.&escape($userprivs);
                   8124:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  8125:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  8126:     if ($result eq 'ok') {
                   8127:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   8128:     }
1.679     raeburn  8129:     return $result;
                   8130: }
                   8131: 
                   8132: sub modify_coursegroup_membership {
                   8133:     my ($cdom,$cnum,$membership) = @_;
                   8134:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   8135:     return $result;
                   8136: }
                   8137: 
1.682     raeburn  8138: sub get_active_groups {
                   8139:     my ($udom,$uname,$cdom,$cnum) = @_;
                   8140:     my $now = time;
                   8141:     my %groups = ();
                   8142:     foreach my $key (keys(%env)) {
1.811     albertel 8143:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  8144:             my ($start,$end) = split(/\./,$env{$key});
                   8145:             if (($end!=0) && ($end<$now)) { next; }
                   8146:             if (($start!=0) && ($start>$now)) { next; }
                   8147:             if ($1 eq $cdom && $2 eq $cnum) {
                   8148:                 $groups{$3} = $env{$key} ;
                   8149:             }
                   8150:         }
                   8151:     }
                   8152:     return %groups;
                   8153: }
                   8154: 
1.683     raeburn  8155: sub get_group_membership {
                   8156:     my ($cdom,$cnum,$group) = @_;
                   8157:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   8158: }
                   8159: 
                   8160: sub get_users_groups {
                   8161:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  8162:     my @usersgroups;
1.683     raeburn  8163:     my $cachetime=1800;
                   8164: 
                   8165:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  8166:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   8167:     if (defined($cached)) {
1.734     albertel 8168:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  8169:     } else {  
                   8170:         $grouplist = '';
1.816     raeburn  8171:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  8172:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  8173:         my $access_end = $env{'course.'.$courseid.
                   8174:                               '.default_enrollment_end_date'};
                   8175:         my $now = time;
                   8176:         foreach my $key (keys(%roleshash)) {
                   8177:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   8178:                 my $group = $1;
                   8179:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   8180:                     my $start = $2;
                   8181:                     my $end = $1;
                   8182:                     if ($start == -1) { next; } # deleted from group
                   8183:                     if (($start!=0) && ($start>$now)) { next; }
                   8184:                     if (($end!=0) && ($end<$now)) {
                   8185:                         if ($access_end && $access_end < $now) {
                   8186:                             if ($access_end - $end < 86400) {
                   8187:                                 push(@usersgroups,$group);
1.733     raeburn  8188:                             }
                   8189:                         }
1.817     raeburn  8190:                         next;
1.733     raeburn  8191:                     }
1.817     raeburn  8192:                     push(@usersgroups,$group);
1.683     raeburn  8193:                 }
                   8194:             }
                   8195:         }
1.817     raeburn  8196:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8197:         $grouplist = join(':',@usersgroups);
                   8198:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8199:     }
1.733     raeburn  8200:     return @usersgroups;
1.683     raeburn  8201: }
                   8202: 
                   8203: sub devalidate_getgroups_cache {
                   8204:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8205:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8206: 
1.683     raeburn  8207:     my $hashid="$udom:$uname:$courseid";
                   8208:     &devalidate_cache_new('getgroups',$hashid);
                   8209: }
                   8210: 
1.12      www      8211: # ------------------------------------------------------------------ Plain Text
                   8212: 
                   8213: sub plaintext {
1.988     raeburn  8214:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8215:     if ($short =~ m{^cr/}) {
1.758     albertel 8216: 	return (split('/',$short))[-1];
                   8217:     }
1.742     raeburn  8218:     if (!defined($cid)) {
                   8219:         $cid = $env{'request.course.id'};
                   8220:     }
                   8221:     my %rolenames = (
1.1008    raeburn  8222:                       Course    => 'std',
                   8223:                       Community => 'alt1',
1.742     raeburn  8224:                     );
1.1037    raeburn  8225:     if ($cid ne '') {
                   8226:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8227:             unless ($forcedefault) {
                   8228:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8229:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8230:                 return &Apache::lonlocal::mt($roletext);
                   8231:             }
                   8232:         }
                   8233:     }
                   8234:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8235:         (defined($rolenames{$type})) && 
                   8236:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8237:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8238:     } elsif ($cid ne '') {
                   8239:         my $crstype = $env{'course.'.$cid.'.type'};
                   8240:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8241:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8242:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8243:         }
1.742     raeburn  8244:     }
1.1037    raeburn  8245:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8246: }
                   8247: 
                   8248: # ----------------------------------------------------------------- Assign Role
                   8249: 
                   8250: sub assignrole {
1.957     raeburn  8251:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8252:         $context)=@_;
1.21      www      8253:     my $mrole;
                   8254:     if ($role =~ /^cr\//) {
1.393     www      8255:         my $cwosec=$url;
1.811     albertel 8256:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8257: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8258:            my $refused = 1;
                   8259:            if ($context eq 'requestcourses') {
                   8260:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8261:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8262:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8263:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8264:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8265:                            if ($crsenv{'internal.courseowner'} eq
                   8266:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8267:                                $refused = '';
                   8268:                            }
                   8269:                        }
                   8270:                    }
                   8271:                }
                   8272:            }
                   8273:            if ($refused) {
                   8274:                &logthis('Refused custom assignrole: '.
                   8275:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8276:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8277:                return 'refused';
                   8278:            }
1.104     www      8279:         }
1.21      www      8280:         $mrole='cr';
1.678     raeburn  8281:     } elsif ($role =~ /^gr\//) {
                   8282:         my $cwogrp=$url;
1.811     albertel 8283:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8284:         unless (&allowed('mdg',$cwogrp)) {
                   8285:             &logthis('Refused group assignrole: '.
                   8286:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   8287:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   8288:             return 'refused';
                   8289:         }
                   8290:         $mrole='gr';
1.21      www      8291:     } else {
1.82      www      8292:         my $cwosec=$url;
1.811     albertel 8293:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  8294:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   8295:             my $refused;
                   8296:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   8297:                 if (!(&allowed('c'.$role,$url))) {
                   8298:                     $refused = 1;
                   8299:                 }
                   8300:             } else {
                   8301:                 $refused = 1;
                   8302:             }
1.947     raeburn  8303:             if ($refused) {
1.1045    raeburn  8304:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8305:                 if (!$selfenroll && $context eq 'course') {
                   8306:                     my %crsenv;
                   8307:                     if ($role eq 'cc' || $role eq 'co') {
                   8308:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8309:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   8310:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   8311:                                 if ($crsenv{'internal.courseowner'} eq 
                   8312:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8313:                                     $refused = '';
                   8314:                                 }
                   8315:                             }
                   8316:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   8317:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   8318:                                 if ($crsenv{'internal.courseowner'} eq 
                   8319:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8320:                                     $refused = '';
                   8321:                                 }
                   8322:                             }
                   8323:                         }
                   8324:                     }
                   8325:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8326:                     $refused = '';
1.1017    raeburn  8327:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8328:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8329:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8330:                         my $wrongcc;
                   8331:                         if ($cnum =~ /^$match_community$/) {
                   8332:                             $wrongcc = 1 if ($role eq 'cc');
                   8333:                         } else {
                   8334:                             $wrongcc = 1 if ($role eq 'co');
                   8335:                         }
                   8336:                         unless ($wrongcc) {
                   8337:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8338:                             if ($crsenv{'internal.courseowner'} eq 
                   8339:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8340:                                 $refused = '';
                   8341:                             }
1.1017    raeburn  8342:                         }
                   8343:                     }
1.1172.2.9  raeburn  8344:                 } elsif ($context eq 'requestauthor') {
                   8345:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   8346:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8347:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8348:                             $refused = '';
                   8349:                         } else {
                   8350:                             my %domdefaults = &get_domain_defaults($udom);
                   8351:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   8352:                                 my $checkbystatus;
                   8353:                                 if ($env{'user.adv'}) {
                   8354:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8355:                                     if ($disposition eq 'automatic') {
                   8356:                                         $refused = '';
                   8357:                                     } elsif ($disposition eq '') {
                   8358:                                         $checkbystatus = 1;
                   8359:                                     }
                   8360:                                 } else {
                   8361:                                     $checkbystatus = 1;
                   8362:                                 }
                   8363:                                 if ($checkbystatus) {
                   8364:                                     if ($env{'environment.inststatus'}) {
                   8365:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8366:                                         foreach my $type (@inststatuses) {
                   8367:                                             if (($type ne '') &&
                   8368:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   8369:                                                 $refused = '';
                   8370:                                             }
                   8371:                                         }
                   8372:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8373:                                         $refused = '';
                   8374:                                     }
                   8375:                                 }
                   8376:                             }
                   8377:                         }
                   8378:                     }
1.1017    raeburn  8379:                 }
                   8380:                 if ($refused) {
1.947     raeburn  8381:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8382:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8383: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8384:                     return 'refused';
                   8385:                 }
1.932     raeburn  8386:             }
1.1131    raeburn  8387:         } elsif ($role eq 'au') {
                   8388:             if ($url ne '/'.$udom.'/') {
                   8389:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8390:                          ' to assign author role for '.$uname.':'.$udom.
                   8391:                          ' in domain: '.$url.' refused (wrong domain).');
                   8392:                 return 'refused';
                   8393:             }
1.104     www      8394:         }
1.21      www      8395:         $mrole=$role;
                   8396:     }
1.620     albertel 8397:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8398:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8399:     if ($end) { $command.='_'.$end; }
1.21      www      8400:     if ($start) {
                   8401: 	if ($end) { 
1.81      www      8402:            $command.='_'.$start; 
1.21      www      8403:         } else {
1.81      www      8404:            $command.='_0_'.$start;
1.21      www      8405:         }
                   8406:     }
1.739     raeburn  8407:     my $origstart = $start;
                   8408:     my $origend = $end;
1.957     raeburn  8409:     my $delflag;
1.357     www      8410: # actually delete
                   8411:     if ($deleteflag) {
1.373     www      8412: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8413: # modify command to delete the role
1.620     albertel 8414:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8415:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8416: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8417: # set start and finish to negative values for userrolelog
                   8418:            $start=-1;
                   8419:            $end=-1;
1.957     raeburn  8420:            $delflag = 1;
1.357     www      8421:         }
                   8422:     }
                   8423: # send command
1.349     www      8424:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8425: # log new user role if status is ok
1.349     www      8426:     if ($answer eq 'ok') {
1.663     raeburn  8427: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  8428:         if (($role eq 'cc') || ($role eq 'in') ||
                   8429:             ($role eq 'ep') || ($role eq 'ad') ||
                   8430:             ($role eq 'ta') || ($role eq 'st') ||
                   8431:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8432:             ($role eq 'co')) {
1.1172.2.13  raeburn  8433: # for course roles, perform group memberships changes triggered by role change.
                   8434:             unless ($role =~ /^gr/) {
                   8435:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8436:                                                  $origstart,$selfenroll,$context);
                   8437:             }
1.1172.2.9  raeburn  8438:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8439:                            $selfenroll,$context);
                   8440:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8441:                  ($role eq 'au') || ($role eq 'dc')) {
                   8442:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8443:                            $context);
                   8444:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8445:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8446:                              $context);
                   8447:         }
1.1053    raeburn  8448:         if ($role eq 'cc') {
                   8449:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8450:         }
1.349     www      8451:     }
                   8452:     return $answer;
1.169     harris41 8453: }
                   8454: 
1.1053    raeburn  8455: sub autoupdate_coowners {
                   8456:     my ($url,$end,$start,$uname,$udom) = @_;
                   8457:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8458:     if (($cdom ne '') && ($cnum ne '')) {
                   8459:         my $now = time;
                   8460:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8461:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8462:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8463:             my $instcode = $coursehash{'internal.coursecode'};
                   8464:             if ($instcode ne '') {
1.1056    raeburn  8465:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8466:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8467:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8468:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8469:                         if ($result eq 'valid') {
                   8470:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8471:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8472:                                     push(@newcoowners,$coowner);
                   8473:                                 }
                   8474:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8475:                                     push(@newcoowners,$uname.':'.$udom);
                   8476:                                 }
                   8477:                                 @newcoowners = sort(@newcoowners);
                   8478:                             } else {
                   8479:                                 push(@newcoowners,$uname.':'.$udom);
                   8480:                             }
                   8481:                         } else {
                   8482:                             if ($coursehash{'internal.co-owners'}) {
                   8483:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8484:                                     unless ($coowner eq $uname.':'.$udom) {
                   8485:                                         push(@newcoowners,$coowner);
                   8486:                                     }
                   8487:                                 }
                   8488:                                 unless (@newcoowners > 0) {
                   8489:                                     $delcoowners = 1;
                   8490:                                     $coowners = '';
                   8491:                                 }
                   8492:                             }
                   8493:                         }
                   8494:                         if (@newcoowners || $delcoowners) {
                   8495:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8496:                                             $delcoowners,@newcoowners);
                   8497:                         }
                   8498:                     }
                   8499:                 }
                   8500:             }
                   8501:         }
                   8502:     }
                   8503: }
                   8504: 
                   8505: sub store_coowners {
                   8506:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8507:     my $cid = $cdom.'_'.$cnum;
                   8508:     my ($coowners,$delresult,$putresult);
                   8509:     if (@newcoowners) {
                   8510:         $coowners = join(',',@newcoowners);
                   8511:         my %coownershash = (
                   8512:                             'internal.co-owners' => $coowners,
                   8513:                            );
                   8514:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8515:         if ($putresult eq 'ok') {
                   8516:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8517:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8518:             }
                   8519:         }
                   8520:     }
                   8521:     if ($delcoowners) {
                   8522:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8523:         if ($delresult eq 'ok') {
                   8524:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8525:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8526:             }
                   8527:         }
                   8528:     }
                   8529:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8530:         my %crsinfo =
                   8531:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8532:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8533:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8534:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8535:         }
                   8536:     }
                   8537: }
                   8538: 
1.169     harris41 8539: # -------------------------------------------------- Modify user authentication
1.197     www      8540: # Overrides without validation
                   8541: 
1.169     harris41 8542: sub modifyuserauth {
                   8543:     my ($udom,$uname,$umode,$upass)=@_;
                   8544:     my $uhome=&homeserver($uname,$udom);
1.197     www      8545:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8546:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8547:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8548:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8549:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8550: 		     &escape($upass),$uhome);
1.620     albertel 8551:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8552:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8553:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8554:     &log($udom,,$uname,$uhome,
1.620     albertel 8555:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8556:                                      $env{'user.name'}.', '.$umode.
1.197     www      8557:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8558:     unless ($reply eq 'ok') {
1.197     www      8559:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8560: 	return 'error: '.$reply;
                   8561:     }   
1.170     harris41 8562:     return 'ok';
1.80      www      8563: }
                   8564: 
1.81      www      8565: # --------------------------------------------------------------- Modify a user
1.80      www      8566: 
1.81      www      8567: sub modifyuser {
1.206     matthew  8568:     my ($udom,    $uname, $uid,
                   8569:         $umode,   $upass, $first,
                   8570:         $middle,  $last,  $gene,
1.1058    raeburn  8571:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8572:     $udom= &LONCAPA::clean_domain($udom);
                   8573:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8574:     my $showcandelete = 'none';
                   8575:     if (ref($candelete) eq 'ARRAY') {
                   8576:         if (@{$candelete} > 0) {
                   8577:             $showcandelete = join(', ',@{$candelete});
                   8578:         }
                   8579:     }
1.81      www      8580:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8581:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8582: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8583:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8584:                                      ' desiredhome not specified'). 
1.620     albertel 8585:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8586:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8587:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8588:     my $newuser;
                   8589:     if ($uhome eq 'no_host') {
                   8590:         $newuser = 1;
                   8591:     }
1.80      www      8592: # ----------------------------------------------------------------- Create User
1.406     albertel 8593:     if (($uhome eq 'no_host') && 
                   8594: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8595:         my $unhome='';
1.844     albertel 8596:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8597:             $unhome = $desiredhome;
1.620     albertel 8598: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8599: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8600:         } else { # load balancing routine for determining $unhome
1.81      www      8601:             my $loadm=10000000;
1.841     albertel 8602: 	    my %servers = &get_servers($udom,'library');
                   8603: 	    foreach my $tryserver (keys(%servers)) {
                   8604: 		my $answer=reply('load',$tryserver);
                   8605: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8606: 		    $loadm=$answer;
                   8607: 		    $unhome=$tryserver;
                   8608: 		}
1.80      www      8609: 	    }
                   8610:         }
                   8611:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8612: 	    return 'error: unable to find a home server for '.$uname.
                   8613:                    ' in domain '.$udom;
1.80      www      8614:         }
                   8615:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8616:                          &escape($upass),$unhome);
                   8617: 	unless ($reply eq 'ok') {
                   8618:             return 'error: '.$reply;
                   8619:         }   
1.230     stredwic 8620:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8621:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8622: 	    return 'error: unable verify users home machine.';
1.80      www      8623:         }
1.209     matthew  8624:     }   # End of creation of new user
1.80      www      8625: # ---------------------------------------------------------------------- Add ID
                   8626:     if ($uid) {
                   8627:        $uid=~tr/A-Z/a-z/;
                   8628:        my %uidhash=&idrget($udom,$uname);
1.196     www      8629:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8630:          && (!$forceid)) {
1.80      www      8631: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8632: 	      return 'error: user id "'.$uid.'" does not match '.
                   8633:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8634:           }
                   8635:        } else {
                   8636: 	  &idput($udom,($uname => $uid));
                   8637:        }
                   8638:     }
                   8639: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8640:     my @tmp=&get('environment',
1.899     raeburn  8641: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8642:                     'permanentemail','inststatus'],
1.134     albertel 8643: 		   $udom,$uname);
1.1075    raeburn  8644:     my (%names,%oldnames);
1.313     matthew  8645:     if ($tmp[0] =~ m/^error:.*/) { 
                   8646:         %names=(); 
                   8647:     } else {
                   8648:         %names = @tmp;
1.1075    raeburn  8649:         %oldnames = %names;
1.313     matthew  8650:     }
1.388     www      8651: #
1.1058    raeburn  8652: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8653: # of users did not contain them), do not overwrite existing values
                   8654: # unless field is in $candelete array ref.  
                   8655: #
                   8656: 
                   8657:     my @fields = ('firstname','middlename','lastname','generation',
                   8658:                   'permanentemail','id');
                   8659:     my %newvalues;
                   8660:     if (ref($candelete) eq 'ARRAY') {
                   8661:         foreach my $field (@fields) {
                   8662:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8663:                 if ($field eq 'firstname') {
                   8664:                     $names{$field} = $first;
                   8665:                 } elsif ($field eq 'middlename') {
                   8666:                     $names{$field} = $middle;
                   8667:                 } elsif ($field eq 'lastname') {
                   8668:                     $names{$field} = $last;
                   8669:                 } elsif ($field eq 'generation') { 
                   8670:                     $names{$field} = $gene;
                   8671:                 } elsif ($field eq 'permanentemail') {
                   8672:                     $names{$field} = $email;
                   8673:                 } elsif ($field eq 'id') {
                   8674:                     $names{$field}  = $uid;
                   8675:                 }
                   8676:             }
                   8677:         }
                   8678:     }
1.388     www      8679:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  8680:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      8681:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  8682:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      8683:     if ($email) {
                   8684:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  8685:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      8686:     }
1.899     raeburn  8687:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  8688:     if (defined($inststatus)) {
                   8689:         $names{'inststatus'} = '';
                   8690:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   8691:         if (ref($usertypes) eq 'HASH') {
                   8692:             my @okstatuses; 
                   8693:             foreach my $item (split(/:/,$inststatus)) {
                   8694:                 if (defined($usertypes->{$item})) {
                   8695:                     push(@okstatuses,$item);  
                   8696:                 }
                   8697:             }
                   8698:             if (@okstatuses) {
                   8699:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   8700:             }
                   8701:         }
                   8702:     }
1.1075    raeburn  8703:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  8704:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  8705:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  8706:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   8707:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   8708:     } else {
                   8709:         $logmsg .= ' during self creation';
                   8710:     }
1.1075    raeburn  8711:     my $changed;
                   8712:     if ($newuser) {
                   8713:         $changed = 1;
                   8714:     } else {
                   8715:         foreach my $field (@fields) {
                   8716:             if ($names{$field} ne $oldnames{$field}) {
                   8717:                 $changed = 1;
                   8718:                 last;
                   8719:             }
                   8720:         }
                   8721:     }
                   8722:     unless ($changed) {
                   8723:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   8724:         &logthis($logmsg);
                   8725:         return 'ok';
                   8726:     }
                   8727:     my $reply = &put('environment', \%names, $udom,$uname);
                   8728:     if ($reply ne 'ok') { 
                   8729:         return 'error: '.$reply;
                   8730:     }
1.1087    raeburn  8731:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   8732:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   8733:     }
1.1075    raeburn  8734:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   8735:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   8736:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  8737:     &logthis($logmsg);
1.134     albertel 8738:     return 'ok';
1.80      www      8739: }
                   8740: 
1.81      www      8741: # -------------------------------------------------------------- Modify student
1.80      www      8742: 
1.81      www      8743: sub modifystudent {
                   8744:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  8745:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.19  raeburn  8746:         $selfenroll,$context,$inststatus,$credits)=@_;
1.455     albertel 8747:     if (!$cid) {
1.620     albertel 8748: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8749: 	    return 'not_in_class';
                   8750: 	}
1.80      www      8751:     }
                   8752: # --------------------------------------------------------------- Make the user
1.81      www      8753:     my $reply=&modifyuser
1.209     matthew  8754: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  8755:          $desiredhome,$email,$inststatus);
1.80      www      8756:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  8757:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  8758:     # student's environment
1.297     matthew  8759:     $uid = undef if (!$forceid);
1.455     albertel 8760:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  8761: 					$gene,$usec,$end,$start,$type,$locktype,
                   8762:                                         $cid,$selfenroll,$context,$credits);
1.297     matthew  8763:     return $reply;
                   8764: }
                   8765: 
                   8766: sub modify_student_enrollment {
1.1172.2.23  raeburn  8767:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
                   8768:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455     albertel 8769:     my ($cdom,$cnum,$chome);
                   8770:     if (!$cid) {
1.620     albertel 8771: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8772: 	    return 'not_in_class';
                   8773: 	}
1.620     albertel 8774: 	$cdom=$env{'course.'.$cid.'.domain'};
                   8775: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 8776:     } else {
                   8777: 	($cdom,$cnum)=split(/_/,$cid);
                   8778:     }
1.620     albertel 8779:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 8780:     if (!$chome) {
1.457     raeburn  8781: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  8782:     }
1.455     albertel 8783:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  8784:     # Make sure the user exists
1.81      www      8785:     my $uhome=&homeserver($uname,$udom);
                   8786:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8787: 	return 'error: no such user';
                   8788:     }
1.297     matthew  8789:     # Get student data if we were not given enough information
                   8790:     if (!defined($first)  || $first  eq '' || 
                   8791:         !defined($last)   || $last   eq '' || 
                   8792:         !defined($uid)    || $uid    eq '' || 
                   8793:         !defined($middle) || $middle eq '' || 
                   8794:         !defined($gene)   || $gene   eq '') {
1.294     matthew  8795:         # They did not supply us with enough data to enroll the student, so
                   8796:         # we need to pick up more information.
1.297     matthew  8797:         my %tmp = &get('environment',
1.294     matthew  8798:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  8799:                        ,$udom,$uname);
                   8800: 
1.800     albertel 8801:         #foreach my $key (keys(%tmp)) {
                   8802:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 8803:         #}
1.294     matthew  8804:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   8805:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   8806:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  8807:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  8808:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   8809:     }
1.556     albertel 8810:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  8811:     my $user = "$uname:$udom";
                   8812:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 8813:     my $reply=cput('classlist',
1.1148    raeburn  8814: 		   {$user => 
1.1172.2.19  raeburn  8815: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487     albertel 8816: 		   $cdom,$cnum);
1.1148    raeburn  8817:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   8818:         &devalidate_getsection_cache($udom,$uname,$cid);
                   8819:     } else { 
1.81      www      8820: 	return 'error: '.$reply;
                   8821:     }
1.297     matthew  8822:     # Add student role to user
1.83      www      8823:     my $uurl='/'.$cid;
1.81      www      8824:     $uurl=~s/\_/\//g;
                   8825:     if ($usec) {
                   8826: 	$uurl.='/'.$usec;
                   8827:     }
1.1148    raeburn  8828:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   8829:                              $selfenroll,$context);
                   8830:     if ($result ne 'ok') {
                   8831:         if ($old_entry{$user} ne '') {
                   8832:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   8833:         } else {
                   8834:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   8835:         }
                   8836:     }
                   8837:     return $result; 
1.21      www      8838: }
                   8839: 
1.556     albertel 8840: sub format_name {
                   8841:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   8842:     my $name;
                   8843:     if ($first ne 'lastname') {
                   8844: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   8845:     } else {
                   8846: 	if ($lastname=~/\S/) {
                   8847: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   8848: 	    $name=~s/\s+,/,/;
                   8849: 	} else {
                   8850: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   8851: 	}
                   8852:     }
                   8853:     $name=~s/^\s+//;
                   8854:     $name=~s/\s+$//;
                   8855:     $name=~s/\s+/ /g;
                   8856:     return $name;
                   8857: }
                   8858: 
1.84      www      8859: # ------------------------------------------------- Write to course preferences
                   8860: 
                   8861: sub writecoursepref {
                   8862:     my ($courseid,%prefs)=@_;
                   8863:     $courseid=~s/^\///;
                   8864:     $courseid=~s/\_/\//g;
                   8865:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   8866:     my $chome=homeserver($cnum,$cdomain);
                   8867:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   8868: 	return 'error: no such course';
                   8869:     }
                   8870:     my $cstring='';
1.800     albertel 8871:     foreach my $pref (keys(%prefs)) {
                   8872: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 8873:     }
1.84      www      8874:     $cstring=~s/\&$//;
                   8875:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   8876: }
                   8877: 
                   8878: # ---------------------------------------------------------- Make/modify course
                   8879: 
                   8880: sub createcourse {
1.741     raeburn  8881:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  8882:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      8883:     $url=&declutter($url);
                   8884:     my $cid='';
1.1028    raeburn  8885:     if ($context eq 'requestcourses') {
                   8886:         my $can_create = 0;
                   8887:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   8888:         if ($udom eq $ownerdom) {
                   8889:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   8890:                                   $context)) {
                   8891:                 $can_create = 1;
                   8892:             }
                   8893:         } else {
                   8894:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   8895:                                            $category);
                   8896:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   8897:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   8898:                 if (@curr > 0) {
                   8899:                     my @options = qw(approval validate autolimit);
                   8900:                     my $optregex = join('|',@options);
                   8901:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   8902:                         $can_create = 1;
                   8903:                     }
                   8904:                 }
                   8905:             }
                   8906:         }
                   8907:         if ($can_create) {
                   8908:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   8909:                 unless (&allowed('ccc',$udom)) {
                   8910:                     return 'refused'; 
                   8911:                 }
1.1017    raeburn  8912:             }
                   8913:         } else {
                   8914:             return 'refused';
                   8915:         }
1.1028    raeburn  8916:     } elsif (!&allowed('ccc',$udom)) {
                   8917:         return 'refused';
1.84      www      8918:     }
1.1011    raeburn  8919: # --------------------------------------------------------------- Get Unique ID
                   8920:     my $uname;
                   8921:     if ($cnum =~ /^$match_courseid$/) {
                   8922:         my $chome=&homeserver($cnum,$udom,'true');
                   8923:         if (($chome eq '') || ($chome eq 'no_host')) {
                   8924:             $uname = $cnum;
                   8925:         } else {
1.1038    raeburn  8926:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8927:         }
                   8928:     } else {
1.1038    raeburn  8929:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8930:     }
                   8931:     return $uname if ($uname =~ /^error/);
                   8932: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  8933:     if (!defined($course_server)) {
                   8934:         if (defined(&domain($udom,'primary'))) {
                   8935:             $course_server = &domain($udom,'primary');
                   8936:         } else {
                   8937:             $course_server = $env{'user.home'}; 
                   8938:         }
                   8939:     }
                   8940:     my %host_servers =
                   8941:         &Apache::lonnet::get_servers($udom,'library');
                   8942:     unless ($host_servers{$course_server}) {
                   8943:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  8944:     }
1.84      www      8945: # ------------------------------------------------------------- Make the course
                   8946:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  8947:                       $course_server);
1.84      www      8948:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  8949:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      8950:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8951: 	return 'error: no such course';
                   8952:     }
1.271     www      8953: # ----------------------------------------------------------------- Course made
1.516     raeburn  8954: # log existence
1.1029    raeburn  8955:     my $now = time;
1.918     raeburn  8956:     my $newcourse = {
                   8957:                     $udom.'_'.$uname => {
1.921     raeburn  8958:                                      description => $description,
                   8959:                                      inst_code   => $inst_code,
                   8960:                                      owner       => $course_owner,
                   8961:                                      type        => $crstype,
1.1029    raeburn  8962:                                      creator     => $env{'user.name'}.':'.
                   8963:                                                     $env{'user.domain'},
                   8964:                                      created     => $now,
                   8965:                                      context     => $context,
1.918     raeburn  8966:                                                 },
                   8967:                     };
1.921     raeburn  8968:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      8969: # set toplevel url
1.271     www      8970:     my $topurl=$url;
                   8971:     unless ($nonstandard) {
                   8972: # ------------------------------------------ For standard courses, make top url
                   8973:         my $mapurl=&clutter($url);
1.278     www      8974:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 8975:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      8976: <map>
                   8977: <resource id="1" type="start"></resource>
                   8978: <resource id="2" src="$mapurl"></resource>
                   8979: <resource id="3" type="finish"></resource>
                   8980: <link index="1" from="1" to="2"></link>
                   8981: <link index="2" from="2" to="3"></link>
                   8982: </map>
                   8983: ENDINITMAP
                   8984:         $topurl=&declutter(
1.638     albertel 8985:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      8986:                           );
                   8987:     }
                   8988: # ----------------------------------------------------------- Write preferences
1.84      www      8989:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  8990:                      ('description'              => $description,
                   8991:                       'url'                      => $topurl,
                   8992:                       'internal.creator'         => $env{'user.name'}.':'.
                   8993:                                                     $env{'user.domain'},
                   8994:                       'internal.created'         => $now,
                   8995:                       'internal.creationcontext' => $context)
                   8996:                     );
1.84      www      8997:     return '/'.$udom.'/'.$uname;
                   8998: }
                   8999: 
1.1011    raeburn  9000: # ------------------------------------------------------------------- Create ID
                   9001: sub generate_coursenum {
1.1038    raeburn  9002:     my ($udom,$crstype) = @_;
1.1011    raeburn  9003:     my $domdesc = &domain($udom);
                   9004:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  9005:     my $first;
                   9006:     if ($crstype eq 'Community') {
                   9007:         $first = '0';
                   9008:     } else {
                   9009:         $first = int(1+rand(9)); 
                   9010:     } 
                   9011:     my $uname=$first.
1.1011    raeburn  9012:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9013:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9014:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9015: # ----------------------------------------------- Make sure that does not exist
                   9016:     my $uhome=&homeserver($uname,$udom,'true');
                   9017:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  9018:         if ($crstype eq 'Community') {
                   9019:             $first = '0';
                   9020:         } else {
                   9021:             $first = int(1+rand(9));
                   9022:         }
                   9023:         $uname=$first.
1.1011    raeburn  9024:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9025:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9026:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9027:         $uhome=&homeserver($uname,$udom,'true');
                   9028:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   9029:             return 'error: unable to generate unique course-ID';
                   9030:         }
                   9031:     }
                   9032:     return $uname;
                   9033: }
                   9034: 
1.813     albertel 9035: sub is_course {
1.1167    droeschl 9036:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   9037:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   9038: 
                   9039:     return unless $cdom and $cnum;
                   9040: 
                   9041:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   9042:         '.');
                   9043: 
1.1172.2.23  raeburn  9044:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 9045:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 9046: }
                   9047: 
1.1015    raeburn  9048: sub store_userdata {
                   9049:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  9050:     my $result;
1.1016    raeburn  9051:     if ($datakey ne '') {
1.1013    raeburn  9052:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  9053:             if ($udom eq '' || $uname eq '') {
                   9054:                 $udom = $env{'user.domain'};
                   9055:                 $uname = $env{'user.name'};
                   9056:             }
                   9057:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  9058:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   9059:                 $result = 'error: no_host';
                   9060:             } else {
                   9061:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   9062:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   9063: 
                   9064:                 my $namevalue='';
                   9065:                 foreach my $key (keys(%{$storehash})) {
                   9066:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   9067:                 }
                   9068:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  9069:                 unless ($namespace eq 'courserequests') {
                   9070:                     $datakey = &escape($datakey);
                   9071:                 }
1.1105    raeburn  9072:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   9073:                                   $namevalue,$uhome);
1.1013    raeburn  9074:             }
                   9075:         } else {
                   9076:             $result = 'error: data to store was not a hash reference'; 
                   9077:         }
                   9078:     } else {
                   9079:         $result= 'error: invalid requestkey'; 
                   9080:     }
                   9081:     return $result;
                   9082: }
                   9083: 
1.21      www      9084: # ---------------------------------------------------------- Assign Custom Role
                   9085: 
                   9086: sub assigncustomrole {
1.957     raeburn  9087:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9088:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  9089:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      9090: }
                   9091: 
                   9092: # ----------------------------------------------------------------- Revoke Role
                   9093: 
                   9094: sub revokerole {
1.957     raeburn  9095:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9096:     my $now=time;
1.965     raeburn  9097:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      9098: }
                   9099: 
                   9100: # ---------------------------------------------------------- Revoke Custom Role
                   9101: 
                   9102: sub revokecustomrole {
1.957     raeburn  9103:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9104:     my $now=time;
1.357     www      9105:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  9106:            $deleteflag,$selfenroll,$context);
1.17      www      9107: }
                   9108: 
1.533     banghart 9109: # ------------------------------------------------------------ Disk usage
1.535     albertel 9110: sub diskusage {
1.955     raeburn  9111:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   9112:     $directorypath =~ s/\/$//;
                   9113:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   9114:                        .&escape($getpropath).':'.&escape($uname).':'
                   9115:                        .&escape($udom),homeserver($uname,$udom));
                   9116:     if ($listing eq 'unknown_cmd') {
                   9117:         if ($getpropath) {
                   9118:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   9119:         }
                   9120:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   9121:     }
1.514     albertel 9122:     return $listing;
1.512     banghart 9123: }
                   9124: 
1.566     banghart 9125: sub is_locked {
1.1096    raeburn  9126:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 9127:     my @check;
                   9128:     my $is_locked;
1.1093    raeburn  9129:     push (@check,$file_name);
1.613     albertel 9130:     my %locked = &get('file_permissions',\@check,
1.620     albertel 9131: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 9132:     my ($tmp)=keys(%locked);
                   9133:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  9134:     
1.566     banghart 9135:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  9136:         $is_locked = 'false';
                   9137:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  9138:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  9139:                $is_locked = 'true';
1.1096    raeburn  9140:                if (ref($which) eq 'ARRAY') {
                   9141:                    push(@{$which},$entry);
                   9142:                } else {
                   9143:                    last;
                   9144:                }
1.745     raeburn  9145:            }
                   9146:        }
1.566     banghart 9147:     } else {
                   9148:         $is_locked = 'false';
                   9149:     }
1.1093    raeburn  9150:     return $is_locked;
1.566     banghart 9151: }
                   9152: 
1.759     albertel 9153: sub declutter_portfile {
                   9154:     my ($file) = @_;
1.833     albertel 9155:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 9156:     return $file;
                   9157: }
                   9158: 
1.559     banghart 9159: # ------------------------------------------------------------- Mark as Read Only
                   9160: 
                   9161: sub mark_as_readonly {
                   9162:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 9163:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9164:     my ($tmp)=keys(%current_permissions);
                   9165:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 9166:     foreach my $file (@{$files}) {
1.759     albertel 9167: 	$file = &declutter_portfile($file);
1.561     banghart 9168:         push(@{$current_permissions{$file}},$what);
1.559     banghart 9169:     }
1.613     albertel 9170:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9171:     return;
                   9172: }
                   9173: 
1.572     banghart 9174: # ------------------------------------------------------------Save Selected Files
                   9175: 
                   9176: sub save_selected_files {
                   9177:     my ($user, $path, @files) = @_;
                   9178:     my $filename = $user."savedfiles";
1.573     banghart 9179:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 9180:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 9181:     foreach my $file (@files) {
1.620     albertel 9182:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 9183:     }
                   9184:     foreach my $file (@other_files) {
1.574     banghart 9185:         print (OUT $file."\n");
1.572     banghart 9186:     }
1.574     banghart 9187:     close (OUT);
1.572     banghart 9188:     return 'ok';
                   9189: }
                   9190: 
1.574     banghart 9191: sub clear_selected_files {
                   9192:     my ($user) = @_;
                   9193:     my $filename = $user."savedfiles";
1.1117    foxr     9194:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 9195:     print (OUT undef);
                   9196:     close (OUT);
                   9197:     return ("ok");    
                   9198: }
                   9199: 
1.572     banghart 9200: sub files_in_path {
                   9201:     my ($user, $path) = @_;
                   9202:     my $filename = $user."savedfiles";
                   9203:     my %return_files;
1.1117    foxr     9204:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 9205:     while (my $line_in = <IN>) {
1.574     banghart 9206:         chomp ($line_in);
                   9207:         my @paths_and_file = split (m!/!, $line_in);
                   9208:         my $file_part = pop (@paths_and_file);
                   9209:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9210:         $path_part.='/';
                   9211:         my $path_and_file = $path_part.$file_part;
                   9212:         if ($path_part eq $path) {
                   9213:             $return_files{$file_part}= 'selected';
                   9214:         }
                   9215:     }
1.574     banghart 9216:     close (IN);
                   9217:     return (\%return_files);
1.572     banghart 9218: }
                   9219: 
                   9220: # called in portfolio select mode, to show files selected NOT in current directory
                   9221: sub files_not_in_path {
                   9222:     my ($user, $path) = @_;
                   9223:     my $filename = $user."savedfiles";
                   9224:     my @return_files;
                   9225:     my $path_part;
1.1117    foxr     9226:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 9227:     while (my $line = <IN>) {
1.572     banghart 9228:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9229:         my @paths_and_file = split(m|/|, $line);
                   9230:         my $file_part = pop(@paths_and_file);
                   9231:         chomp($file_part);
                   9232:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9233:         $path_part .= '/';
                   9234:         my $path_and_file = $path_part.$file_part;
                   9235:         if ($path_part ne $path) {
1.800     albertel 9236:             push(@return_files, ($path_and_file));
1.572     banghart 9237:         }
                   9238:     }
1.800     albertel 9239:     close(OUT);
1.574     banghart 9240:     return (@return_files);
1.572     banghart 9241: }
                   9242: 
1.745     raeburn  9243: #----------------------------------------------Get portfolio file permissions
1.629     banghart 9244: 
1.745     raeburn  9245: sub get_portfile_permissions {
                   9246:     my ($domain,$user) = @_;
1.613     albertel 9247:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9248:     my ($tmp)=keys(%current_permissions);
                   9249:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9250:     return \%current_permissions;
                   9251: }
                   9252: 
                   9253: #---------------------------------------------Get portfolio file access controls
                   9254: 
1.749     raeburn  9255: sub get_access_controls {
1.745     raeburn  9256:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 9257:     my %access;
                   9258:     my $real_file = $file;
                   9259:     $file =~ s/\.meta$//;
1.745     raeburn  9260:     if (defined($file)) {
1.749     raeburn  9261:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   9262:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 9263:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  9264:             }
                   9265:         }
1.745     raeburn  9266:     } else {
1.749     raeburn  9267:         foreach my $key (keys(%{$current_permissions})) {
                   9268:             if ($key =~ /\0accesscontrol$/) {
                   9269:                 if (defined($group)) {
                   9270:                     if ($key !~ m-^\Q$group\E/-) {
                   9271:                         next;
                   9272:                     }
                   9273:                 }
                   9274:                 my ($fullpath) = split(/\0/,$key);
                   9275:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   9276:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   9277:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   9278:                     }
                   9279:                 }
                   9280:             }
                   9281:         }
                   9282:     }
                   9283:     return %access;
                   9284: }
                   9285: 
                   9286: sub modify_access_controls {
                   9287:     my ($file_name,$changes,$domain,$user)=@_;
                   9288:     my ($outcome,$deloutcome);
                   9289:     my %store_permissions;
                   9290:     my %new_values;
                   9291:     my %new_control;
                   9292:     my %translation;
                   9293:     my @deletions = ();
                   9294:     my $now = time;
                   9295:     if (exists($$changes{'activate'})) {
                   9296:         if (ref($$changes{'activate'}) eq 'HASH') {
                   9297:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   9298:             my $numnew = scalar(@newitems);
                   9299:             for (my $i=0; $i<$numnew; $i++) {
                   9300:                 my $newkey = $newitems[$i];
                   9301:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  9302:                 if ($newkey =~ /^\d+:/) { 
                   9303:                     $newkey =~ s/^(\d+)/$newid/;
                   9304:                     $translation{$1} = $newid;
                   9305:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   9306:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   9307:                     $translation{$1} = $newid;
                   9308:                 }
1.749     raeburn  9309:                 $new_values{$file_name."\0".$newkey} = 
                   9310:                                           $$changes{'activate'}{$newitems[$i]};
                   9311:                 $new_control{$newkey} = $now;
                   9312:             }
                   9313:         }
                   9314:     }
                   9315:     my %todelete;
                   9316:     my %changed_items;
                   9317:     foreach my $action ('delete','update') {
                   9318:         if (exists($$changes{$action})) {
                   9319:             if (ref($$changes{$action}) eq 'HASH') {
                   9320:                 foreach my $key (keys(%{$$changes{$action}})) {
                   9321:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   9322:                     if ($action eq 'delete') { 
                   9323:                         $todelete{$itemnum} = 1;
                   9324:                     } else {
                   9325:                         $changed_items{$itemnum} = $key;
                   9326:                     }
                   9327:                 }
1.745     raeburn  9328:             }
                   9329:         }
1.749     raeburn  9330:     }
                   9331:     # get lock on access controls for file.
                   9332:     my $lockhash = {
                   9333:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   9334:                                                        ':'.$env{'user.domain'},
                   9335:                    }; 
                   9336:     my $tries = 0;
                   9337:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9338:    
                   9339:     while (($gotlock ne 'ok') && $tries <3) {
                   9340:         $tries ++;
                   9341:         sleep 1;
                   9342:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9343:     }
                   9344:     if ($gotlock eq 'ok') {
                   9345:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   9346:         my ($tmp)=keys(%curr_permissions);
                   9347:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   9348:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   9349:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   9350:             if (ref($curr_controls) eq 'HASH') {
                   9351:                 foreach my $control_item (keys(%{$curr_controls})) {
                   9352:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   9353:                     if (defined($todelete{$itemnum})) {
                   9354:                         push(@deletions,$file_name."\0".$control_item);
                   9355:                     } else {
                   9356:                         if (defined($changed_items{$itemnum})) {
                   9357:                             $new_control{$changed_items{$itemnum}} = $now;
                   9358:                             push(@deletions,$file_name."\0".$control_item);
                   9359:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   9360:                         } else {
                   9361:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   9362:                         }
                   9363:                     }
1.745     raeburn  9364:                 }
                   9365:             }
                   9366:         }
1.970     raeburn  9367:         my ($group);
                   9368:         if (&is_course($domain,$user)) {
                   9369:             ($group,my $file) = split(/\//,$file_name,2);
                   9370:         }
1.749     raeburn  9371:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   9372:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   9373:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   9374:         #  remove lock
                   9375:         my @del_lock = ($file_name."\0".'locked_access_records');
                   9376:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9377:         my $sqlresult =
1.970     raeburn  9378:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9379:                                     $group);
1.749     raeburn  9380:     } else {
                   9381:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9382:     }
1.749     raeburn  9383:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9384: }
                   9385: 
1.827     raeburn  9386: sub make_public_indefinitely {
                   9387:     my ($requrl) = @_;
                   9388:     my $now = time;
                   9389:     my $action = 'activate';
                   9390:     my $aclnum = 0;
                   9391:     if (&is_portfolio_url($requrl)) {
                   9392:         my (undef,$udom,$unum,$file_name,$group) =
                   9393:             &parse_portfolio_url($requrl);
                   9394:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   9395:         my %access_controls = &get_access_controls($current_perms,
                   9396:                                                    $group,$file_name);
                   9397:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9398:             my ($num,$scope,$end,$start) = 
                   9399:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   9400:             if ($scope eq 'public') {
                   9401:                 if ($start <= $now && $end == 0) {
                   9402:                     $action = 'none';
                   9403:                 } else {
                   9404:                     $action = 'update';
                   9405:                     $aclnum = $num;
                   9406:                 }
                   9407:                 last;
                   9408:             }
                   9409:         }
                   9410:         if ($action eq 'none') {
                   9411:              return 'ok';
                   9412:         } else {
                   9413:             my %changes;
                   9414:             my $newend = 0;
                   9415:             my $newstart = $now;
                   9416:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   9417:             $changes{$action}{$newkey} = {
                   9418:                 type => 'public',
                   9419:                 time => {
                   9420:                     start => $newstart,
                   9421:                     end   => $newend,
                   9422:                 },
                   9423:             };
                   9424:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9425:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   9426:             return $outcome;
                   9427:         }
                   9428:     } else {
                   9429:         return 'invalid';
                   9430:     }
                   9431: }
                   9432: 
1.745     raeburn  9433: #------------------------------------------------------Get Marked as Read Only
                   9434: 
                   9435: sub get_marked_as_readonly {
                   9436:     my ($domain,$user,$what,$group) = @_;
                   9437:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 9438:     my @readonly_files;
1.629     banghart 9439:     my $cmp1=$what;
                   9440:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  9441:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9442:         if (defined($group)) {
                   9443:             if ($file_name !~ m-^\Q$group\E/-) {
                   9444:                 next;
                   9445:             }
                   9446:         }
1.561     banghart 9447:         if (ref($value) eq "ARRAY"){
                   9448:             foreach my $stored_what (@{$value}) {
1.629     banghart 9449:                 my $cmp2=$stored_what;
1.759     albertel 9450:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  9451:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  9452:                 }
1.629     banghart 9453:                 if ($cmp1 eq $cmp2) {
1.561     banghart 9454:                     push(@readonly_files, $file_name);
1.745     raeburn  9455:                     last;
1.563     banghart 9456:                 } elsif (!defined($what)) {
                   9457:                     push(@readonly_files, $file_name);
1.745     raeburn  9458:                     last;
1.561     banghart 9459:                 }
                   9460:             }
1.745     raeburn  9461:         }
1.561     banghart 9462:     }
                   9463:     return @readonly_files;
                   9464: }
1.577     banghart 9465: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 9466: 
1.577     banghart 9467: sub get_marked_as_readonly_hash {
1.745     raeburn  9468:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 9469:     my %readonly_files;
1.745     raeburn  9470:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9471:         if (defined($group)) {
                   9472:             if ($file_name !~ m-^\Q$group\E/-) {
                   9473:                 next;
                   9474:             }
                   9475:         }
1.577     banghart 9476:         if (ref($value) eq "ARRAY"){
                   9477:             foreach my $stored_what (@{$value}) {
1.745     raeburn  9478:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 9479:                     foreach my $lock_descriptor(@{$stored_what}) {
                   9480:                         if ($lock_descriptor eq 'graded') {
                   9481:                             $readonly_files{$file_name} = 'graded';
                   9482:                         } elsif ($lock_descriptor eq 'handback') {
                   9483:                             $readonly_files{$file_name} = 'handback';
                   9484:                         } else {
                   9485:                             if (!exists($readonly_files{$file_name})) {
                   9486:                                 $readonly_files{$file_name} = 'locked';
                   9487:                             }
                   9488:                         }
1.745     raeburn  9489:                     }
1.750     banghart 9490:                 } 
1.577     banghart 9491:             }
                   9492:         } 
                   9493:     }
                   9494:     return %readonly_files;
                   9495: }
1.559     banghart 9496: # ------------------------------------------------------------ Unmark as Read Only
                   9497: 
                   9498: sub unmark_as_readonly {
1.629     banghart 9499:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   9500:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  9501:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 9502:     $file_name = &declutter_portfile($file_name);
1.634     albertel 9503:     my $symb_crs = $what;
                   9504:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  9505:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 9506:     my ($tmp)=keys(%current_permissions);
                   9507:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9508:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 9509:     foreach my $file (@readonly_files) {
1.759     albertel 9510: 	my $clean_file = &declutter_portfile($file);
                   9511: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 9512: 	my $current_locks = $current_permissions{$file};
1.563     banghart 9513:         my @new_locks;
                   9514:         my @del_keys;
                   9515:         if (ref($current_locks) eq "ARRAY"){
                   9516:             foreach my $locker (@{$current_locks}) {
1.632     albertel 9517:                 my $compare=$locker;
1.749     raeburn  9518:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  9519:                     $compare=join('',@{$locker});
1.746     raeburn  9520:                     if ($compare ne $symb_crs) {
                   9521:                         push(@new_locks, $locker);
                   9522:                     }
1.563     banghart 9523:                 }
                   9524:             }
1.650     albertel 9525:             if (scalar(@new_locks) > 0) {
1.563     banghart 9526:                 $current_permissions{$file} = \@new_locks;
                   9527:             } else {
                   9528:                 push(@del_keys, $file);
1.613     albertel 9529:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 9530:                 delete($current_permissions{$file});
1.563     banghart 9531:             }
                   9532:         }
1.561     banghart 9533:     }
1.613     albertel 9534:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9535:     return;
                   9536: }
1.512     banghart 9537: 
1.17      www      9538: # ------------------------------------------------------------ Directory lister
                   9539: 
                   9540: sub dirlist {
1.955     raeburn  9541:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      9542:     $uri=~s/^\///;
                   9543:     $uri=~s/\/$//;
1.253     stredwic 9544:     my ($udom, $uname);
1.955     raeburn  9545:     if ($getuserdir) {
1.253     stredwic 9546:         $udom = $userdomain;
                   9547:         $uname = $username;
1.955     raeburn  9548:     } else {
                   9549:         (undef,$udom,$uname)=split(/\//,$uri);
                   9550:         if(defined($userdomain)) {
                   9551:             $udom = $userdomain;
                   9552:         }
                   9553:         if(defined($username)) {
                   9554:             $uname = $username;
                   9555:         }
1.253     stredwic 9556:     }
1.955     raeburn  9557:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 9558: 
1.955     raeburn  9559:     $dirRoot = $perlvar{'lonDocRoot'};
                   9560:     if (defined($getpropath)) {
                   9561:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 9562:         $dirRoot =~ s/\/$//;
1.955     raeburn  9563:     } elsif (defined($getuserdir)) {
                   9564:         my $subdir=$uname.'__';
                   9565:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   9566:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   9567:                    ."/$udom/$subdir/$uname";
                   9568:     } elsif (defined($alternateRoot)) {
                   9569:         $dirRoot = $alternateRoot;
1.751     banghart 9570:     }
1.253     stredwic 9571: 
                   9572:     if($udom) {
                   9573:         if($uname) {
1.1135    raeburn  9574:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  9575:             if ($uhome eq 'no_host') {
                   9576:                 return ([],'no_host');
                   9577:             }
1.955     raeburn  9578:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  9579:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  9580:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  9581:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9582:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  9583:             } else {
                   9584:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9585:             }
1.605     matthew  9586:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9587:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  9588:                 @listing_results = split(/:/,$listing);
                   9589:             } else {
                   9590:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9591:             }
1.1135    raeburn  9592:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  9593:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9594:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9595:                 return ([],$listing);
                   9596:             } else {
                   9597:                 return (\@listing_results);
1.1135    raeburn  9598:             }
1.955     raeburn  9599:         } elsif(!$alternateRoot) {
1.1136    raeburn  9600:             my (%allusers,%listerror);
1.841     albertel 9601: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  9602:  	    foreach my $tryserver (keys(%servers)) {
                   9603:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   9604:                                   &escape($udom),$tryserver);
                   9605:                 if ($listing eq 'unknown_cmd') {
                   9606: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9607: 				      $udom, $tryserver);
                   9608:                 } else {
                   9609:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9610:                 }
1.841     albertel 9611: 		if ($listing eq 'unknown_cmd') {
                   9612: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9613: 				      $udom, $tryserver);
                   9614: 		    @listing_results = split(/:/,$listing);
                   9615: 		} else {
                   9616: 		    @listing_results =
                   9617: 			map { &unescape($_); } split(/:/,$listing);
                   9618: 		}
1.1136    raeburn  9619:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   9620:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9621:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9622:                     $listerror{$tryserver} = $listing;
                   9623:                 } else {
1.841     albertel 9624: 		    foreach my $line (@listing_results) {
                   9625: 			my ($entry) = split(/&/,$line,2);
                   9626: 			$allusers{$entry} = 1;
                   9627: 		    }
                   9628: 		}
1.253     stredwic 9629:             }
1.1136    raeburn  9630:             my @alluserslist=();
1.800     albertel 9631:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  9632:                 push(@alluserslist,$user.'&user');
1.253     stredwic 9633:             }
1.1136    raeburn  9634:             return (\@alluserslist);
1.253     stredwic 9635:         } else {
1.1136    raeburn  9636:             return ([],'missing username');
1.253     stredwic 9637:         }
1.955     raeburn  9638:     } elsif(!defined($getpropath)) {
1.1136    raeburn  9639:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   9640:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   9641:         return (\@all_domains);
1.955     raeburn  9642:     } else {
1.1136    raeburn  9643:         return ([],'missing domain');
1.275     stredwic 9644:     }
                   9645: }
                   9646: 
                   9647: # --------------------------------------------- GetFileTimestamp
                   9648: # This function utilizes dirlist and returns the date stamp for
                   9649: # when it was last modified.  It will also return an error of -1
                   9650: # if an error occurs
                   9651: 
                   9652: sub GetFileTimestamp {
1.955     raeburn  9653:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 9654:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   9655:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  9656:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   9657:                                     undef,$getuserdir);
                   9658:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9659:         return -1;
                   9660:     }
                   9661:     if (ref($fileref) eq 'ARRAY') {
                   9662:         my @stats = split('&',$fileref->[0]);
1.375     matthew  9663:         # @stats contains first the filename, then the stat output
                   9664:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 9665:     } else {
                   9666:         return -1;
1.253     stredwic 9667:     }
1.26      www      9668: }
                   9669: 
1.712     albertel 9670: sub stat_file {
                   9671:     my ($uri) = @_;
1.787     albertel 9672:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 9673: 
1.955     raeburn  9674:     my ($udom,$uname,$file);
1.712     albertel 9675:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   9676: 	($udom,$uname,$file) =
1.811     albertel 9677: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 9678: 	$file = 'userfiles/'.$file;
                   9679:     }
                   9680:     if ($uri =~ m-^/res/-) {
                   9681: 	($udom,$uname) = 
1.807     albertel 9682: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 9683: 	$file = $uri;
                   9684:     }
                   9685: 
                   9686:     if (!$udom || !$uname || !$file) {
                   9687: 	# unable to handle the uri
                   9688: 	return ();
                   9689:     }
1.956     raeburn  9690:     my $getpropath;
                   9691:     if ($file =~ /^userfiles\//) {
                   9692:         $getpropath = 1;
                   9693:     }
1.1136    raeburn  9694:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   9695:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9696:         return ();
                   9697:     } else {
                   9698:         if (ref($listref) eq 'ARRAY') {
                   9699:             my @stats = split('&',$listref->[0]);
                   9700: 	    shift(@stats); #filename is first
                   9701: 	    return @stats;
                   9702:         }
1.712     albertel 9703:     }
                   9704:     return ();
                   9705: }
                   9706: 
1.26      www      9707: # -------------------------------------------------------- Value of a Condition
                   9708: 
1.713     albertel 9709: # gets the value of a specific preevaluated condition
                   9710: #    stored in the string  $env{user.state.<cid>}
                   9711: # or looks up a condition reference in the bighash and if if hasn't
                   9712: # already been evaluated recurses into docondval to get the value of
                   9713: # the condition, then memoizing it to 
                   9714: #   $env{user.state.<cid>.<condition>}
1.40      www      9715: sub directcondval {
                   9716:     my $number=shift;
1.620     albertel 9717:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 9718: 	&Apache::lonuserstate::evalstate();
                   9719:     }
1.713     albertel 9720:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   9721: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   9722:     } elsif ($number =~ /^_/) {
                   9723: 	my $sub_condition;
                   9724: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9725: 		&GDBM_READER(),0640)) {
                   9726: 	    $sub_condition=$bighash{'conditions'.$number};
                   9727: 	    untie(%bighash);
                   9728: 	}
                   9729: 	my $value = &docondval($sub_condition);
1.949     raeburn  9730: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 9731: 	return $value;
                   9732:     }
1.620     albertel 9733:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   9734:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      9735:     } else {
                   9736:        return 2;
                   9737:     }
                   9738: }
                   9739: 
1.713     albertel 9740: # get the collection of conditions for this resource
1.26      www      9741: sub condval {
                   9742:     my $condidx=shift;
1.54      www      9743:     my $allpathcond='';
1.713     albertel 9744:     foreach my $cond (split(/\|/,$condidx)) {
                   9745: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   9746: 	    $allpathcond.=
                   9747: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   9748: 	}
1.191     harris41 9749:     }
1.54      www      9750:     $allpathcond=~s/\|$//;
1.713     albertel 9751:     return &docondval($allpathcond);
                   9752: }
                   9753: 
                   9754: #evaluates an expression of conditions
                   9755: sub docondval {
                   9756:     my ($allpathcond) = @_;
                   9757:     my $result=0;
                   9758:     if ($env{'request.course.id'}
                   9759: 	&& defined($allpathcond)) {
                   9760: 	my $operand='|';
                   9761: 	my @stack;
                   9762: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   9763: 	    if ($chunk eq '(') {
                   9764: 		push @stack,($operand,$result);
                   9765: 	    } elsif ($chunk eq ')') {
                   9766: 		my $before=pop @stack;
                   9767: 		if (pop @stack eq '&') {
                   9768: 		    $result=$result>$before?$before:$result;
                   9769: 		} else {
                   9770: 		    $result=$result>$before?$result:$before;
                   9771: 		}
                   9772: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   9773: 		$operand=$chunk;
                   9774: 	    } else {
                   9775: 		my $new=directcondval($chunk);
                   9776: 		if ($operand eq '&') {
                   9777: 		    $result=$result>$new?$new:$result;
                   9778: 		} else {
                   9779: 		    $result=$result>$new?$result:$new;
                   9780: 		}
                   9781: 	    }
                   9782: 	}
1.26      www      9783:     }
                   9784:     return $result;
1.421     albertel 9785: }
                   9786: 
                   9787: # ---------------------------------------------------- Devalidate courseresdata
                   9788: 
                   9789: sub devalidatecourseresdata {
                   9790:     my ($coursenum,$coursedomain)=@_;
                   9791:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9792:     &devalidate_cache_new('courseres',$hashid);
1.28      www      9793: }
                   9794: 
1.763     www      9795: 
1.200     www      9796: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     9797: #
                   9798: #  Parameters:
                   9799: #      $coursenum    - Number of the course.
                   9800: #      $coursedomain - Domain at which the course was created.
                   9801: #  Returns:
                   9802: #     A hash of the course parameters along (I think) with timestamps
                   9803: #     and version info.
1.877     foxr     9804: 
1.624     albertel 9805: sub get_courseresdata {
                   9806:     my ($coursenum,$coursedomain)=@_;
1.200     www      9807:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   9808:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9809:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 9810:     my %dumpreply;
1.417     albertel 9811:     unless (defined($cached)) {
1.624     albertel 9812: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 9813: 	$result=\%dumpreply;
1.251     albertel 9814: 	my ($tmp) = keys(%dumpreply);
                   9815: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 9816: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 9817: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   9818: 	    return $tmp;
1.416     albertel 9819: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 9820: 	    $result=undef;
1.599     albertel 9821: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 9822: 	}
                   9823:     }
1.624     albertel 9824:     return $result;
                   9825: }
                   9826: 
1.633     albertel 9827: sub devalidateuserresdata {
                   9828:     my ($uname,$udom)=@_;
                   9829:     my $hashid="$udom:$uname";
                   9830:     &devalidate_cache_new('userres',$hashid);
                   9831: }
                   9832: 
1.624     albertel 9833: sub get_userresdata {
                   9834:     my ($uname,$udom)=@_;
                   9835:     #most student don\'t have any data set, check if there is some data
                   9836:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   9837: 
                   9838:     my $hashid="$udom:$uname";
                   9839:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   9840:     if (!defined($cached)) {
                   9841: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   9842: 	$result=\%resourcedata;
                   9843: 	&do_cache_new('userres',$hashid,$result,600);
                   9844:     }
                   9845:     my ($tmp)=keys(%$result);
                   9846:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   9847: 	return $result;
                   9848:     }
                   9849:     #error 2 occurs when the .db doesn't exist
                   9850:     if ($tmp!~/error: 2 /) {
1.672     albertel 9851: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 9852: 		 " Trying to get resource data for ".
                   9853: 		 $uname." at ".$udom.": ".
                   9854: 		 $tmp."</font>");
                   9855:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 9856: 	#&EXT_cache_set($udom,$uname);
                   9857: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 9858: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 9859:     }
                   9860:     return $tmp;
                   9861: }
1.879     foxr     9862: #----------------------------------------------- resdata - return resource data
                   9863: #  Purpose:
                   9864: #    Return resource data for either users or for a course.
                   9865: #  Parameters:
                   9866: #     $name      - Course/user name.
                   9867: #     $domain    - Name of the domain the user/course is registered on.
                   9868: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   9869: #     @which     - Array of names of resources desired.
                   9870: #  Returns:
                   9871: #     The value of the first reasource in @which that is found in the
                   9872: #     resource hash.
                   9873: #  Exceptional Conditions:
                   9874: #     If the $type passed in is not valid (not the string 'course' or 
                   9875: #     'user', an undefined  reference is returned.
                   9876: #     If none of the resources are found, an undef is returned
1.624     albertel 9877: sub resdata {
                   9878:     my ($name,$domain,$type,@which)=@_;
                   9879:     my $result;
                   9880:     if ($type eq 'course') {
                   9881: 	$result=&get_courseresdata($name,$domain);
                   9882:     } elsif ($type eq 'user') {
                   9883: 	$result=&get_userresdata($name,$domain);
                   9884:     }
                   9885:     if (!ref($result)) { return $result; }    
1.251     albertel 9886:     foreach my $item (@which) {
1.927     albertel 9887: 	if (defined($result->{$item->[0]})) {
                   9888: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 9889: 	}
1.250     albertel 9890:     }
1.291     albertel 9891:     return undef;
1.200     www      9892: }
                   9893: 
1.1172.2.31  raeburn  9894: sub get_numsuppfiles {
                   9895:     my ($cnum,$cdom,$ignorecache)=@_;
                   9896:     my $hashid=$cnum.':'.$cdom;
                   9897:     my ($suppcount,$cached);
                   9898:     unless ($ignorecache) {
                   9899:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   9900:     }
                   9901:     unless (defined($cached)) {
                   9902:         my $chome=&homeserver($cnum,$cdom);
                   9903:         unless ($chome eq 'no_host') {
                   9904:             ($suppcount,my $errors) = (0,0);
                   9905:             my $suppmap = 'supplemental.sequence';
                   9906:             ($suppcount,$errors) =
                   9907:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   9908:         }
                   9909:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   9910:     }
                   9911:     return $suppcount;
                   9912: }
                   9913: 
1.379     matthew  9914: #
                   9915: # EXT resource caching routines
                   9916: #
                   9917: 
                   9918: sub clear_EXT_cache_status {
1.383     albertel 9919:     &delenv('cache.EXT.');
1.379     matthew  9920: }
                   9921: 
                   9922: sub EXT_cache_status {
                   9923:     my ($target_domain,$target_user) = @_;
1.383     albertel 9924:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 9925:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  9926:         # We know already the user has no data
                   9927:         return 1;
                   9928:     } else {
                   9929:         return 0;
                   9930:     }
                   9931: }
                   9932: 
                   9933: sub EXT_cache_set {
                   9934:     my ($target_domain,$target_user) = @_;
1.383     albertel 9935:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  9936:     #&appenv({$cachename => time});
1.379     matthew  9937: }
                   9938: 
1.28      www      9939: # --------------------------------------------------------- Value of a Variable
1.58      www      9940: sub EXT {
1.715     albertel 9941: 
1.1172.2.28  raeburn  9942:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      9943:     unless ($varname) { return ''; }
1.218     albertel 9944:     #get real user name/domain, courseid and symb
                   9945:     my $courseid;
1.359     albertel 9946:     my $publicuser;
1.427     www      9947:     if ($symbparm) {
                   9948: 	$symbparm=&get_symb_from_alias($symbparm);
                   9949:     }
1.218     albertel 9950:     if (!($uname && $udom)) {
1.790     albertel 9951:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 9952:       if (!$symbparm) {	$symbparm=$cursymb; }
                   9953:     } else {
1.620     albertel 9954: 	$courseid=$env{'request.course.id'};
1.218     albertel 9955:     }
1.48      www      9956:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   9957:     my $rest;
1.320     albertel 9958:     if (defined($therest[0])) {
1.48      www      9959:        $rest=join('.',@therest);
                   9960:     } else {
                   9961:        $rest='';
                   9962:     }
1.320     albertel 9963: 
1.57      www      9964:     my $qualifierrest=$qualifier;
                   9965:     if ($rest) { $qualifierrest.='.'.$rest; }
                   9966:     my $spacequalifierrest=$space;
                   9967:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      9968:     if ($realm eq 'user') {
1.48      www      9969: # --------------------------------------------------------------- user.resource
                   9970: 	if ($space eq 'resource') {
1.651     albertel 9971: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   9972: 		  || defined($Apache::lonhomework::parsing_a_task))
                   9973: 		 &&
1.744     albertel 9974: 		 ($symbparm eq &symbread()) ) {	
                   9975: 		# if we are in the middle of processing the resource the
                   9976: 		# get the value we are planning on committing
                   9977:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   9978:                     return $Apache::lonhomework::results{$qualifierrest};
                   9979:                 } else {
                   9980:                     return $Apache::lonhomework::history{$qualifierrest};
                   9981:                 }
1.335     albertel 9982: 	    } else {
1.359     albertel 9983: 		my %restored;
1.620     albertel 9984: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 9985: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   9986: 		} else {
                   9987: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   9988: 		}
1.335     albertel 9989: 		return $restored{$qualifierrest};
                   9990: 	    }
1.48      www      9991: # ----------------------------------------------------------------- user.access
                   9992:         } elsif ($space eq 'access') {
1.218     albertel 9993: 	    # FIXME - not supporting calls for a specific user
1.48      www      9994:             return &allowed($qualifier,$rest);
                   9995: # ------------------------------------------ user.preferences, user.environment
                   9996:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 9997: 	    if (($uname eq $env{'user.name'}) &&
                   9998: 		($udom eq $env{'user.domain'})) {
                   9999: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 10000: 	    } else {
1.359     albertel 10001: 		my %returnhash;
                   10002: 		if (!$publicuser) {
                   10003: 		    %returnhash=&userenvironment($udom,$uname,
                   10004: 						 $qualifierrest);
                   10005: 		}
1.218     albertel 10006: 		return $returnhash{$qualifierrest};
                   10007: 	    }
1.48      www      10008: # ----------------------------------------------------------------- user.course
                   10009:         } elsif ($space eq 'course') {
1.218     albertel 10010: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10011:             return $env{join('.',('request.course',$qualifier))};
1.48      www      10012: # ------------------------------------------------------------------- user.role
                   10013:         } elsif ($space eq 'role') {
1.218     albertel 10014: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10015:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      10016:             if ($qualifier eq 'value') {
                   10017: 		return $role;
                   10018:             } elsif ($qualifier eq 'extent') {
                   10019:                 return $where;
                   10020:             }
                   10021: # ----------------------------------------------------------------- user.domain
                   10022:         } elsif ($space eq 'domain') {
1.218     albertel 10023:             return $udom;
1.48      www      10024: # ------------------------------------------------------------------- user.name
                   10025:         } elsif ($space eq 'name') {
1.218     albertel 10026:             return $uname;
1.48      www      10027: # ---------------------------------------------------- Any other user namespace
1.29      www      10028:         } else {
1.359     albertel 10029: 	    my %reply;
                   10030: 	    if (!$publicuser) {
                   10031: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   10032: 	    }
                   10033: 	    return $reply{$qualifierrest};
1.48      www      10034:         }
1.236     www      10035:     } elsif ($realm eq 'query') {
                   10036: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 10037:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   10038: 						[$spacequalifierrest]);
1.620     albertel 10039: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      10040:    } elsif ($realm eq 'request') {
1.48      www      10041: # ------------------------------------------------------------- request.browser
                   10042:         if ($space eq 'browser') {
1.1145    bisitz   10043:             return $env{'browser.'.$qualifier};
1.57      www      10044: # ------------------------------------------------------------ request.filename
                   10045:         } else {
1.620     albertel 10046:             return $env{'request.'.$spacequalifierrest};
1.29      www      10047:         }
1.28      www      10048:     } elsif ($realm eq 'course') {
1.48      www      10049: # ---------------------------------------------------------- course.description
1.620     albertel 10050:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      10051:     } elsif ($realm eq 'resource') {
1.165     www      10052: 
1.620     albertel 10053: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 10054: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   10055: 	}
1.693     albertel 10056: 
1.1172.2.30  raeburn  10057:         if ($qualifier eq '') {
                   10058: 	    if ($space eq 'title') {
                   10059: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   10060: 	        return &gettitle($symbparm);
                   10061: 	    }
1.693     albertel 10062: 	
1.1172.2.30  raeburn  10063: 	    if ($space eq 'map') {
                   10064: 	        my ($map) = &decode_symb($symbparm);
                   10065: 	        return &symbread($map);
                   10066: 	    }
                   10067:             if ($space eq 'maptitle') {
                   10068:                 my ($map) = &decode_symb($symbparm);
                   10069:                 return &gettitle($map);
                   10070:             }
                   10071: 	    if ($space eq 'filename') {
                   10072: 	        if ($symbparm) {
                   10073: 		    return &clutter((&decode_symb($symbparm))[2]);
                   10074: 	        }
                   10075: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 10076: 	    }
1.1172.2.30  raeburn  10077: 
                   10078:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   10079:                 if ($space eq 'visibleparts') {
                   10080:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10081:                     my $item;
                   10082:                     if (ref($navmap)) {
                   10083:                         my $res = $navmap->getBySymb($symbparm);
                   10084:                         my $parts = $res->parts();
                   10085:                         if (ref($parts) eq 'ARRAY') {
                   10086:                             $item = join(',',@{$parts});
                   10087:                         }
                   10088:                         undef($navmap);
                   10089:                     }
                   10090:                     return $item;
                   10091:                 }
                   10092:             }
                   10093:         }
1.693     albertel 10094: 
                   10095: 	my ($section, $group, @groups);
1.593     albertel 10096: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  10097:         if (($courseid eq '') && ($cid)) {
                   10098:             $courseid = $cid;
                   10099:         }
                   10100: 	if (($symbparm && $courseid) && 
                   10101: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      10102: 
1.218     albertel 10103: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      10104: 
1.60      www      10105: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 10106: 	    my $symbp=$symbparm;
1.735     albertel 10107: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 10108: 
                   10109: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   10110: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   10111: 
1.620     albertel 10112: 	    if (($env{'user.name'} eq $uname) &&
                   10113: 		($env{'user.domain'} eq $udom)) {
                   10114: 		$section=$env{'request.course.sec'};
1.733     raeburn  10115:                 @groups = split(/:/,$env{'request.course.groups'});  
                   10116:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 10117: 	    } else {
1.539     albertel 10118: 		if (! defined($usection)) {
1.551     albertel 10119: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 10120: 		} else {
                   10121: 		    $section = $usection;
                   10122: 		}
1.733     raeburn  10123:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 10124: 	    }
                   10125: 
                   10126: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   10127: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   10128: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   10129: 
1.593     albertel 10130: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 10131: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 10132: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      10133: 
1.60      www      10134: # ----------------------------------------------------------- first, check user
1.624     albertel 10135: 
                   10136: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 10137: 				       ([$courselevelr,'resource'],
                   10138: 					[$courselevelm,'map'     ],
                   10139: 					[$courselevel, 'course'  ]));
1.931     albertel 10140: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      10141: 
1.594     albertel 10142: # ------------------------------------------------ second, check some of course
1.684     raeburn  10143:             my $coursereply;
1.691     raeburn  10144:             if (@groups > 0) {
                   10145:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   10146:                                        $mapparm,$spacequalifierrest);
1.927     albertel 10147:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  10148:             }
1.96      www      10149: 
1.684     raeburn  10150: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 10151: 				  $env{'course.'.$courseid.'.domain'},
                   10152: 				  'course',
                   10153: 				  ([$seclevelr,   'resource'],
                   10154: 				   [$seclevelm,   'map'     ],
                   10155: 				   [$seclevel,    'course'  ],
                   10156: 				   [$courselevelr,'resource']));
                   10157: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      10158: 
1.60      www      10159: # ------------------------------------------------------ third, check map parms
1.218     albertel 10160: 	    my %parmhash=();
                   10161: 	    my $thisparm='';
                   10162: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 10163: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 10164: 		    &GDBM_READER(),0640)) {
1.218     albertel 10165: 		$thisparm=$parmhash{$symbparm};
                   10166: 		untie(%parmhash);
                   10167: 	    }
1.927     albertel 10168: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 10169: 	}
1.594     albertel 10170: # ------------------------------------------ fourth, look in resource metadata
1.71      www      10171: 
1.218     albertel 10172: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 10173: 	my $filename;
                   10174: 	if (!$symbparm) { $symbparm=&symbread(); }
                   10175: 	if ($symbparm) {
1.409     www      10176: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 10177: 	} else {
1.620     albertel 10178: 	    $filename=$env{'request.filename'};
1.282     albertel 10179: 	}
                   10180: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 10181: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 10182: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 10183: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      10184: 
1.927     albertel 10185: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 10186: 	if ($symbparm && defined($courseid) && 
1.620     albertel 10187: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 10188: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   10189: 				     $env{'course.'.$courseid.'.domain'},
                   10190: 				     'course',
1.927     albertel 10191: 				     ([$courselevelm,'map'   ],
                   10192: 				      [$courselevel, 'course']));
                   10193: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 10194: 	}
1.145     www      10195: # ------------------------------------------------------------------ Cascade up
1.218     albertel 10196: 	unless ($space eq '0') {
1.336     albertel 10197: 	    my @parts=split(/_/,$space);
                   10198: 	    my $id=pop(@parts);
                   10199: 	    my $part=join('_',@parts);
                   10200: 	    if ($part eq '') { $part='0'; }
1.927     albertel 10201: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 10202: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  10203: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 10204: 	}
1.395     albertel 10205: 	if ($recurse) { return undef; }
                   10206: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 10207: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      10208: # ---------------------------------------------------- Any other user namespace
                   10209:     } elsif ($realm eq 'environment') {
                   10210: # ----------------------------------------------------------------- environment
1.620     albertel 10211: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   10212: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 10213: 	} else {
1.770     albertel 10214: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   10215: 		return '';
                   10216: 	    }
1.219     albertel 10217: 	    my %returnhash=&userenvironment($udom,$uname,
                   10218: 					    $spacequalifierrest);
                   10219: 	    return $returnhash{$spacequalifierrest};
                   10220: 	}
1.28      www      10221:     } elsif ($realm eq 'system') {
1.48      www      10222: # ----------------------------------------------------------------- system.time
                   10223: 	if ($space eq 'time') {
                   10224: 	    return time;
                   10225:         }
1.696     albertel 10226:     } elsif ($realm eq 'server') {
                   10227: # ----------------------------------------------------------------- system.time
                   10228: 	if ($space eq 'name') {
                   10229: 	    return $ENV{'SERVER_NAME'};
                   10230:         }
1.28      www      10231:     }
1.48      www      10232:     return '';
1.61      www      10233: }
                   10234: 
1.927     albertel 10235: sub get_reply {
                   10236:     my ($reply_value) = @_;
1.940     raeburn  10237:     if (ref($reply_value) eq 'ARRAY') {
                   10238:         if (wantarray) {
                   10239: 	    return @$reply_value;
                   10240:         }
                   10241:         return $reply_value->[0];
                   10242:     } else {
                   10243:         return $reply_value;
1.927     albertel 10244:     }
                   10245: }
                   10246: 
1.691     raeburn  10247: sub check_group_parms {
                   10248:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   10249:     my @groupitems = ();
                   10250:     my $resultitem;
1.927     albertel 10251:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  10252:     foreach my $group (@{$groups}) {
                   10253:         foreach my $level (@levels) {
1.927     albertel 10254:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   10255:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  10256:         }
                   10257:     }
                   10258:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   10259:                             $env{'course.'.$courseid.'.domain'},
                   10260:                                      'course',@groupitems);
                   10261:     return $coursereply;
                   10262: }
                   10263: 
                   10264: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  10265:     my ($courseid,@groups) = @_;
                   10266:     @groups = sort(@groups);
1.691     raeburn  10267:     return @groups;
                   10268: }
                   10269: 
1.395     albertel 10270: sub packages_tab_default {
                   10271:     my ($uri,$varname)=@_;
                   10272:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 10273: 
                   10274:     my (@extension,@specifics,$do_default);
                   10275:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 10276: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 10277: 	if ($pack_type eq 'default') {
                   10278: 	    $do_default=1;
                   10279: 	} elsif ($pack_type eq 'extension') {
                   10280: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 10281: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 10282: 	    # only look at packages defaults for packages that this id is
1.738     albertel 10283: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   10284: 	}
                   10285:     }
                   10286:     # first look for a package that matches the requested part id
                   10287:     foreach my $package (@specifics) {
                   10288: 	my (undef,$pack_type,$pack_part)=@{$package};
                   10289: 	next if ($pack_part ne $part);
                   10290: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10291: 	    return $packagetab{"$pack_type&$name&default"};
                   10292: 	}
                   10293:     }
                   10294:     # look for any possible matching non extension_ package
                   10295:     foreach my $package (@specifics) {
                   10296: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 10297: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10298: 	    return $packagetab{"$pack_type&$name&default"};
                   10299: 	}
1.585     albertel 10300: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 10301: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   10302: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 10303: 	}
                   10304:     }
1.738     albertel 10305:     # look for any posible extension_ match
                   10306:     foreach my $package (@extension) {
                   10307: 	my ($package,$pack_type)=@{$package};
                   10308: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10309: 	    return $packagetab{"$pack_type&$name&default"};
                   10310: 	}
                   10311: 	if (defined($packagetab{$package."&$name&default"})) {
                   10312: 	    return $packagetab{$package."&$name&default"};
                   10313: 	}
                   10314:     }
                   10315:     # look for a global default setting
                   10316:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   10317: 	return $packagetab{"default&$name&default"};
                   10318:     }
1.395     albertel 10319:     return undef;
                   10320: }
                   10321: 
1.334     albertel 10322: sub add_prefix_and_part {
                   10323:     my ($prefix,$part)=@_;
                   10324:     my $keyroot;
                   10325:     if (defined($prefix) && $prefix !~ /^__/) {
                   10326: 	# prefix that has a part already
                   10327: 	$keyroot=$prefix;
                   10328:     } elsif (defined($prefix)) {
                   10329: 	# prefix that is missing a part
                   10330: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   10331:     } else {
                   10332: 	# no prefix at all
                   10333: 	if (defined($part)) { $keyroot='_'.$part; }
                   10334:     }
                   10335:     return $keyroot;
                   10336: }
                   10337: 
1.71      www      10338: # ---------------------------------------------------------------- Get metadata
                   10339: 
1.599     albertel 10340: my %metaentry;
1.1070    www      10341: my %importedpartids;
1.71      www      10342: sub metadata {
1.176     www      10343:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      10344:     $uri=&declutter($uri);
1.288     albertel 10345:     # if it is a non metadata possible uri return quickly
1.529     albertel 10346:     if (($uri eq '') || 
                   10347: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  10348: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  10349:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 10350: 	return undef;
                   10351:     }
1.1172.2.49  raeburn  10352:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 10353: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 10354: 	return undef;
1.288     albertel 10355:     }
1.73      www      10356:     my $filename=$uri;
                   10357:     $uri=~s/\.meta$//;
1.172     www      10358: #
                   10359: # Is the metadata already cached?
1.177     www      10360: # Look at timestamp of caching
1.172     www      10361: # Everything is cached by the main uri, libraries are never directly cached
                   10362: #
1.428     albertel 10363:     if (!defined($liburi)) {
1.599     albertel 10364: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 10365: 	if (defined($cached)) { return $result->{':'.$what}; }
                   10366:     }
                   10367:     {
1.1069    www      10368: # Imported parts would go here
1.1070    www      10369:         my %importedids=();
                   10370:         my @origfileimportpartids=();
1.1069    www      10371:         my $importedparts=0;
1.172     www      10372: #
                   10373: # Is this a recursive call for a library?
                   10374: #
1.599     albertel 10375: #	if (! exists($metacache{$uri})) {
                   10376: #	    $metacache{$uri}={};
                   10377: #	}
1.924     albertel 10378: 	my $cachetime = 60*60;
1.171     www      10379:         if ($liburi) {
                   10380: 	    $liburi=&declutter($liburi);
                   10381:             $filename=$liburi;
1.401     bowersj2 10382:         } else {
1.599     albertel 10383: 	    &devalidate_cache_new('meta',$uri);
                   10384: 	    undef(%metaentry);
1.401     bowersj2 10385: 	}
1.140     www      10386:         my %metathesekeys=();
1.73      www      10387:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 10388: 	my $metastring;
1.1140    www      10389: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 10390: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 10391: 	    $metastring = 
1.929     albertel 10392: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 10393: 					  ('grade_target' => 'meta'));
                   10394: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  10395: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   10396:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 10397: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 10398: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 10399: 	    $metastring=&getfile($file);
1.489     albertel 10400: 	}
1.208     albertel 10401:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      10402:         my $token;
1.140     www      10403:         undef %metathesekeys;
1.71      www      10404:         while ($token=$parser->get_token) {
1.339     albertel 10405: 	    if ($token->[0] eq 'S') {
                   10406: 		if (defined($token->[2]->{'package'})) {
1.172     www      10407: #
                   10408: # This is a package - get package info
                   10409: #
1.339     albertel 10410: 		    my $package=$token->[2]->{'package'};
                   10411: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10412: 		    if (defined($token->[2]->{'id'})) { 
                   10413: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   10414: 		    }
1.599     albertel 10415: 		    if ($metaentry{':packages'}) {
                   10416: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 10417: 		    } else {
1.599     albertel 10418: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 10419: 		    }
1.736     albertel 10420: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 10421: 			my $part=$keyroot;
                   10422: 			$part=~s/^\_//;
1.736     albertel 10423: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   10424: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   10425: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 10426: 			    # ignore package.tab specified default values
                   10427:                             # here &package_tab_default() will fetch those
                   10428: 			    if ($subp eq 'default') { next; }
1.736     albertel 10429: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 10430: 			    my $unikey;
                   10431: 			    if ($pack =~ /_0$/) {
                   10432: 				$unikey='parameter_0_'.$name;
                   10433: 				$part=0;
                   10434: 			    } else {
                   10435: 				$unikey='parameter'.$keyroot.'_'.$name;
                   10436: 			    }
1.339     albertel 10437: 			    if ($subp eq 'display') {
                   10438: 				$value.=' [Part: '.$part.']';
                   10439: 			    }
1.599     albertel 10440: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 10441: 			    $metathesekeys{$unikey}=1;
1.599     albertel 10442: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10443: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 10444: 			    }
1.599     albertel 10445: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   10446: 				$metaentry{':'.$unikey}=
                   10447: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 10448: 			    }
1.339     albertel 10449: 			}
                   10450: 		    }
                   10451: 		} else {
1.172     www      10452: #
                   10453: # This is not a package - some other kind of start tag
1.339     albertel 10454: #
                   10455: 		    my $entry=$token->[1];
1.1068    www      10456: 		    my $unikey='';
1.175     www      10457: 
1.339     albertel 10458: 		    if ($entry eq 'import') {
1.175     www      10459: #
                   10460: # Importing a library here
1.339     albertel 10461: #
1.1067    www      10462:                         my $location=$parser->get_text('/import');
                   10463:                         my $dir=$filename;
                   10464:                         $dir=~s|[^/]*$||;
                   10465:                         $location=&filelocation($dir,$location);
1.1069    www      10466:                        
1.1068    www      10467:                         my $importmode=$token->[2]->{'importmode'};
                   10468:                         if ($importmode eq 'problem') {
1.1069    www      10469: # Import as problem/response
1.1068    www      10470:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10471:                         } elsif ($importmode eq 'part') {
                   10472: # Import as part(s)
1.1069    www      10473:                            $importedparts=1;
                   10474: # We need to get the original file and the imported file to get the part order correct
                   10475: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   10476: # Load and inspect original file
1.1070    www      10477:                            if ($#origfileimportpartids<0) {
                   10478:                               undef(%importedpartids);
                   10479:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   10480:                               my $origfile=&getfile($origfilelocation);
                   10481:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10482:                            }
                   10483: 
1.1069    www      10484: # Load and inspect imported file
                   10485:                            my $impfile=&getfile($location);
                   10486:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10487:                            if ($#impfilepartids>=0) {
                   10488: # This problem had parts
1.1070    www      10489:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      10490:                            } else {
                   10491: # Importing by turning a single problem into a problem part
                   10492: # It gets the import-tags ID as part-ID
                   10493:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      10494:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      10495:                            }
1.1068    www      10496:                         } else {
                   10497: # Normal import
                   10498:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10499:                            if (defined($token->[2]->{'id'})) {
                   10500:                               $unikey.='_'.$token->[2]->{'id'};
                   10501:                            }
1.1067    www      10502:                         }
                   10503: 
1.339     albertel 10504: 			if ($depthcount<20) {
1.736     albertel 10505: 			    my $metadata = 
                   10506: 				&metadata($uri,'keys', $location,$unikey,
                   10507: 					  $depthcount+1);
                   10508: 			    foreach my $meta (split(',',$metadata)) {
                   10509: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   10510: 				$metathesekeys{$meta}=1;
1.339     albertel 10511: 			    }
1.1068    www      10512: 			
                   10513:                         }
1.1067    www      10514: 		    } else {
                   10515: #
                   10516: # Not importing, some other kind of non-package, non-library start tag
                   10517: # 
                   10518:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10519:                         if (defined($token->[2]->{'id'})) {
                   10520:                             $unikey.='_'.$token->[2]->{'id'};
                   10521:                         }
1.339     albertel 10522: 			if (defined($token->[2]->{'name'})) { 
                   10523: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   10524: 			}
                   10525: 			$metathesekeys{$unikey}=1;
1.736     albertel 10526: 			foreach my $param (@{$token->[3]}) {
                   10527: 			    $metaentry{':'.$unikey.'.'.$param} =
                   10528: 				$token->[2]->{$param};
1.339     albertel 10529: 			}
                   10530: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 10531: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 10532: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   10533: 		 # only ws inside the tag, and not in default, so use default
                   10534: 		 # as value
1.599     albertel 10535: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 10536: 			} elsif ( $internaltext =~ /\S/ ) {
                   10537: 		  # something interesting inside the tag
                   10538: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 10539: 			} else {
1.908     albertel 10540: 		  # no interesting values, don't set a default
1.339     albertel 10541: 			}
1.172     www      10542: # end of not-a-package not-a-library import
1.339     albertel 10543: 		    }
1.172     www      10544: # end of not-a-package start tag
1.339     albertel 10545: 		}
1.172     www      10546: # the next is the end of "start tag"
1.339     albertel 10547: 	    }
                   10548: 	}
1.483     albertel 10549: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 10550: 	$extension = lc($extension);
                   10551: 	if ($extension eq 'htm') { $extension='html'; }
                   10552: 
1.737     albertel 10553: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 10554: 	    #no specific packages #how's our extension
                   10555: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 10556: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 10557: 					 \%metathesekeys);
                   10558: 	}
1.883     albertel 10559: 
                   10560: 	if (!exists($metaentry{':packages'})
                   10561: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 10562: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 10563: 		#no specific packages well let's get default then
                   10564: 		if ($key!~/^default&/) { next; }
1.488     albertel 10565: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 10566: 					     \%metathesekeys);
                   10567: 	    }
                   10568: 	}
1.338     www      10569: # are there custom rights to evaluate
1.599     albertel 10570: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 10571: 
1.338     www      10572:     #
                   10573:     # Importing a rights file here
1.339     albertel 10574:     #
                   10575: 	    unless ($depthcount) {
1.599     albertel 10576: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 10577: 		my $dir=$filename;
                   10578: 		$dir=~s|[^/]*$||;
                   10579: 		$location=&filelocation($dir,$location);
1.736     albertel 10580: 		my $rights_metadata =
                   10581: 		    &metadata($uri,'keys',$location,'_rights',
                   10582: 			      $depthcount+1);
                   10583: 		foreach my $rights (split(',',$rights_metadata)) {
                   10584: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   10585: 		    $metathesekeys{$rights}=1;
1.339     albertel 10586: 		}
                   10587: 	    }
                   10588: 	}
1.737     albertel 10589: 	# uniqifiy package listing
                   10590: 	my %seen;
                   10591: 	my @uniq_packages =
                   10592: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   10593: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   10594: 
1.1070    www      10595:         if ($importedparts) {
                   10596: # We had imported parts and need to rebuild partorder
                   10597:            $metaentry{':partorder'}='';
                   10598:            $metathesekeys{'partorder'}=1;
                   10599:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   10600:                if ($origfileimportpartids[$index] eq 'part') {
                   10601: # original part, part of the problem
                   10602:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   10603:                } else {
                   10604: # we have imported parts at this position
                   10605:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   10606:                }
                   10607:            }
                   10608:            $metaentry{':partorder'}=~s/^\,//;
                   10609:         }
                   10610: 
1.737     albertel 10611: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 10612: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  10613: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 10614: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      10615: # this is the end of "was not already recently cached
1.71      www      10616:     }
1.599     albertel 10617:     return $metaentry{':'.$what};
1.261     albertel 10618: }
                   10619: 
1.488     albertel 10620: sub metadata_create_package_def {
1.483     albertel 10621:     my ($uri,$key,$package,$metathesekeys)=@_;
                   10622:     my ($pack,$name,$subp)=split(/\&/,$key);
                   10623:     if ($subp eq 'default') { next; }
                   10624:     
1.599     albertel 10625:     if (defined($metaentry{':packages'})) {
                   10626: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 10627:     } else {
1.599     albertel 10628: 	$metaentry{':packages'}=$package;
1.483     albertel 10629:     }
                   10630:     my $value=$packagetab{$key};
                   10631:     my $unikey;
                   10632:     $unikey='parameter_0_'.$name;
1.599     albertel 10633:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 10634:     $$metathesekeys{$unikey}=1;
1.599     albertel 10635:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10636: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 10637:     }
1.599     albertel 10638:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   10639: 	$metaentry{':'.$unikey}=
                   10640: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 10641:     }
                   10642: }
                   10643: 
1.261     albertel 10644: sub metadata_generate_part0 {
                   10645:     my ($metadata,$metacache,$uri) = @_;
                   10646:     my %allnames;
1.737     albertel 10647:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 10648: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 10649: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   10650: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 10651: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 10652: 	    $allnames{$name}=$part;
                   10653: 	  }
                   10654: 	}
                   10655:     }
                   10656:     foreach my $name (keys(%allnames)) {
                   10657:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 10658:       my $key=":parameter_0_$name";
1.261     albertel 10659:       $$metacache{"$key.part"}='0';
                   10660:       $$metacache{"$key.name"}=$name;
1.428     albertel 10661:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 10662: 					   $allnames{$name}.'_'.$name.
                   10663: 					   '.type'};
1.428     albertel 10664:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 10665: 			     '.display'};
1.644     www      10666:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 10667:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 10668:       $$metacache{"$key.display"}=$olddis;
                   10669:     }
1.71      www      10670: }
                   10671: 
1.764     albertel 10672: # ------------------------------------------------------ Devalidate title cache
                   10673: 
                   10674: sub devalidate_title_cache {
                   10675:     my ($url)=@_;
                   10676:     if (!$env{'request.course.id'}) { return; }
                   10677:     my $symb=&symbread($url);
                   10678:     if (!$symb) { return; }
                   10679:     my $key=$env{'request.course.id'}."\0".$symb;
                   10680:     &devalidate_cache_new('title',$key);
                   10681: }
                   10682: 
1.1014    droeschl 10683: # ------------------------------------------------- Get the title of a course
                   10684: 
                   10685: sub current_course_title {
                   10686:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   10687: }
1.301     www      10688: # ------------------------------------------------- Get the title of a resource
                   10689: 
                   10690: sub gettitle {
                   10691:     my $urlsymb=shift;
                   10692:     my $symb=&symbread($urlsymb);
1.534     albertel 10693:     if ($symb) {
1.620     albertel 10694: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 10695: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 10696: 	if (defined($cached)) { 
                   10697: 	    return $result;
                   10698: 	}
1.534     albertel 10699: 	my ($map,$resid,$url)=&decode_symb($symb);
                   10700: 	my $title='';
1.907     albertel 10701: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   10702: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   10703: 	} else {
                   10704: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10705: 		    &GDBM_READER(),0640)) {
                   10706: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   10707: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   10708: 		untie(%bighash);
                   10709: 	    }
1.534     albertel 10710: 	}
                   10711: 	$title=~s/\&colon\;/\:/gs;
                   10712: 	if ($title) {
1.1159    www      10713: # Remember both $symb and $title for dynamic metadata
                   10714:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      10715:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      10716: # Cache this title and then return it
1.599     albertel 10717: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 10718: 	}
                   10719: 	$urlsymb=$url;
                   10720:     }
                   10721:     my $title=&metadata($urlsymb,'title');
                   10722:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   10723:     return $title;
1.301     www      10724: }
1.613     albertel 10725: 
1.614     albertel 10726: sub get_slot {
                   10727:     my ($which,$cnum,$cdom)=@_;
                   10728:     if (!$cnum || !$cdom) {
1.790     albertel 10729: 	(undef,my $courseid)=&whichuser();
1.620     albertel 10730: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   10731: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 10732:     }
1.703     albertel 10733:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   10734:     my %slotinfo;
                   10735:     if (exists($remembered{$key})) {
                   10736: 	$slotinfo{$which} = $remembered{$key};
                   10737:     } else {
                   10738: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   10739: 	&Apache::lonhomework::showhash(%slotinfo);
                   10740: 	my ($tmp)=keys(%slotinfo);
                   10741: 	if ($tmp=~/^error:/) { return (); }
                   10742: 	$remembered{$key} = $slotinfo{$which};
                   10743:     }
1.616     albertel 10744:     if (ref($slotinfo{$which}) eq 'HASH') {
                   10745: 	return %{$slotinfo{$which}};
                   10746:     }
                   10747:     return $slotinfo{$which};
1.614     albertel 10748: }
1.1150    raeburn  10749: 
                   10750: sub get_reservable_slots {
                   10751:     my ($cnum,$cdom,$uname,$udom) = @_;
                   10752:     my $now = time;
                   10753:     my $reservable_info;
                   10754:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   10755:     if (exists($remembered{$key})) {
                   10756:         $reservable_info = $remembered{$key};
                   10757:     } else {
                   10758:         my %resv;
                   10759:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   10760:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   10761:         $reservable_info = \%resv;
                   10762:         $remembered{$key} = $reservable_info;
                   10763:     }
                   10764:     return $reservable_info;
                   10765: }
                   10766: 
                   10767: sub get_course_slots {
                   10768:     my ($cnum,$cdom) = @_;
                   10769:     my $hashid=$cnum.':'.$cdom;
                   10770:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   10771:     if (defined($cached)) {
                   10772:         if (ref($result) eq 'HASH') {
                   10773:             return %{$result};
                   10774:         }
                   10775:     } else {
                   10776:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   10777:         my ($tmp) = keys(%slots);
                   10778:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  10779:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  10780:             return %slots;
                   10781:         }
                   10782:     }
                   10783:     return;
                   10784: }
                   10785: 
                   10786: sub devalidate_slots_cache {
                   10787:     my ($cnum,$cdom)=@_;
                   10788:     my $hashid=$cnum.':'.$cdom;
                   10789:     &devalidate_cache_new('allslots',$hashid);
                   10790: }
                   10791: 
1.1172.2.8  raeburn  10792: sub get_coursechange {
                   10793:     my ($cdom,$cnum) = @_;
                   10794:     if ($cdom eq '' || $cnum eq '') {
                   10795:         return unless ($env{'request.course.id'});
                   10796:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10797:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10798:     }
                   10799:     my $hashid=$cdom.'_'.$cnum;
                   10800:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   10801:     if ((defined($cached)) && ($change ne '')) {
                   10802:         return $change;
                   10803:     } else {
                   10804:         my %crshash;
                   10805:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   10806:         if ($crshash{'internal.contentchange'} eq '') {
                   10807:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   10808:             if ($change eq '') {
                   10809:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   10810:                 $change = $crshash{'internal.created'};
                   10811:             }
                   10812:         } else {
                   10813:             $change = $crshash{'internal.contentchange'};
                   10814:         }
                   10815:         my $cachetime = 600;
                   10816:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   10817:     }
                   10818:     return $change;
                   10819: }
                   10820: 
                   10821: sub devalidate_coursechange_cache {
                   10822:     my ($cnum,$cdom)=@_;
                   10823:     my $hashid=$cnum.':'.$cdom;
                   10824:     &devalidate_cache_new('crschange',$hashid);
                   10825: }
                   10826: 
1.31      www      10827: # ------------------------------------------------- Update symbolic store links
                   10828: 
                   10829: sub symblist {
                   10830:     my ($mapname,%newhash)=@_;
1.438     www      10831:     $mapname=&deversion(&declutter($mapname));
1.31      www      10832:     my %hash;
1.620     albertel 10833:     if (($env{'request.course.fn'}) && (%newhash)) {
                   10834:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10835:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  10836: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 10837: 		next if ($url eq 'last_known'
                   10838: 			 && $env{'form.no_update_last_known'});
                   10839: 		$hash{declutter($url)}=&encode_symb($mapname,
                   10840: 						    $newhash{$url}->[1],
                   10841: 						    $newhash{$url}->[0]);
1.191     harris41 10842:             }
1.31      www      10843:             if (untie(%hash)) {
                   10844: 		return 'ok';
                   10845:             }
                   10846:         }
                   10847:     }
                   10848:     return 'error';
1.212     www      10849: }
                   10850: 
                   10851: # --------------------------------------------------------------- Verify a symb
                   10852: 
                   10853: sub symbverify {
1.1172.2.11  raeburn  10854:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      10855:     my $thisfn=$thisurl;
1.439     www      10856:     $thisfn=&declutter($thisfn);
1.215     www      10857: # direct jump to resource in page or to a sequence - will construct own symbs
                   10858:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   10859: # check URL part
1.409     www      10860:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      10861: 
1.431     www      10862:     unless ($url eq $thisfn) { return 0; }
1.213     www      10863: 
1.216     www      10864:     $symb=&symbclean($symb);
1.510     www      10865:     $thisurl=&deversion($thisurl);
1.439     www      10866:     $thisfn=&deversion($thisfn);
1.213     www      10867: 
                   10868:     my %bighash;
                   10869:     my $okay=0;
1.431     www      10870: 
1.620     albertel 10871:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10872:                             &GDBM_READER(),0640)) {
1.1172.2.13  raeburn  10873:         my $noclutter;
1.1032    raeburn  10874:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   10875:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  10876:             if ($map =~ m{^uploaded/.+\.page$}) {
                   10877:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   10878:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   10879:                 $noclutter = 1;
                   10880:             }
                   10881:         }
                   10882:         my $ids;
                   10883:         if ($noclutter) {
                   10884:             $ids=$bighash{'ids_'.$thisurl};
                   10885:         } else {
                   10886:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  10887:         }
1.1102    raeburn  10888:         unless ($ids) {
1.1172.2.13  raeburn  10889:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  10890:             $ids=$bighash{$idkey};
1.216     www      10891:         }
                   10892:         if ($ids) {
                   10893: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  10894:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   10895:                 $symb =~ s/\?.+$//;
                   10896:             }
1.800     albertel 10897: 	    foreach my $id (split(/\,/,$ids)) {
                   10898: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      10899:                if (
                   10900:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  10901:    eq $symb) {
1.1172.2.11  raeburn  10902:                    if (ref($encstate)) {
                   10903:                        $$encstate = $bighash{'encrypted_'.$id};
                   10904:                    }
1.1172.2.13  raeburn  10905:                    if (($env{'request.role.adv'}) ||
                   10906:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  10907:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  10908:                        $okay=1;
                   10909:                        last;
                   10910:                    }
                   10911:                }
                   10912:            }
1.216     www      10913:         }
1.213     www      10914: 	untie(%bighash);
                   10915:     }
                   10916:     return $okay;
1.31      www      10917: }
                   10918: 
1.210     www      10919: # --------------------------------------------------------------- Clean-up symb
                   10920: 
                   10921: sub symbclean {
                   10922:     my $symb=shift;
1.568     albertel 10923:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      10924: # remove version from map
                   10925:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      10926: 
1.210     www      10927: # remove version from URL
                   10928:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      10929: 
1.507     www      10930: # remove wrapper
                   10931: 
1.510     www      10932:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 10933:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      10934:     return $symb;
1.409     www      10935: }
                   10936: 
                   10937: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 10938: 
                   10939: sub encode_symb {
                   10940:     my ($map,$resid,$url)=@_;
                   10941:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   10942: }
1.409     www      10943: 
                   10944: sub decode_symb {
1.568     albertel 10945:     my $symb=shift;
                   10946:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   10947:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      10948:     return (&fixversion($map),$resid,&fixversion($url));
                   10949: }
                   10950: 
                   10951: sub fixversion {
                   10952:     my $fn=shift;
1.609     banghart 10953:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      10954:     my %bighash;
                   10955:     my $uri=&clutter($fn);
1.620     albertel 10956:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      10957: # is this cached?
1.599     albertel 10958:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      10959:     if (defined($cached)) { return $result; }
                   10960: # unfortunately not cached, or expired
1.620     albertel 10961:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      10962: 	    &GDBM_READER(),0640)) {
                   10963:  	if ($bighash{'version_'.$uri}) {
                   10964:  	    my $version=$bighash{'version_'.$uri};
1.444     www      10965:  	    unless (($version eq 'mostrecent') || 
                   10966: 		    ($version==&getversion($uri))) {
1.440     www      10967:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   10968:  	    }
                   10969:  	}
                   10970:  	untie %bighash;
1.413     www      10971:     }
1.599     albertel 10972:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      10973: }
                   10974: 
                   10975: sub deversion {
                   10976:     my $url=shift;
                   10977:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   10978:     return $url;
1.210     www      10979: }
                   10980: 
1.31      www      10981: # ------------------------------------------------------ Return symb list entry
                   10982: 
                   10983: sub symbread {
1.249     www      10984:     my ($thisfn,$donotrecurse)=@_;
1.1172.2.54  raeburn  10985:     my $cache_str='request.symbread.cached.'.$thisfn;
                   10986:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      10987: # no filename provided? try from environment
1.1172.2.54  raeburn  10988:     unless ($thisfn) {
1.620     albertel 10989:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  10990:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   10991:         }
                   10992:         $thisfn=$env{'request.filename'};
1.44      www      10993:     }
1.569     albertel 10994:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      10995: # is that filename actually a symb? Verify, clean, and return
                   10996:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 10997: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 10998: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 10999: 	}
1.242     www      11000:     }
1.44      www      11001:     $thisfn=declutter($thisfn);
1.31      www      11002:     my %hash;
1.37      www      11003:     my %bighash;
                   11004:     my $syval='';
1.620     albertel 11005:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  11006:         my $targetfn = $thisfn;
1.609     banghart 11007:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  11008:             $targetfn = 'adm/wrapper/'.$thisfn;
                   11009:         }
1.687     albertel 11010: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   11011: 	    $targetfn=$1;
                   11012: 	}
1.620     albertel 11013:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11014:                       &GDBM_READER(),0640)) {
1.481     raeburn  11015: 	    $syval=$hash{$targetfn};
1.37      www      11016:             untie(%hash);
                   11017:         }
                   11018: # ---------------------------------------------------------- There was an entry
                   11019:         if ($syval) {
1.601     albertel 11020: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 11021: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  11022: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11023: 		    #return $env{$cache_str}='';
1.601     albertel 11024: 		#}    
                   11025: 		#$syval.=$1;
                   11026: 	    #}
1.37      www      11027:         } else {
                   11028: # ------------------------------------------------------- Was not in symb table
1.620     albertel 11029:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11030:                             &GDBM_READER(),0640)) {
1.37      www      11031: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      11032:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      11033:               unless ($ids) { 
                   11034:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      11035:               }
                   11036:               unless ($ids) {
                   11037: # alias?
                   11038: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      11039:               }
1.37      www      11040:               if ($ids) {
                   11041: # ------------------------------------------------------------------- Has ID(s)
                   11042:                  my @possibilities=split(/\,/,$ids);
1.39      www      11043:                  if ($#possibilities==0) {
                   11044: # ----------------------------------------------- There is only one possibility
1.37      www      11045: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 11046: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11047: 						    $resid,$thisfn);
1.249     www      11048:                  } elsif (!$donotrecurse) {
1.39      www      11049: # ------------------------------------------ There is more than one possibility
                   11050:                      my $realpossible=0;
1.800     albertel 11051:                      foreach my $id (@possibilities) {
                   11052: 			 my $file=$bighash{'src_'.$id};
1.39      www      11053:                          if (&allowed('bre',$file)) {
1.800     albertel 11054:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      11055:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   11056: 				$realpossible++;
1.626     albertel 11057:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11058: 						    $resid,$thisfn);
1.39      www      11059:                             }
                   11060: 			 }
1.191     harris41 11061:                      }
1.39      www      11062: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      11063:                  } else {
                   11064:                      $syval='';
1.37      www      11065:                  }
                   11066: 	      }
                   11067:               untie(%bighash)
1.481     raeburn  11068:            }
1.31      www      11069:         }
1.62      www      11070:         if ($syval) {
1.620     albertel 11071: 	    return $env{$cache_str}=$syval;
1.62      www      11072:         }
1.31      www      11073:     }
1.949     raeburn  11074:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11075:     return $env{$cache_str}='';
1.31      www      11076: }
                   11077: 
                   11078: # ---------------------------------------------------------- Return random seed
                   11079: 
1.32      www      11080: sub numval {
                   11081:     my $txt=shift;
                   11082:     $txt=~tr/A-J/0-9/;
                   11083:     $txt=~tr/a-j/0-9/;
                   11084:     $txt=~tr/K-T/0-9/;
                   11085:     $txt=~tr/k-t/0-9/;
                   11086:     $txt=~tr/U-Z/0-5/;
                   11087:     $txt=~tr/u-z/0-5/;
                   11088:     $txt=~s/\D//g;
1.564     albertel 11089:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      11090:     return int($txt);
1.368     albertel 11091: }
                   11092: 
1.484     albertel 11093: sub numval2 {
                   11094:     my $txt=shift;
                   11095:     $txt=~tr/A-J/0-9/;
                   11096:     $txt=~tr/a-j/0-9/;
                   11097:     $txt=~tr/K-T/0-9/;
                   11098:     $txt=~tr/k-t/0-9/;
                   11099:     $txt=~tr/U-Z/0-5/;
                   11100:     $txt=~tr/u-z/0-5/;
                   11101:     $txt=~s/\D//g;
                   11102:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11103:     my $total;
                   11104:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 11105:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 11106:     return int($total);
                   11107: }
                   11108: 
1.575     albertel 11109: sub numval3 {
                   11110:     use integer;
                   11111:     my $txt=shift;
                   11112:     $txt=~tr/A-J/0-9/;
                   11113:     $txt=~tr/a-j/0-9/;
                   11114:     $txt=~tr/K-T/0-9/;
                   11115:     $txt=~tr/k-t/0-9/;
                   11116:     $txt=~tr/U-Z/0-5/;
                   11117:     $txt=~tr/u-z/0-5/;
                   11118:     $txt=~s/\D//g;
                   11119:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11120:     my $total;
                   11121:     foreach my $val (@txts) { $total+=$val; }
                   11122:     if ($_64bit) { $total=(($total<<32)>>32); }
                   11123:     return $total;
                   11124: }
                   11125: 
1.675     albertel 11126: sub digest {
                   11127:     my ($data)=@_;
                   11128:     my $digest=&Digest::MD5::md5($data);
                   11129:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   11130:     my ($e,$f);
                   11131:     {
                   11132:         use integer;
                   11133:         $e=($a+$b);
                   11134:         $f=($c+$d);
                   11135:         if ($_64bit) {
                   11136:             $e=(($e<<32)>>32);
                   11137:             $f=(($f<<32)>>32);
                   11138:         }
                   11139:     }
                   11140:     if (wantarray) {
                   11141: 	return ($e,$f);
                   11142:     } else {
                   11143: 	my $g;
                   11144: 	{
                   11145: 	    use integer;
                   11146: 	    $g=($e+$f);
                   11147: 	    if ($_64bit) {
                   11148: 		$g=(($g<<32)>>32);
                   11149: 	    }
                   11150: 	}
                   11151: 	return $g;
                   11152:     }
                   11153: }
                   11154: 
1.368     albertel 11155: sub latest_rnd_algorithm_id {
1.675     albertel 11156:     return '64bit5';
1.366     albertel 11157: }
1.32      www      11158: 
1.503     albertel 11159: sub get_rand_alg {
                   11160:     my ($courseid)=@_;
1.790     albertel 11161:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 11162:     if ($courseid) {
1.620     albertel 11163: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 11164:     }
                   11165:     return &latest_rnd_algorithm_id();
                   11166: }
                   11167: 
1.562     albertel 11168: sub validCODE {
                   11169:     my ($CODE)=@_;
                   11170:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   11171:     return 0;
                   11172: }
                   11173: 
1.491     albertel 11174: sub getCODE {
1.620     albertel 11175:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 11176:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   11177: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   11178: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 11179: 	return $Apache::lonhomework::history{'resource.CODE'};
                   11180:     }
                   11181:     return undef;
                   11182: }
1.1133    foxr     11183: #
                   11184: #  Determines the random seed for a specific context:
                   11185: #
                   11186: # parameters:
                   11187: #   symb      - in course context the symb for the seed.
                   11188: #   course_id - The course id of the form domain_coursenum.
                   11189: #   domain    - Domain for the user.
                   11190: #   course    - Course for the user.
                   11191: #   cenv      - environment of the course.
                   11192: #
                   11193: # NOTE:
                   11194: #   All parameters are picked out of the environment if missing
                   11195: #   or not defined.
                   11196: #   If a symb cannot be determined the current time is used instead.
                   11197: #
                   11198: #  For a given well defined symb, courside, domain, username,
                   11199: #  and course environment, the seed is reproducible.
                   11200: #
1.31      www      11201: sub rndseed {
1.1133    foxr     11202:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 11203:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 11204:     if (!defined($symb)) {
1.366     albertel 11205: 	unless ($symb=$wsymb) { return time; }
                   11206:     }
1.1146    foxr     11207:     if (!defined $courseid) { 
                   11208: 	$courseid=$wcourseid; 
                   11209:     }
                   11210:     if (!defined $domain) { $domain=$wdomain; }
                   11211:     if (!defined $username) { $username=$wusername }
1.1133    foxr     11212: 
                   11213:     my $which;
                   11214:     if (defined($cenv->{'rndseed'})) {
                   11215: 	$which = $cenv->{'rndseed'};
                   11216:     } else {
                   11217: 	$which =&get_rand_alg($courseid);
                   11218:     }
1.491     albertel 11219:     if (defined(&getCODE())) {
1.675     albertel 11220: 	if ($which eq '64bit5') {
                   11221: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   11222: 	} elsif ($which eq '64bit4') {
1.575     albertel 11223: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   11224: 	} else {
                   11225: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   11226: 	}
1.675     albertel 11227:     } elsif ($which eq '64bit5') {
                   11228: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 11229:     } elsif ($which eq '64bit4') {
                   11230: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 11231:     } elsif ($which eq '64bit3') {
                   11232: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 11233:     } elsif ($which eq '64bit2') {
                   11234: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 11235:     } elsif ($which eq '64bit') {
                   11236: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   11237:     }
                   11238:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   11239: }
                   11240: 
                   11241: sub rndseed_32bit {
                   11242:     my ($symb,$courseid,$domain,$username)=@_;
                   11243:     {
                   11244: 	use integer;
                   11245: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   11246: 	my $symbseed=numval($symb) << 22;
                   11247: 	my $namechck=unpack("%32C*",$username) << 17;
                   11248: 	my $nameseed=numval($username) << 12;
                   11249: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   11250: 	my $courseseed=unpack("%32C*",$courseid);
                   11251: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 11252: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11253: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11254: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 11255: 	return $num;
                   11256:     }
                   11257: }
                   11258: 
                   11259: sub rndseed_64bit {
                   11260:     my ($symb,$courseid,$domain,$username)=@_;
                   11261:     {
                   11262: 	use integer;
                   11263: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   11264: 	my $symbseed=numval($symb) << 10;
                   11265: 	my $namechck=unpack("%32S*",$username);
                   11266: 	
                   11267: 	my $nameseed=numval($username) << 21;
                   11268: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   11269: 	my $courseseed=unpack("%32S*",$courseid);
                   11270: 	
                   11271: 	my $num1=$symbchck+$symbseed+$namechck;
                   11272: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11273: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11274: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11275: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 11276: 	return "$num1,$num2";
1.155     albertel 11277:     }
1.366     albertel 11278: }
                   11279: 
1.443     albertel 11280: sub rndseed_64bit2 {
                   11281:     my ($symb,$courseid,$domain,$username)=@_;
                   11282:     {
                   11283: 	use integer;
                   11284: 	# strings need to be an even # of cahracters long, it it is odd the
                   11285:         # last characters gets thrown away
                   11286: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11287: 	my $symbseed=numval($symb) << 10;
                   11288: 	my $namechck=unpack("%32S*",$username.' ');
                   11289: 	
                   11290: 	my $nameseed=numval($username) << 21;
1.501     albertel 11291: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11292: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11293: 	
                   11294: 	my $num1=$symbchck+$symbseed+$namechck;
                   11295: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11296: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11297: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 11298: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 11299: 	return "$num1,$num2";
                   11300:     }
                   11301: }
                   11302: 
                   11303: sub rndseed_64bit3 {
                   11304:     my ($symb,$courseid,$domain,$username)=@_;
                   11305:     {
                   11306: 	use integer;
                   11307: 	# strings need to be an even # of cahracters long, it it is odd the
                   11308:         # last characters gets thrown away
                   11309: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11310: 	my $symbseed=numval2($symb) << 10;
                   11311: 	my $namechck=unpack("%32S*",$username.' ');
                   11312: 	
                   11313: 	my $nameseed=numval2($username) << 21;
1.443     albertel 11314: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11315: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11316: 	
                   11317: 	my $num1=$symbchck+$symbseed+$namechck;
                   11318: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11319: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11320: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 11321: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11322: 	
1.503     albertel 11323: 	return "$num1:$num2";
1.443     albertel 11324:     }
                   11325: }
                   11326: 
1.575     albertel 11327: sub rndseed_64bit4 {
                   11328:     my ($symb,$courseid,$domain,$username)=@_;
                   11329:     {
                   11330: 	use integer;
                   11331: 	# strings need to be an even # of cahracters long, it it is odd the
                   11332:         # last characters gets thrown away
                   11333: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11334: 	my $symbseed=numval3($symb) << 10;
                   11335: 	my $namechck=unpack("%32S*",$username.' ');
                   11336: 	
                   11337: 	my $nameseed=numval3($username) << 21;
                   11338: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11339: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11340: 	
                   11341: 	my $num1=$symbchck+$symbseed+$namechck;
                   11342: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11343: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11344: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 11345: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11346: 	
1.575     albertel 11347: 	return "$num1:$num2";
                   11348:     }
                   11349: }
                   11350: 
1.675     albertel 11351: sub rndseed_64bit5 {
                   11352:     my ($symb,$courseid,$domain,$username)=@_;
                   11353:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   11354:     return "$num1:$num2";
                   11355: }
                   11356: 
1.366     albertel 11357: sub rndseed_CODE_64bit {
                   11358:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 11359:     {
1.366     albertel 11360: 	use integer;
1.443     albertel 11361: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 11362: 	my $symbseed=numval2($symb);
1.491     albertel 11363: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11364: 	my $CODEseed=numval(&getCODE());
1.443     albertel 11365: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 11366: 	my $num1=$symbseed+$CODEchck;
                   11367: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11368: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11369: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 11370: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11371: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 11372: 	return "$num1:$num2";
1.366     albertel 11373:     }
                   11374: }
                   11375: 
1.575     albertel 11376: sub rndseed_CODE_64bit4 {
                   11377:     my ($symb,$courseid,$domain,$username)=@_;
                   11378:     {
                   11379: 	use integer;
                   11380: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   11381: 	my $symbseed=numval3($symb);
                   11382: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11383: 	my $CODEseed=numval3(&getCODE());
                   11384: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11385: 	my $num1=$symbseed+$CODEchck;
                   11386: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11387: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11388: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 11389: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11390: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   11391: 	return "$num1:$num2";
                   11392:     }
                   11393: }
                   11394: 
1.675     albertel 11395: sub rndseed_CODE_64bit5 {
                   11396:     my ($symb,$courseid,$domain,$username)=@_;
                   11397:     my $code = &getCODE();
                   11398:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   11399:     return "$num1:$num2";
                   11400: }
                   11401: 
1.366     albertel 11402: sub setup_random_from_rndseed {
                   11403:     my ($rndseed)=@_;
1.503     albertel 11404:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  11405: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   11406:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   11407:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   11408:         } else {
                   11409:             &Math::Random::random_set_seed($num1,$num2);
                   11410:         }
1.366     albertel 11411:     } else {
                   11412: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 11413:     }
1.36      albertel 11414: }
                   11415: 
1.474     albertel 11416: sub latest_receipt_algorithm_id {
1.835     albertel 11417:     return 'receipt3';
1.474     albertel 11418: }
                   11419: 
1.480     www      11420: sub recunique {
                   11421:     my $fucourseid=shift;
                   11422:     my $unique;
1.835     albertel 11423:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   11424: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11425: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      11426:     } else {
                   11427: 	$unique=$perlvar{'lonReceipt'};
                   11428:     }
                   11429:     return unpack("%32C*",$unique);
                   11430: }
                   11431: 
                   11432: sub recprefix {
                   11433:     my $fucourseid=shift;
                   11434:     my $prefix;
1.835     albertel 11435:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   11436: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11437: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      11438:     } else {
                   11439: 	$prefix=$perlvar{'lonHostID'};
                   11440:     }
                   11441:     return unpack("%32C*",$prefix);
                   11442: }
                   11443: 
1.76      www      11444: sub ireceipt {
1.474     albertel 11445:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 11446: 
                   11447:     my $return =&recprefix($fucourseid).'-';
                   11448: 
                   11449:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   11450: 	$env{'request.state'} eq 'construct') {
                   11451: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   11452: 	return $return;
                   11453:     }
                   11454: 
1.76      www      11455:     my $cuname=unpack("%32C*",$funame);
                   11456:     my $cudom=unpack("%32C*",$fudom);
                   11457:     my $cucourseid=unpack("%32C*",$fucourseid);
                   11458:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      11459:     my $cunique=&recunique($fucourseid);
1.474     albertel 11460:     my $cpart=unpack("%32S*",$part);
1.835     albertel 11461:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   11462: 
1.790     albertel 11463: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 11464: 			       
                   11465: 	$return.= ($cunique%$cuname+
                   11466: 		   $cunique%$cudom+
                   11467: 		   $cusymb%$cuname+
                   11468: 		   $cusymb%$cudom+
                   11469: 		   $cucourseid%$cuname+
                   11470: 		   $cucourseid%$cudom+
                   11471: 		   $cpart%$cuname+
                   11472: 		   $cpart%$cudom);
                   11473:     } else {
                   11474: 	$return.= ($cunique%$cuname+
                   11475: 		   $cunique%$cudom+
                   11476: 		   $cusymb%$cuname+
                   11477: 		   $cusymb%$cudom+
                   11478: 		   $cucourseid%$cuname+
                   11479: 		   $cucourseid%$cudom);
                   11480:     }
                   11481:     return $return;
1.76      www      11482: }
                   11483: 
                   11484: sub receipt {
1.474     albertel 11485:     my ($part)=@_;
1.790     albertel 11486:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 11487:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      11488: }
1.260     ng       11489: 
1.790     albertel 11490: sub whichuser {
                   11491:     my ($passedsymb)=@_;
                   11492:     my ($symb,$courseid,$domain,$name,$publicuser);
                   11493:     if (defined($env{'form.grade_symb'})) {
                   11494: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   11495: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   11496: 	if (!$allowed &&
                   11497: 	    exists($env{'request.course.sec'}) &&
                   11498: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   11499: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   11500: 			      '/'.$env{'request.course.sec'});
                   11501: 	}
                   11502: 	if ($allowed) {
                   11503: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   11504: 	    $courseid=$tmp_courseid;
                   11505: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   11506: 	    ($name)=&get_env_multiple('form.grade_username');
                   11507: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   11508: 	}
                   11509:     }
                   11510:     if (!$passedsymb) {
                   11511: 	$symb=&symbread();
                   11512:     } else {
                   11513: 	$symb=$passedsymb;
                   11514:     }
                   11515:     $courseid=$env{'request.course.id'};
                   11516:     $domain=$env{'user.domain'};
                   11517:     $name=$env{'user.name'};
                   11518:     if ($name eq 'public' && $domain eq 'public') {
                   11519: 	if (!defined($env{'form.username'})) {
                   11520: 	    $env{'form.username'}.=time.rand(10000000);
                   11521: 	}
                   11522: 	$name.=$env{'form.username'};
                   11523:     }
                   11524:     return ($symb,$courseid,$domain,$name,$publicuser);
                   11525: 
                   11526: }
                   11527: 
1.36      albertel 11528: # ------------------------------------------------------------ Serves up a file
1.472     albertel 11529: # returns either the contents of the file or 
                   11530: # -1 if the file doesn't exist
1.481     raeburn  11531: #
                   11532: # if the target is a file that was uploaded via DOCS, 
                   11533: # a check will be made to see if a current copy exists on the local server,
                   11534: # if it does this will be served, otherwise a copy will be retrieved from
                   11535: # the home server for the course and stored in /home/httpd/html/userfiles on
                   11536: # the local server.   
1.472     albertel 11537: 
1.36      albertel 11538: sub getfile {
1.538     albertel 11539:     my ($file) = @_;
1.609     banghart 11540:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 11541:     &repcopy($file);
                   11542:     return &readfile($file);
                   11543: }
                   11544: 
                   11545: sub repcopy_userfile {
                   11546:     my ($file)=@_;
1.1142    raeburn  11547:     my $londocroot = $perlvar{'lonDocRoot'};
                   11548:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  11549:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 11550:     my ($cdom,$cnum,$filename) = 
1.811     albertel 11551: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 11552:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   11553:     if (-e "$file") {
1.828     www      11554: # we already have a local copy, check it out
1.538     albertel 11555: 	my @fileinfo = stat($file);
1.828     www      11556: 	my $rtncode;
                   11557: 	my $info;
1.538     albertel 11558: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 11559: 	if ($lwpresp ne 'ok') {
1.828     www      11560: # there is no such file anymore, even though we had a local copy
1.482     albertel 11561: 	    if ($rtncode eq '404') {
1.538     albertel 11562: 		unlink($file);
1.482     albertel 11563: 	    }
                   11564: 	    return -1;
                   11565: 	}
                   11566: 	if ($info < $fileinfo[9]) {
1.828     www      11567: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  11568: 	    return 'ok';
1.828     www      11569: 	} else {
                   11570: # the file is outdated, get rid of it
                   11571: 	    unlink($file);
1.482     albertel 11572: 	}
1.828     www      11573:     }
                   11574: # one way or the other, at this point, we don't have the file
                   11575: # construct the correct path for the file
                   11576:     my @parts = ($cdom,$cnum); 
                   11577:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   11578: 	push @parts, split(/\//,$1);
                   11579:     }
                   11580:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   11581:     foreach my $part (@parts) {
                   11582: 	$path .= '/'.$part;
                   11583: 	if (!-e $path) {
                   11584: 	    mkdir($path,0770);
1.482     albertel 11585: 	}
                   11586:     }
1.828     www      11587: # now the path exists for sure
                   11588: # get a user agent
                   11589:     my $ua=new LWP::UserAgent;
                   11590:     my $transferfile=$file.'.in.transfer';
                   11591: # FIXME: this should flock
                   11592:     if (-e $transferfile) { return 'ok'; }
                   11593:     my $request;
                   11594:     $uri=~s/^\///;
1.980     raeburn  11595:     my $homeserver = &homeserver($cnum,$cdom);
                   11596:     my $protocol = $protocol{$homeserver};
                   11597:     $protocol = 'http' if ($protocol ne 'https');
                   11598:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      11599:     my $response=$ua->request($request,$transferfile);
                   11600: # did it work?
                   11601:     if ($response->is_error()) {
                   11602: 	unlink($transferfile);
                   11603: 	&logthis("Userfile repcopy failed for $uri");
                   11604: 	return -1;
                   11605:     }
                   11606: # worked, rename the transfer file
                   11607:     rename($transferfile,$file);
1.607     raeburn  11608:     return 'ok';
1.481     raeburn  11609: }
                   11610: 
1.517     albertel 11611: sub tokenwrapper {
                   11612:     my $uri=shift;
1.980     raeburn  11613:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 11614:     $uri=~s|^/||;
1.620     albertel 11615:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 11616:     my $token=$1;
1.552     albertel 11617:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   11618:     if ($udom && $uname && $file) {
                   11619: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  11620:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  11621:         my $homeserver = &homeserver($uname,$udom);
                   11622:         my $protocol = $protocol{$homeserver};
                   11623:         $protocol = 'http' if ($protocol ne 'https');
                   11624:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 11625:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   11626:                                '&tokenissued='.$perlvar{'lonHostID'};
                   11627:     } else {
                   11628:         return '/adm/notfound.html';
                   11629:     }
                   11630: }
                   11631: 
1.828     www      11632: # call with reqtype HEAD: get last modification time
                   11633: # call with reqtype GET: get the file contents
                   11634: # Do not call this with reqtype GET for large files! It loads everything into memory
                   11635: #
1.481     raeburn  11636: sub getuploaded {
                   11637:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   11638:     $uri=~s/^\///;
1.980     raeburn  11639:     my $homeserver = &homeserver($cnum,$cdom);
                   11640:     my $protocol = $protocol{$homeserver};
                   11641:     $protocol = 'http' if ($protocol ne 'https');
                   11642:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  11643:     my $ua=new LWP::UserAgent;
                   11644:     my $request=new HTTP::Request($reqtype,$uri);
                   11645:     my $response=$ua->request($request);
                   11646:     $$rtncode = $response->code;
1.482     albertel 11647:     if (! $response->is_success()) {
                   11648: 	return 'failed';
                   11649:     }      
                   11650:     if ($reqtype eq 'HEAD') {
1.486     www      11651: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 11652:     } elsif ($reqtype eq 'GET') {
                   11653: 	$$info = $response->content;
1.472     albertel 11654:     }
1.482     albertel 11655:     return 'ok';
1.36      albertel 11656: }
                   11657: 
1.481     raeburn  11658: sub readfile {
                   11659:     my $file = shift;
                   11660:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   11661:     my $fh;
                   11662:     open($fh,"<$file");
                   11663:     my $a='';
1.800     albertel 11664:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  11665:     return $a;
                   11666: }
                   11667: 
1.36      albertel 11668: sub filelocation {
1.590     banghart 11669:     my ($dir,$file) = @_;
                   11670:     my $location;
                   11671:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 11672: 
                   11673:     if ($file =~ m-^/adm/-) {
                   11674: 	$file=~s-^/adm/wrapper/-/-;
                   11675: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   11676:     }
1.882     albertel 11677: 
1.1139    www      11678:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  11679:         $location = $file;
1.609     banghart 11680:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 11681:         my ($udom,$uname,$filename)=
1.811     albertel 11682:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 11683:         my $home=&homeserver($uname,$udom);
                   11684:         my $is_me=0;
                   11685:         my @ids=&current_machine_ids();
                   11686:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   11687:         if ($is_me) {
1.1117    foxr     11688:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 11689:         } else {
                   11690:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   11691:   	      $udom.'/'.$uname.'/'.$filename;
                   11692:         }
1.882     albertel 11693:     } elsif ($file =~ m-^/adm/-) {
                   11694: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 11695:     } else {
                   11696:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      11697:         $file=~s:^/(res|priv)/:/:;
                   11698:         my $space=$1;
1.590     banghart 11699:         if ( !( $file =~ m:^/:) ) {
                   11700:             $location = $dir. '/'.$file;
                   11701:         } else {
1.1142    raeburn  11702:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 11703:         }
1.59      albertel 11704:     }
1.590     banghart 11705:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 11706:     while ($location=~m{/\.\./}) {
                   11707: 	if ($location =~ m{/[^/]+/\.\./}) {
                   11708: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   11709: 	} else {
                   11710: 	    $location=~ s{/\.\./}{/}g;
                   11711: 	}
                   11712:     } #remove dir/..
1.590     banghart 11713:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   11714:     return $location;
1.46      www      11715: }
1.36      albertel 11716: 
1.46      www      11717: sub hreflocation {
                   11718:     my ($dir,$file)=@_;
1.980     raeburn  11719:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 11720: 	$file=filelocation($dir,$file);
1.700     albertel 11721:     } elsif ($file=~m-^/adm/-) {
                   11722: 	$file=~s-^/adm/wrapper/-/-;
                   11723: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 11724:     }
                   11725:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   11726: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   11727:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  11728: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   11729: 	        {/uploaded/$1/$2/}x;
1.46      www      11730:     }
1.913     albertel 11731:     if ($file=~ m{^/userfiles/}) {
                   11732: 	$file =~ s{^/userfiles/}{/uploaded/};
                   11733:     }
1.462     albertel 11734:     return $file;
1.465     albertel 11735: }
                   11736: 
1.1139    www      11737: 
                   11738: 
                   11739: 
                   11740: 
1.465     albertel 11741: sub current_machine_domains {
1.853     albertel 11742:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   11743: }
                   11744: 
                   11745: sub machine_domains {
                   11746:     my ($hostname) = @_;
1.465     albertel 11747:     my @domains;
1.838     albertel 11748:     my %hostname = &all_hostnames();
1.465     albertel 11749:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  11750: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 11751: 	if ($hostname eq $name) {
1.844     albertel 11752: 	    push(@domains,&host_domain($id));
1.465     albertel 11753: 	}
                   11754:     }
                   11755:     return @domains;
                   11756: }
                   11757: 
                   11758: sub current_machine_ids {
1.853     albertel 11759:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   11760: }
                   11761: 
                   11762: sub machine_ids {
                   11763:     my ($hostname) = @_;
                   11764:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 11765:     my @ids;
1.888     albertel 11766:     my %name_to_host = &all_names();
1.889     albertel 11767:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   11768: 	return @{ $name_to_host{$hostname} };
                   11769:     }
                   11770:     return;
1.31      www      11771: }
                   11772: 
1.824     raeburn  11773: sub additional_machine_domains {
                   11774:     my @domains;
                   11775:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   11776:     while( my $line = <$fh>) {
                   11777:         $line =~ s/\s//g;
                   11778:         push(@domains,$line);
                   11779:     }
                   11780:     return @domains;
                   11781: }
                   11782: 
                   11783: sub default_login_domain {
                   11784:     my $domain = $perlvar{'lonDefDomain'};
                   11785:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   11786:     foreach my $posdom (&current_machine_domains(),
                   11787:                         &additional_machine_domains()) {
                   11788:         if (lc($posdom) eq lc($testdomain)) {
                   11789:             $domain=$posdom;
                   11790:             last;
                   11791:         }
                   11792:     }
                   11793:     return $domain;
                   11794: }
                   11795: 
1.31      www      11796: # ------------------------------------------------------------- Declutters URLs
                   11797: 
                   11798: sub declutter {
                   11799:     my $thisfn=shift;
1.569     albertel 11800:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  11801:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   11802:         $thisfn=~s{^/home/httpd/html}{};
                   11803:     }
1.31      www      11804:     $thisfn=~s/^\///;
1.697     albertel 11805:     $thisfn=~s|^adm/wrapper/||;
                   11806:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      11807:     $thisfn=~s/^res\///;
1.1172    bisitz   11808:     $thisfn=~s/^priv\///;
1.1032    raeburn  11809:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   11810:         $thisfn=~s/\?.+$//;
                   11811:     }
1.268     www      11812:     return $thisfn;
                   11813: }
                   11814: 
                   11815: # ------------------------------------------------------------- Clutter up URLs
                   11816: 
                   11817: sub clutter {
                   11818:     my $thisfn='/'.&declutter(shift);
1.887     albertel 11819:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 11820: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      11821:        $thisfn='/res'.$thisfn; 
                   11822:     }
1.1031    raeburn  11823:     if ($thisfn !~m|^/adm|) {
                   11824: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 11825: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 11826: 	} else {
                   11827: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   11828: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 11829: 	    if ($embstyle eq 'ssi'
                   11830: 		|| ($embstyle eq 'hdn')
                   11831: 		|| ($embstyle eq 'rat')
                   11832: 		|| ($embstyle eq 'prv')
                   11833: 		|| ($embstyle eq 'ign')) {
                   11834: 		#do nothing with these
                   11835: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 11836: 		|| ($embstyle eq 'emb')
                   11837: 		|| ($embstyle eq 'wrp')) {
                   11838: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 11839: 	    } elsif ($embstyle eq 'unk'
                   11840: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 11841: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 11842: 	    } else {
1.718     www      11843: #		&logthis("Got a blank emb style");
1.695     albertel 11844: 	    }
1.694     albertel 11845: 	}
                   11846:     }
1.31      www      11847:     return $thisfn;
1.12      www      11848: }
                   11849: 
1.787     albertel 11850: sub clutter_with_no_wrapper {
                   11851:     my $uri = &clutter(shift);
                   11852:     if ($uri =~ m-^/adm/-) {
                   11853: 	$uri =~ s-^/adm/wrapper/-/-;
                   11854: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   11855:     }
                   11856:     return $uri;
                   11857: }
                   11858: 
1.557     albertel 11859: sub freeze_escape {
                   11860:     my ($value)=@_;
                   11861:     if (ref($value)) {
                   11862: 	$value=&nfreeze($value);
                   11863: 	return '__FROZEN__'.&escape($value);
                   11864:     }
                   11865:     return &escape($value);
                   11866: }
                   11867: 
1.11      www      11868: 
1.557     albertel 11869: sub thaw_unescape {
                   11870:     my ($value)=@_;
                   11871:     if ($value =~ /^__FROZEN__/) {
                   11872: 	substr($value,0,10,undef);
                   11873: 	$value=&unescape($value);
                   11874: 	return &thaw($value);
                   11875:     }
                   11876:     return &unescape($value);
                   11877: }
                   11878: 
1.436     albertel 11879: sub correct_line_ends {
                   11880:     my ($result)=@_;
                   11881:     $$result =~s/\r\n/\n/mg;
                   11882:     $$result =~s/\r/\n/mg;
1.415     albertel 11883: }
1.1       albertel 11884: # ================================================================ Main Program
                   11885: 
1.184     www      11886: sub goodbye {
1.204     albertel 11887:    &logthis("Starting Shut down");
1.443     albertel 11888: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 11889:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 11890: #converted
1.599     albertel 11891: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 11892:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   11893: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   11894: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 11895: #1.1 only
1.870     albertel 11896: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   11897: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   11898: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   11899: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   11900:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 11901:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   11902:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      11903:    &flushcourselogs();
                   11904:    &logthis("Shutting down");
                   11905: }
                   11906: 
1.852     albertel 11907: sub get_dns {
1.1172.2.17  raeburn  11908:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 11909:     if (!$ignore_cache) {
                   11910: 	my ($content,$cached)=
                   11911: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   11912: 	if ($cached) {
1.1172.2.17  raeburn  11913: 	    &$func($content,$hashref);
1.869     albertel 11914: 	    return;
                   11915: 	}
                   11916:     }
                   11917: 
                   11918:     my %alldns;
1.852     albertel 11919:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11920:     foreach my $dns (<$config>) {
                   11921: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  11922:         my $line = $1;
                   11923:         my ($host,$protocol) = split(/:/,$line);
                   11924:         if ($protocol ne 'https') {
                   11925:             $protocol = 'http';
                   11926:         }
                   11927: 	$alldns{$host} = $protocol;
1.869     albertel 11928:     }
                   11929:     while (%alldns) {
1.1172.2.52  raeburn  11930: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 11931: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  11932:         $ua->timeout(30);
1.979     raeburn  11933: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 11934: 	my $response=$ua->request($request);
1.979     raeburn  11935:         delete($alldns{$dns});
1.852     albertel 11936: 	next if ($response->is_error());
                   11937: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  11938:         unless ($nocache) {
1.1172.2.23  raeburn  11939: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  11940:         }
                   11941: 	&$func(\@content,$hashref);
1.869     albertel 11942: 	return;
1.852     albertel 11943:     }
                   11944:     close($config);
1.871     albertel 11945:     my $which = (split('/',$url))[3];
                   11946:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   11947:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 11948:     my @content = <$config>;
1.1172.2.17  raeburn  11949:     &$func(\@content,$hashref);
                   11950:     return;
                   11951: }
                   11952: 
                   11953: # ------------------------------------------------------Get DNS checksums file
                   11954: sub parse_dns_checksums_tab {
                   11955:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  11956:     my $lonhost = $perlvar{'lonHostID'};
                   11957:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  11958:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  11959:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   11960:     my $webconfdir = '/etc/httpd/conf';
                   11961:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   11962:         $webconfdir = '/etc/apache2';
                   11963:     } elsif ($distro =~ /^sles(\d+)$/) {
                   11964:         if ($1 >= 10) {
                   11965:             $webconfdir = '/etc/apache2';
                   11966:         }
                   11967:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   11968:         if ($1 >= 10.0) {
                   11969:             $webconfdir = '/etc/apache2';
                   11970:         }
                   11971:     }
1.1172.2.17  raeburn  11972:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   11973:     my (%chksum,%revnum);
                   11974:     if (ref($lines) eq 'ARRAY') {
                   11975:         chomp(@{$lines});
1.1172.2.34  raeburn  11976:         my $version = shift(@{$lines});
                   11977:         if ($version eq $release) {
1.1172.2.17  raeburn  11978:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  11979:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  11980:                 if ($file =~ m{^/etc/httpd/conf}) {
                   11981:                     if ($webconfdir eq '/etc/apache2') {
                   11982:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   11983:                     }
                   11984:                 }
1.1172.2.34  raeburn  11985:                 $chksum{$file} = $shasum;
                   11986:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  11987:             }
                   11988:             if (ref($hashref) eq 'HASH') {
                   11989:                 %{$hashref} = (
                   11990:                                 sums     => \%chksum,
                   11991:                                 versions => \%revnum,
                   11992:                               );
                   11993:             }
                   11994:         }
                   11995:     }
1.869     albertel 11996:     return;
1.852     albertel 11997: }
1.1172.2.17  raeburn  11998: 
                   11999: sub fetch_dns_checksums {
                   12000:     my %checksums;
1.1172.2.34  raeburn  12001:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  12002:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  12003:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12004:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  12005:              \%checksums);
                   12006:     return \%checksums;
                   12007: }
                   12008: 
1.327     albertel 12009: # ------------------------------------------------------------ Read domain file
                   12010: {
1.852     albertel 12011:     my $loaded;
1.846     albertel 12012:     my %domain;
                   12013: 
1.852     albertel 12014:     sub parse_domain_tab {
                   12015: 	my ($lines) = @_;
                   12016: 	foreach my $line (@$lines) {
                   12017: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      12018: 
1.846     albertel 12019: 	    chomp($line);
1.852     albertel 12020: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 12021: 	    my %this_domain;
                   12022: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   12023: 			       'lang_def', 'city', 'longi', 'lati',
                   12024: 			       'primary') {
                   12025: 		$this_domain{$field} = shift(@elements);
                   12026: 	    }
                   12027: 	    $domain{$name} = \%this_domain;
1.852     albertel 12028: 	}
                   12029:     }
1.864     albertel 12030: 
                   12031:     sub reset_domain_info {
                   12032: 	undef($loaded);
                   12033: 	undef(%domain);
                   12034:     }
                   12035: 
1.852     albertel 12036:     sub load_domain_tab {
1.869     albertel 12037: 	my ($ignore_cache) = @_;
                   12038: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 12039: 	my $fh;
                   12040: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   12041: 	    my @lines = <$fh>;
                   12042: 	    &parse_domain_tab(\@lines);
1.448     albertel 12043: 	}
1.852     albertel 12044: 	close($fh);
                   12045: 	$loaded = 1;
1.327     albertel 12046:     }
1.846     albertel 12047: 
                   12048:     sub domain {
1.852     albertel 12049: 	&load_domain_tab() if (!$loaded);
                   12050: 
1.846     albertel 12051: 	my ($name,$what) = @_;
                   12052: 	return if ( !exists($domain{$name}) );
                   12053: 
                   12054: 	if (!$what) {
                   12055: 	    return $domain{$name}{'description'};
                   12056: 	}
                   12057: 	return $domain{$name}{$what};
                   12058:     }
1.974     raeburn  12059: 
                   12060:     sub domain_info {
                   12061:         &load_domain_tab() if (!$loaded);
                   12062:         return %domain;
                   12063:     }
                   12064: 
1.327     albertel 12065: }
                   12066: 
                   12067: 
1.1       albertel 12068: # ------------------------------------------------------------- Read hosts file
                   12069: {
1.838     albertel 12070:     my %hostname;
1.844     albertel 12071:     my %hostdom;
1.845     albertel 12072:     my %libserv;
1.852     albertel 12073:     my $loaded;
1.888     albertel 12074:     my %name_to_host;
1.1074    raeburn  12075:     my %internetdom;
1.1107    raeburn  12076:     my %LC_dns_serv;
1.852     albertel 12077: 
                   12078:     sub parse_hosts_tab {
                   12079: 	my ($file) = @_;
                   12080: 	foreach my $configline (@$file) {
                   12081: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  12082:             chomp($configline);
                   12083: 	    if ($configline =~ /^\^/) {
                   12084:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   12085:                     $LC_dns_serv{$1} = 1;
                   12086:                 }
                   12087:                 next;
                   12088:             }
1.1074    raeburn  12089: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 12090: 	    $name=~s/\s//g;
                   12091: 	    if ($id && $domain && $role && $name) {
                   12092: 		$hostname{$id}=$name;
1.888     albertel 12093: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 12094: 		$hostdom{$id}=$domain;
                   12095: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  12096:                 if (defined($protocol)) {
                   12097:                     if ($protocol eq 'https') {
                   12098:                         $protocol{$id} = $protocol;
                   12099:                     } else {
                   12100:                         $protocol{$id} = 'http'; 
                   12101:                     }
1.968     raeburn  12102:                 } else {
1.969     raeburn  12103:                     $protocol{$id} = 'http';
1.968     raeburn  12104:                 }
1.1074    raeburn  12105:                 if (defined($intdom)) {
                   12106:                     $internetdom{$id} = $intdom;
                   12107:                 }
1.852     albertel 12108: 	    }
                   12109: 	}
                   12110:     }
1.864     albertel 12111:     
                   12112:     sub reset_hosts_info {
1.897     albertel 12113: 	&purge_remembered();
1.864     albertel 12114: 	&reset_domain_info();
                   12115: 	&reset_hosts_ip_info();
1.892     albertel 12116: 	undef(%name_to_host);
1.864     albertel 12117: 	undef(%hostname);
                   12118: 	undef(%hostdom);
                   12119: 	undef(%libserv);
                   12120: 	undef($loaded);
                   12121:     }
1.1       albertel 12122: 
1.852     albertel 12123:     sub load_hosts_tab {
1.869     albertel 12124: 	my ($ignore_cache) = @_;
                   12125: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 12126: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12127: 	my @config = <$config>;
                   12128: 	&parse_hosts_tab(\@config);
                   12129: 	close($config);
                   12130: 	$loaded=1;
1.1       albertel 12131:     }
1.852     albertel 12132: 
1.838     albertel 12133:     sub hostname {
1.852     albertel 12134: 	&load_hosts_tab() if (!$loaded);
                   12135: 
1.838     albertel 12136: 	my ($lonid) = @_;
                   12137: 	return $hostname{$lonid};
                   12138:     }
1.845     albertel 12139: 
1.838     albertel 12140:     sub all_hostnames {
1.852     albertel 12141: 	&load_hosts_tab() if (!$loaded);
                   12142: 
1.838     albertel 12143: 	return %hostname;
                   12144:     }
1.845     albertel 12145: 
1.888     albertel 12146:     sub all_names {
                   12147: 	&load_hosts_tab() if (!$loaded);
                   12148: 
                   12149: 	return %name_to_host;
                   12150:     }
                   12151: 
1.974     raeburn  12152:     sub all_host_domain {
                   12153:         &load_hosts_tab() if (!$loaded);
                   12154:         return %hostdom;
                   12155:     }
                   12156: 
1.845     albertel 12157:     sub is_library {
1.852     albertel 12158: 	&load_hosts_tab() if (!$loaded);
                   12159: 
1.845     albertel 12160: 	return exists($libserv{$_[0]});
                   12161:     }
                   12162: 
                   12163:     sub all_library {
1.852     albertel 12164: 	&load_hosts_tab() if (!$loaded);
                   12165: 
1.845     albertel 12166: 	return %libserv;
                   12167:     }
                   12168: 
1.1062    droeschl 12169:     sub unique_library {
                   12170: 	#2x reverse removes all hostnames that appear more than once
                   12171:         my %unique = reverse &all_library();
                   12172:         return reverse %unique;
                   12173:     }
                   12174: 
1.841     albertel 12175:     sub get_servers {
1.852     albertel 12176: 	&load_hosts_tab() if (!$loaded);
                   12177: 
1.841     albertel 12178: 	my ($domain,$type) = @_;
                   12179: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   12180: 	                                          : %hostname;
                   12181: 	my %result;
1.842     albertel 12182: 	if (ref($domain) eq 'ARRAY') {
                   12183: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 12184: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 12185: 		    $result{$host} = $hostname;
                   12186: 		}
                   12187: 	    }
                   12188: 	} else {
                   12189: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   12190: 		if ($hostdom{$host} eq $domain) {
                   12191: 		    $result{$host} = $hostname;
                   12192: 		}
1.841     albertel 12193: 	    }
                   12194: 	}
                   12195: 	return %result;
                   12196:     }
1.845     albertel 12197: 
1.1062    droeschl 12198:     sub get_unique_servers {
                   12199:         my %unique = reverse &get_servers(@_);
                   12200: 	return reverse %unique;
                   12201:     }
                   12202: 
1.844     albertel 12203:     sub host_domain {
1.852     albertel 12204: 	&load_hosts_tab() if (!$loaded);
                   12205: 
1.844     albertel 12206: 	my ($lonid) = @_;
                   12207: 	return $hostdom{$lonid};
                   12208:     }
                   12209: 
1.841     albertel 12210:     sub all_domains {
1.852     albertel 12211: 	&load_hosts_tab() if (!$loaded);
                   12212: 
1.841     albertel 12213: 	my %seen;
                   12214: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   12215: 	return @uniq;
                   12216:     }
1.1074    raeburn  12217: 
                   12218:     sub internet_dom {
                   12219:         &load_hosts_tab() if (!$loaded);
                   12220: 
                   12221:         my ($lonid) = @_;
                   12222:         return $internetdom{$lonid};
                   12223:     }
1.1107    raeburn  12224: 
                   12225:     sub is_LC_dns {
                   12226:         &load_hosts_tab() if (!$loaded);
                   12227: 
                   12228:         my ($hostname) = @_;
                   12229:         return exists($LC_dns_serv{$hostname});
                   12230:     }
                   12231: 
1.1       albertel 12232: }
                   12233: 
1.847     albertel 12234: { 
                   12235:     my %iphost;
1.856     albertel 12236:     my %name_to_ip;
                   12237:     my %lonid_to_ip;
1.869     albertel 12238: 
1.847     albertel 12239:     sub get_hosts_from_ip {
                   12240: 	my ($ip) = @_;
                   12241: 	my %iphosts = &get_iphost();
                   12242: 	if (ref($iphosts{$ip})) {
                   12243: 	    return @{$iphosts{$ip}};
                   12244: 	}
                   12245: 	return;
1.839     albertel 12246:     }
1.864     albertel 12247:     
                   12248:     sub reset_hosts_ip_info {
                   12249: 	undef(%iphost);
                   12250: 	undef(%name_to_ip);
                   12251: 	undef(%lonid_to_ip);
                   12252:     }
1.856     albertel 12253: 
                   12254:     sub get_host_ip {
                   12255: 	my ($lonid) = @_;
                   12256: 	if (exists($lonid_to_ip{$lonid})) {
                   12257: 	    return $lonid_to_ip{$lonid};
                   12258: 	}
                   12259: 	my $name=&hostname($lonid);
                   12260:    	my $ip = gethostbyname($name);
                   12261: 	return if (!$ip || length($ip) ne 4);
                   12262: 	$ip=inet_ntoa($ip);
                   12263: 	$name_to_ip{$name}   = $ip;
                   12264: 	$lonid_to_ip{$lonid} = $ip;
                   12265: 	return $ip;
                   12266:     }
1.847     albertel 12267:     
                   12268:     sub get_iphost {
1.869     albertel 12269: 	my ($ignore_cache) = @_;
1.894     albertel 12270: 
1.869     albertel 12271: 	if (!$ignore_cache) {
                   12272: 	    if (%iphost) {
                   12273: 		return %iphost;
                   12274: 	    }
                   12275: 	    my ($ip_info,$cached)=
                   12276: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   12277: 	    if ($cached) {
                   12278: 		%iphost      = %{$ip_info->[0]};
                   12279: 		%name_to_ip  = %{$ip_info->[1]};
                   12280: 		%lonid_to_ip = %{$ip_info->[2]};
                   12281: 		return %iphost;
                   12282: 	    }
                   12283: 	}
1.894     albertel 12284: 
                   12285: 	# get yesterday's info for fallback
                   12286: 	my %old_name_to_ip;
                   12287: 	my ($ip_info,$cached)=
                   12288: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   12289: 	if ($cached) {
                   12290: 	    %old_name_to_ip = %{$ip_info->[1]};
                   12291: 	}
                   12292: 
1.888     albertel 12293: 	my %name_to_host = &all_names();
                   12294: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 12295: 	    my $ip;
                   12296: 	    if (!exists($name_to_ip{$name})) {
                   12297: 		$ip = gethostbyname($name);
                   12298: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 12299: 		    if (defined($old_name_to_ip{$name})) {
                   12300: 			$ip = $old_name_to_ip{$name};
                   12301: 			&logthis("Can't find $name defaulting to old $ip");
                   12302: 		    } else {
                   12303: 			&logthis("Name $name no IP found");
                   12304: 			next;
                   12305: 		    }
                   12306: 		} else {
                   12307: 		    $ip=inet_ntoa($ip);
1.847     albertel 12308: 		}
                   12309: 		$name_to_ip{$name} = $ip;
                   12310: 	    } else {
                   12311: 		$ip = $name_to_ip{$name};
1.653     albertel 12312: 	    }
1.888     albertel 12313: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   12314: 		$lonid_to_ip{$id} = $ip;
                   12315: 	    }
                   12316: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 12317: 	}
1.1172.2.23  raeburn  12318: 	&do_cache_new('iphost','iphost',
                   12319: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   12320: 		      48*60*60);
1.869     albertel 12321: 
1.847     albertel 12322: 	return %iphost;
1.598     albertel 12323:     }
                   12324: 
1.992     raeburn  12325:     #
                   12326:     #  Given a DNS returns the loncapa host name for that DNS 
                   12327:     # 
                   12328:     sub host_from_dns {
                   12329:         my ($dns) = @_;
                   12330:         my @hosts;
                   12331:         my $ip;
                   12332: 
1.993     raeburn  12333:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  12334:             $ip = $name_to_ip{$dns};
                   12335:         }
                   12336:         if (!$ip) {
                   12337:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   12338:             if (length($ip) == 4) { 
                   12339: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   12340:             }
                   12341:         }
                   12342:         if ($ip) {
                   12343: 	    @hosts = get_hosts_from_ip($ip);
                   12344: 	    return $hosts[0];
                   12345:         }
                   12346:         return undef;
1.986     foxr     12347:     }
1.992     raeburn  12348: 
1.1074    raeburn  12349:     sub get_internet_names {
                   12350:         my ($lonid) = @_;
                   12351:         return if ($lonid eq '');
                   12352:         my ($idnref,$cached)=
                   12353:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   12354:         if ($cached) {
                   12355:             return $idnref;
                   12356:         }
                   12357:         my $ip = &get_host_ip($lonid);
                   12358:         my @hosts = &get_hosts_from_ip($ip);
                   12359:         my %iphost = &get_iphost();
                   12360:         my (@idns,%seen);
                   12361:         foreach my $id (@hosts) {
                   12362:             my $dom = &host_domain($id);
                   12363:             my $prim_id = &domain($dom,'primary');
                   12364:             my $prim_ip = &get_host_ip($prim_id);
                   12365:             next if ($seen{$prim_ip});
                   12366:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   12367:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   12368:                     my $intdom = &internet_dom($id);
                   12369:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   12370:                         push(@idns,$intdom);
                   12371:                     }
                   12372:                 }
                   12373:             }
                   12374:             $seen{$prim_ip} = 1;
                   12375:         }
1.1172.2.23  raeburn  12376:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  12377:     }
                   12378: 
1.986     foxr     12379: }
                   12380: 
1.1079    raeburn  12381: sub all_loncaparevs {
1.1172.2.39  raeburn  12382:     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  12383: }
                   12384: 
1.1172.2.27  raeburn  12385: # ------------------------------------------------------- Read loncaparev table
                   12386: {
                   12387:     sub load_loncaparevs {
                   12388:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   12389:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   12390:                 while (my $configline=<$config>) {
                   12391:                     chomp($configline);
                   12392:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   12393:                     $loncaparevs{$hostid}=$loncaparev;
                   12394:                 }
                   12395:                 close($config);
                   12396:             }
                   12397:         }
                   12398:     }
                   12399: }
                   12400: 
                   12401: # ----------------------------------------------------- Read serverhostID table
                   12402: {
                   12403:     sub load_serverhomeIDs {
                   12404:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   12405:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   12406:                 while (my $configline=<$config>) {
                   12407:                     chomp($configline);
                   12408:                     my ($name,$id)=split(/:/,$configline);
                   12409:                     $serverhomeIDs{$name}=$id;
                   12410:                 }
                   12411:                 close($config);
                   12412:             }
                   12413:         }
                   12414:     }
                   12415: }
                   12416: 
                   12417: 
1.862     albertel 12418: BEGIN {
                   12419: 
                   12420: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   12421:     unless ($readit) {
                   12422: {
                   12423:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   12424:     %perlvar = (%perlvar,%{$configvars});
                   12425: }
                   12426: 
                   12427: 
1.1       albertel 12428: # ------------------------------------------------------ Read spare server file
                   12429: {
1.448     albertel 12430:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 12431: 
                   12432:     while (my $configline=<$config>) {
                   12433:        chomp($configline);
1.284     matthew  12434:        if ($configline) {
1.784     albertel 12435: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 12436: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 12437: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 12438:        }
                   12439:     }
1.448     albertel 12440:     close($config);
1.1       albertel 12441: }
1.11      www      12442: # ------------------------------------------------------------ Read permissions
                   12443: {
1.448     albertel 12444:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      12445: 
                   12446:     while (my $configline=<$config>) {
1.448     albertel 12447: 	chomp($configline);
                   12448: 	if ($configline) {
                   12449: 	    my ($role,$perm)=split(/ /,$configline);
                   12450: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   12451: 	}
1.11      www      12452:     }
1.448     albertel 12453:     close($config);
1.11      www      12454: }
                   12455: 
                   12456: # -------------------------------------------- Read plain texts for permissions
                   12457: {
1.448     albertel 12458:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      12459: 
                   12460:     while (my $configline=<$config>) {
1.448     albertel 12461: 	chomp($configline);
                   12462: 	if ($configline) {
1.742     raeburn  12463: 	    my ($short,@plain)=split(/:/,$configline);
                   12464:             %{$prp{$short}} = ();
                   12465: 	    if (@plain > 0) {
                   12466:                 $prp{$short}{'std'} = $plain[0];
                   12467:                 for (my $i=1; $i<@plain; $i++) {
                   12468:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   12469:                 }
                   12470:             }
1.448     albertel 12471: 	}
1.135     www      12472:     }
1.448     albertel 12473:     close($config);
1.135     www      12474: }
                   12475: 
                   12476: # ---------------------------------------------------------- Read package table
                   12477: {
1.448     albertel 12478:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      12479: 
                   12480:     while (my $configline=<$config>) {
1.483     albertel 12481: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 12482: 	chomp($configline);
                   12483: 	my ($short,$plain)=split(/:/,$configline);
                   12484: 	my ($pack,$name)=split(/\&/,$short);
                   12485: 	if ($plain ne '') {
                   12486: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   12487: 	    $packagetab{$short}=$plain; 
                   12488: 	}
1.11      www      12489:     }
1.448     albertel 12490:     close($config);
1.329     matthew  12491: }
                   12492: 
1.1172.2.27  raeburn  12493: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  12494: 
1.1172.2.27  raeburn  12495: &load_loncaparevs();
                   12496: 
                   12497: # ------------------------------------------------------- Read serverhostID table
                   12498: 
                   12499: &load_serverhomeIDs();
1.1074    raeburn  12500: 
1.1172.2.27  raeburn  12501: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  12502: {
                   12503:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   12504:     if (-e $file) {
                   12505:         my $parser = HTML::LCParser->new($file);
                   12506:         while (my $token = $parser->get_token()) {
                   12507:             if ($token->[0] eq 'S') {
                   12508:                 my $item = $token->[1];
                   12509:                 my $name = $token->[2]{'name'};
                   12510:                 my $value = $token->[2]{'value'};
                   12511:                 if ($item ne '' && $name ne '' && $value ne '') {
                   12512:                     my $release = $parser->get_text();
                   12513:                     $release =~ s/(^\s*|\s*$ )//gx;
                   12514:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   12515:                 }
                   12516:             }
                   12517:         }
                   12518:     }
1.1073    raeburn  12519: }
                   12520: 
1.1138    raeburn  12521: # ---------------------------------------------------------- Read managers table
                   12522: {
                   12523:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   12524:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   12525:             while (my $configline=<$config>) {
                   12526:                 chomp($configline);
                   12527:                 next if ($configline =~ /^\#/);
                   12528:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   12529:                     $managerstab{$configline} = 1;
                   12530:                 }
                   12531:             }
                   12532:             close($config);
                   12533:         }
                   12534:     }
                   12535: }
                   12536: 
1.329     matthew  12537: # ------------- set up temporary directory
                   12538: {
1.1117    foxr     12539:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  12540: 
1.11      www      12541: }
                   12542: 
1.794     albertel 12543: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   12544: 				'compress_threshold'=> 20_000,
                   12545:  			        });
1.185     www      12546: 
1.281     www      12547: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      12548: $dumpcount=0;
1.958     www      12549: $locknum=0;
1.22      www      12550: 
1.163     harris41 12551: &logtouch();
1.672     albertel 12552: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      12553: $readit=1;
1.564     albertel 12554:     {
                   12555: 	use integer;
                   12556: 	my $test=(2**32)+1;
1.568     albertel 12557: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 12558: 	&logthis(" Detected 64bit platform ($_64bit)");
                   12559:     }
1.195     www      12560: }
1.1       albertel 12561: }
1.179     www      12562: 
1.1       albertel 12563: 1;
1.191     harris41 12564: __END__
                   12565: 
1.243     albertel 12566: =pod
                   12567: 
1.191     harris41 12568: =head1 NAME
                   12569: 
1.243     albertel 12570: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 12571: 
                   12572: =head1 SYNOPSIS
                   12573: 
1.243     albertel 12574: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 12575: 
                   12576:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   12577: 
1.243     albertel 12578: Common parameters:
                   12579: 
                   12580: =over 4
                   12581: 
                   12582: =item *
                   12583: 
                   12584: $uname : an internal username (if $cname expecting a course Id specifically)
                   12585: 
                   12586: =item *
                   12587: 
                   12588: $udom : a domain (if $cdom expecting a course's domain specifically)
                   12589: 
                   12590: =item *
                   12591: 
                   12592: $symb : a resource instance identifier
                   12593: 
                   12594: =item *
                   12595: 
                   12596: $namespace : the name of a .db file that contains the data needed or
                   12597: being set.
                   12598: 
                   12599: =back
                   12600: 
1.394     bowersj2 12601: =head1 OVERVIEW
1.191     harris41 12602: 
1.394     bowersj2 12603: lonnet provides subroutines which interact with the
                   12604: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   12605: about classes, users, and resources.
1.243     albertel 12606: 
                   12607: For many of these objects you can also use this to store data about
                   12608: them or modify them in various ways.
1.191     harris41 12609: 
1.394     bowersj2 12610: =head2 Symbs
1.191     harris41 12611: 
1.394     bowersj2 12612: To identify a specific instance of a resource, LON-CAPA uses symbols
                   12613: or "symbs"X<symb>. These identifiers are built from the URL of the
                   12614: map, the resource number of the resource in the map, and the URL of
                   12615: the resource itself. The latter is somewhat redundant, but might help
                   12616: if maps change.
                   12617: 
                   12618: An example is
                   12619: 
                   12620:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   12621: 
                   12622: The respective map entry is
                   12623: 
                   12624:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   12625:   title="Problem 2">
                   12626:  </resource>
                   12627: 
                   12628: Symbs are used by the random number generator, as well as to store and
                   12629: restore data specific to a certain instance of for example a problem.
                   12630: 
                   12631: =head2 Storing And Retrieving Data
                   12632: 
                   12633: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   12634: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   12635: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   12636: is is the non-critical message twin of cstore. These functions are for
                   12637: handlers to store a perl hash to a user's permanent data space in an
                   12638: easy manner, and to retrieve it again on another call. It is expected
                   12639: that a handler would use this once at the beginning to retrieve data,
                   12640: and then again once at the end to send only the new data back.
                   12641: 
                   12642: The data is stored in the user's data directory on the user's
                   12643: homeserver under the ID of the course.
                   12644: 
                   12645: The hash that is returned by restore will have all of the previous
                   12646: value for all of the elements of the hash.
                   12647: 
                   12648: Example:
                   12649: 
                   12650:  #creating a hash
                   12651:  my %hash;
                   12652:  $hash{'foo'}='bar';
                   12653: 
                   12654:  #storing it
                   12655:  &Apache::lonnet::cstore(\%hash);
                   12656: 
                   12657:  #changing a value
                   12658:  $hash{'foo'}='notbar';
                   12659: 
                   12660:  #adding a new value
                   12661:  $hash{'bar'}='foo';
                   12662:  &Apache::lonnet::cstore(\%hash);
                   12663: 
                   12664:  #retrieving the hash
                   12665:  my %history=&Apache::lonnet::restore();
                   12666: 
                   12667:  #print the hash
                   12668:  foreach my $key (sort(keys(%history))) {
                   12669:    print("\%history{$key} = $history{$key}");
                   12670:  }
                   12671: 
                   12672: Will print out:
1.191     harris41 12673: 
1.394     bowersj2 12674:  %history{1:foo} = bar
                   12675:  %history{1:keys} = foo:timestamp
                   12676:  %history{1:timestamp} = 990455579
                   12677:  %history{2:bar} = foo
                   12678:  %history{2:foo} = notbar
                   12679:  %history{2:keys} = foo:bar:timestamp
                   12680:  %history{2:timestamp} = 990455580
                   12681:  %history{bar} = foo
                   12682:  %history{foo} = notbar
                   12683:  %history{timestamp} = 990455580
                   12684:  %history{version} = 2
                   12685: 
                   12686: Note that the special hash entries C<keys>, C<version> and
                   12687: C<timestamp> were added to the hash. C<version> will be equal to the
                   12688: total number of versions of the data that have been stored. The
                   12689: C<timestamp> attribute will be the UNIX time the hash was
                   12690: stored. C<keys> is available in every historical section to list which
                   12691: keys were added or changed at a specific historical revision of a
                   12692: hash.
                   12693: 
                   12694: B<Warning>: do not store the hash that restore returns directly. This
                   12695: will cause a mess since it will restore the historical keys as if the
                   12696: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 12697: 
1.394     bowersj2 12698: Calling convention:
1.191     harris41 12699: 
1.1172.2.27  raeburn  12700:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
                   12701:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
1.191     harris41 12702: 
1.394     bowersj2 12703: For more detailed information, see lonnet specific documentation.
1.191     harris41 12704: 
1.394     bowersj2 12705: =head1 RETURN MESSAGES
1.191     harris41 12706: 
1.394     bowersj2 12707: =over 4
1.191     harris41 12708: 
1.394     bowersj2 12709: =item * B<con_lost>: unable to contact remote host
1.191     harris41 12710: 
1.394     bowersj2 12711: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   12712: when the connection is brought back up
1.191     harris41 12713: 
1.394     bowersj2 12714: =item * B<con_failed>: unable to contact remote host and unable to save message
                   12715: for later delivery
1.191     harris41 12716: 
1.967     bisitz   12717: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 12718: 
1.394     bowersj2 12719: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 12720: that was requested
1.191     harris41 12721: 
1.243     albertel 12722: =back
1.191     harris41 12723: 
1.243     albertel 12724: =head1 PUBLIC SUBROUTINES
1.191     harris41 12725: 
1.243     albertel 12726: =head2 Session Environment Functions
1.191     harris41 12727: 
1.243     albertel 12728: =over 4
1.191     harris41 12729: 
1.394     bowersj2 12730: =item * 
                   12731: X<appenv()>
1.949     raeburn  12732: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 12733: the user envirnoment file, and will be restored for each access this
1.620     albertel 12734: user makes during this session, also modifies the %env for the current
1.949     raeburn  12735: process. Optional rolesarrayref - if defined contains a reference to an array
                   12736: of roles which are exempt from the restriction on modifying user.role entries 
                   12737: in the user's environment.db and in %env.    
1.191     harris41 12738: 
                   12739: =item *
1.394     bowersj2 12740: X<delenv()>
1.987     raeburn  12741: B<delenv($delthis,$regexp)>: removes all items from the session
                   12742: environment file that begin with $delthis. If the 
                   12743: optional second arg - $regexp - is true, $delthis is treated as a 
                   12744: regular expression, otherwise \Q$delthis\E is used. 
                   12745: The values are also deleted from the current processes %env.
1.191     harris41 12746: 
1.795     albertel 12747: =item * get_env_multiple($name) 
                   12748: 
                   12749: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   12750: values may be defined and end up as an array ref.
                   12751: 
                   12752: returns an array of values
                   12753: 
1.243     albertel 12754: =back
                   12755: 
                   12756: =head2 User Information
1.191     harris41 12757: 
1.243     albertel 12758: =over 4
1.191     harris41 12759: 
                   12760: =item *
1.394     bowersj2 12761: X<queryauthenticate()>
                   12762: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 12763: authentication scheme
                   12764: 
                   12765: =item *
1.394     bowersj2 12766: X<authenticate()>
1.1073    raeburn  12767: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 12768: authenticate user from domain's lib servers (first use the current
                   12769: one). C<$upass> should be the users password.
1.1073    raeburn  12770: $checkdefauth is optional (value is 1 if a check should be made to
                   12771:    authenticate user using default authentication method, and allow
                   12772:    account creation if username does not have account in the domain).
                   12773: $clientcancheckhost is optional (value is 1 if checking whether the
                   12774:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 12775: 
                   12776: =item *
1.394     bowersj2 12777: X<homeserver()>
                   12778: B<homeserver($uname,$udom)>: find the server which has
                   12779: the user's directory and files (there must be only one), this caches
                   12780: the answer, and also caches if there is a borken connection.
1.191     harris41 12781: 
                   12782: =item *
1.394     bowersj2 12783: X<idget()>
                   12784: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   12785: (IDs are a unique resource in a domain, there must be only 1 ID per
                   12786: username, and only 1 username per ID in a specific domain) (returns
                   12787: hash: id=>name,id=>name)
1.191     harris41 12788: 
                   12789: =item *
1.394     bowersj2 12790: X<idrget()>
                   12791: B<idrget($udom,@unames)>: find the IDs behind a list of
                   12792: usernames (returns hash: name=>id,name=>id)
1.191     harris41 12793: 
                   12794: =item *
1.394     bowersj2 12795: X<idput()>
                   12796: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 12797: 
                   12798: =item *
1.394     bowersj2 12799: X<rolesinit()>
1.1169    droeschl 12800: B<rolesinit($udom,$username)>: get user privileges.
                   12801: returns user role, first access and timer interval hashes
1.243     albertel 12802: 
                   12803: =item *
1.1171    droeschl 12804: X<privileged()>
                   12805: B<privileged($username,$domain)>: returns a true if user has a
                   12806: privileged and active role (i.e. su or dc), false otherwise.
                   12807: 
                   12808: =item *
1.551     albertel 12809: X<getsection()>
                   12810: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 12811: course $cname, return section name/number or '' for "not in course"
                   12812: and '-1' for "no section"
                   12813: 
                   12814: =item *
1.394     bowersj2 12815: X<userenvironment()>
                   12816: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 12817: passed in @what from the requested user's environment, returns a hash
                   12818: 
1.858     raeburn  12819: =item * 
                   12820: X<userlog_query()>
1.859     albertel 12821: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   12822: activity.log file. %filters defines filters applied when parsing the
                   12823: log file. These can be start or end timestamps, or the type of action
                   12824: - log to look for Login or Logout events, check for Checkin or
                   12825: Checkout, role for role selection. The response is in the form
                   12826: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   12827: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  12828: 
1.243     albertel 12829: =back
                   12830: 
                   12831: =head2 User Roles
                   12832: 
                   12833: =over 4
                   12834: 
                   12835: =item *
                   12836: 
1.810     raeburn  12837: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 12838:  F: full access
                   12839:  U,I,K: authentication modes (cxx only)
                   12840:  '': forbidden
                   12841:  1: user needs to choose course
                   12842:  2: browse allowed
1.766     albertel 12843:  A: passphrase authentication needed
1.243     albertel 12844: 
                   12845: =item *
                   12846: 
1.1172.2.13  raeburn  12847: constructaccess($url,$setpriv) : check for access to construction space URL
                   12848: 
                   12849: See if the owner domain and name in the URL match those in the
                   12850: expected environment.  If so, return three element list
                   12851: ($ownername,$ownerdomain,$ownerhome).
                   12852: 
                   12853: Otherwise return the null string.
                   12854: 
                   12855: If second argument 'setpriv' is true, it assigns the privileges,
                   12856: and returns the same three element list, unless the owner has
                   12857: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   12858: in which case the null string is returned.
                   12859: 
                   12860: =item *
                   12861: 
1.243     albertel 12862: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   12863: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   12864: and course level
                   12865: 
                   12866: =item *
                   12867: 
1.988     raeburn  12868: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   12869: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  12870: $type is Course (default) or Community.
1.988     raeburn  12871: If $forcedefault evaluates to true, text returned will be default 
                   12872: text for $type. Otherwise, if this is a course, the text returned 
                   12873: will be a custom name for the role (if defined in the course's 
                   12874: environment).  If no custom name is defined the default is returned.
                   12875:    
1.832     raeburn  12876: =item *
                   12877: 
1.1172.2.23  raeburn  12878: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  12879: All arguments are optional. Returns a hash of a roles, either for
                   12880: co-author/assistant author roles for a user's Construction Space
1.906     albertel 12881: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  12882: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   12883: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   12884: For each key, value is set to colon-separated start and end times for
                   12885: the role.  If no username and domain are specified, will default to
1.934     raeburn  12886: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  12887: of role statuses (active, future or previous), roles 
                   12888: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   12889: to restrict the list of roles reported. If no array ref is 
                   12890: provided for types, will default to return only active roles.
1.834     albertel 12891: 
1.1172.2.13  raeburn  12892: =item *
                   12893: 
                   12894: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   12895: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   12896: 
                   12897: Additional optional arguments are: $type (if role checking is to be restricted
                   12898: to certain user status types -- previous (expired roles), active (currently
                   12899: available roles) or future (roles available in the future), and
                   12900: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  12901: have active Domain Coordinator role in course's domain or in additional
                   12902: domains (specified in 'Domains to check for privileged users' in course
                   12903: environment -- set via:  Course Settings -> Classlists and staff listing).
                   12904: 
                   12905: =item *
                   12906: 
                   12907: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   12908: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   12909: $possdomains and $possroles are optional array refs -- to domains to check and
                   12910: roles to check.  If $possdomains is not specified, a dump will be done of the
                   12911: users' roles.db to check for a dc or su role in any domain. This can be
                   12912: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   12913: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   12914: this then allows &privileged_by_domain() to be used, which caches the identity
                   12915: of privileged users, eliminating the need for repeated calls to &dump().
                   12916: 
                   12917: =item *
                   12918: 
                   12919: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   12920: where the outer hash keys are domains specified in the $possdomains array ref,
                   12921: next inner hash keys are privileged roles specified in the $roles array ref,
                   12922: and the innermost hash contains key = value pairs for username:domain = end:start
                   12923: for active or future "privileged" users with that role in that domain. To avoid
                   12924: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   12925: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  12926: 
1.243     albertel 12927: =back
                   12928: 
                   12929: =head2 User Modification
                   12930: 
                   12931: =over 4
                   12932: 
                   12933: =item *
                   12934: 
1.957     raeburn  12935: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 12936: user for the level given by URL.  Optional start and end dates (leave empty
                   12937: string or zero for "no date")
1.191     harris41 12938: 
                   12939: =item *
                   12940: 
1.243     albertel 12941: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   12942: change a users, password, possible return values are: ok,
                   12943: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   12944: refused
1.191     harris41 12945: 
                   12946: =item *
                   12947: 
1.243     albertel 12948: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 12949: 
                   12950: =item *
                   12951: 
1.1058    raeburn  12952: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   12953:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   12954: 
                   12955: will update user information (firstname,middlename,lastname,generation,
                   12956: permanentemail), and if forceid is true, student/employee ID also.
                   12957: A user's institutional affiliation(s) can also be updated.
                   12958: User information fields will not be overwritten with empty entries 
                   12959: unless the field is included in the $candelete array reference.
                   12960: This array is included when a single user is modified via "Manage Users",
                   12961: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 12962: 
                   12963: =item *
                   12964: 
1.286     matthew  12965: modifystudent
                   12966: 
1.957     raeburn  12967: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  12968: The course id is resolved based on the current user's environment.  
                   12969: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  12970: associated with a course.
                   12971: 
1.297     matthew  12972: This call is essentially a wrapper for lonnet::modifyuser and
                   12973: lonnet::modify_student_enrollment
1.286     matthew  12974: 
                   12975: Inputs: 
                   12976: 
                   12977: =over 4
                   12978: 
1.957     raeburn  12979: =item B<$udom> Student's loncapa domain
1.286     matthew  12980: 
1.957     raeburn  12981: =item B<$uname> Student's loncapa login name
1.286     matthew  12982: 
1.964     bisitz   12983: =item B<$uid> Student/Employee ID
1.286     matthew  12984: 
1.957     raeburn  12985: =item B<$umode> Student's authentication mode
1.286     matthew  12986: 
1.957     raeburn  12987: =item B<$upass> Student's password
1.286     matthew  12988: 
1.957     raeburn  12989: =item B<$first> Student's first name
1.286     matthew  12990: 
1.957     raeburn  12991: =item B<$middle> Student's middle name
1.286     matthew  12992: 
1.957     raeburn  12993: =item B<$last> Student's last name
1.286     matthew  12994: 
1.957     raeburn  12995: =item B<$gene> Student's generation
1.286     matthew  12996: 
1.957     raeburn  12997: =item B<$usec> Student's section in course
1.286     matthew  12998: 
                   12999: =item B<$end> Unix time of the roles expiration
                   13000: 
                   13001: =item B<$start> Unix time of the roles start date
                   13002: 
                   13003: =item B<$forceid> If defined, allow $uid to be changed
                   13004: 
                   13005: =item B<$desiredhome> server to use as home server for student
                   13006: 
1.957     raeburn  13007: =item B<$email> Student's permanent e-mail address
                   13008: 
                   13009: =item B<$type> Type of enrollment (auto or manual)
                   13010: 
1.963     raeburn  13011: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   13012: 
                   13013: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  13014: 
1.963     raeburn  13015: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  13016: 
1.963     raeburn  13017: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  13018: 
1.1172.2.19  raeburn  13019: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   13020: 
                   13021: =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  13022: 
1.286     matthew  13023: =back
1.297     matthew  13024: 
                   13025: =item *
                   13026: 
                   13027: modify_student_enrollment
                   13028: 
1.1172.2.31  raeburn  13029: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  13030: 'role.request.course' must be defined for this function to proceed.
                   13031: 
                   13032: Inputs:
                   13033: 
                   13034: =over 4
                   13035: 
1.1172.2.31  raeburn  13036: =item $udom, student's domain
1.297     matthew  13037: 
1.1172.2.31  raeburn  13038: =item $uname, student's name
1.297     matthew  13039: 
1.1172.2.31  raeburn  13040: =item $uid, student's user id
1.297     matthew  13041: 
1.1172.2.31  raeburn  13042: =item $first, student's first name
1.297     matthew  13043: 
                   13044: =item $middle
                   13045: 
                   13046: =item $last
                   13047: 
                   13048: =item $gene
                   13049: 
                   13050: =item $usec
                   13051: 
                   13052: =item $end
                   13053: 
                   13054: =item $start
                   13055: 
1.957     raeburn  13056: =item $type
                   13057: 
                   13058: =item $locktype
                   13059: 
                   13060: =item $cid
                   13061: 
                   13062: =item $selfenroll
                   13063: 
                   13064: =item $context
                   13065: 
1.1172.2.19  raeburn  13066: =item $credits, number of credits student will earn from this class
                   13067: 
1.297     matthew  13068: =back
                   13069: 
1.191     harris41 13070: 
                   13071: =item *
                   13072: 
1.243     albertel 13073: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   13074: custom role; give a custom role to a user for the level given by URL.  Specify
                   13075: name and domain of role author, and role name
1.191     harris41 13076: 
                   13077: =item *
                   13078: 
1.243     albertel 13079: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 13080: 
                   13081: =item *
                   13082: 
1.243     albertel 13083: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   13084: 
                   13085: =back
                   13086: 
                   13087: =head2 Course Infomation
                   13088: 
                   13089: =over 4
1.191     harris41 13090: 
                   13091: =item *
                   13092: 
1.1118    foxr     13093: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 13094: specified course id, including all environment settings for the
                   13095: course, the description of the course will be in the hash under the
                   13096: key 'description'
1.191     harris41 13097: 
1.1118    foxr     13098: $options is an optional parameter that if supplied is a hash reference that controls
                   13099: what how this function works.  It has the following key/values:
                   13100: 
                   13101: =over 4
                   13102: 
                   13103: =item freshen_cache
                   13104: 
                   13105: If defined, and the environment cache for the course is valid, it is 
                   13106: returned in the returned hash.
                   13107: 
                   13108: =item one_time
                   13109: 
                   13110: If defined, the last cache time is set to _now_
                   13111: 
                   13112: =item user
                   13113: 
                   13114: If defined, the supplied username is used instead of the current user.
                   13115: 
                   13116: 
                   13117: =back
                   13118: 
1.191     harris41 13119: =item *
                   13120: 
1.624     albertel 13121: resdata($name,$domain,$type,@which) : request for current parameter
                   13122: setting for a specific $type, where $type is either 'course' or 'user',
                   13123: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  13124: answers for 10 minutes.
1.243     albertel 13125: 
1.877     foxr     13126: =item *
                   13127: 
                   13128: get_courseresdata($courseid, $domain) : dump the entire course resource
                   13129: data base, returning a hash that is keyed by the resource name and has
                   13130: values that are the resource value.  I believe that the timestamps and
                   13131: versions are also returned.
                   13132: 
1.1172.2.31  raeburn  13133: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   13134: supplemental content area. This routine caches the number of files for
                   13135: 10 minutes.
                   13136: 
1.243     albertel 13137: =back
                   13138: 
                   13139: =head2 Course Modification
                   13140: 
                   13141: =over 4
1.191     harris41 13142: 
                   13143: =item *
                   13144: 
1.243     albertel 13145: writecoursepref($courseid,%prefs) : write preferences (environment
                   13146: database) for a course
1.191     harris41 13147: 
                   13148: =item *
                   13149: 
1.1011    raeburn  13150: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   13151: 
                   13152: =item *
                   13153: 
1.1038    raeburn  13154: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 13155: 
1.1167    droeschl 13156: =item *
                   13157: 
                   13158: is_course($courseid), is_course($cdom, $cnum)
                   13159: 
                   13160: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   13161: two component version $cdom, $cnum. It checks if the specified course exists.
                   13162: 
                   13163: Returns:
                   13164:     undef if the course doesn't exist, otherwise
                   13165:     in scalar context the combined courseid.
                   13166:     in list context the two components of the course identifier, domain and 
                   13167:     courseid.    
                   13168: 
1.243     albertel 13169: =back
                   13170: 
                   13171: =head2 Resource Subroutines
                   13172: 
                   13173: =over 4
1.191     harris41 13174: 
                   13175: =item *
                   13176: 
1.243     albertel 13177: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 13178: 
                   13179: =item *
                   13180: 
1.243     albertel 13181: repcopy($filename) : subscribes to the requested file, and attempts to
                   13182: replicate from the owning library server, Might return
1.607     raeburn  13183: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   13184: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 13185: resource. Expects the local filesystem pathname
                   13186: (/home/httpd/html/res/....)
                   13187: 
                   13188: =back
                   13189: 
                   13190: =head2 Resource Information
                   13191: 
                   13192: =over 4
1.191     harris41 13193: 
                   13194: =item *
                   13195: 
1.1172.2.28  raeburn  13196: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   13197: and returns the value of a variety of different possible values,
                   13198: $varname should be a request string, and the other parameters can be
                   13199: used to specify who and what one is asking about. Ordinarily, $cid 
                   13200: does not need to be specified, as it is retrived from 
                   13201: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   13202: within lonuserstate::loadmap() when initializing a course, before
                   13203: $env{'request.course.id'} has been set, so it needs to be provided
                   13204: in that one case.
1.243     albertel 13205: 
                   13206: Possible values for $varname are environment.lastname (or other item
                   13207: from the envirnment hash), user.name (or someother aspect about the
                   13208: user), resource.0.maxtries (or some other part and parameter of a
                   13209: resource)
1.204     albertel 13210: 
                   13211: =item *
                   13212: 
1.243     albertel 13213: directcondval($number) : get current value of a condition; reads from a state
                   13214: string
1.204     albertel 13215: 
                   13216: =item *
                   13217: 
1.243     albertel 13218: condval($condidx) : value of condition index based on state
1.204     albertel 13219: 
                   13220: =item *
                   13221: 
1.243     albertel 13222: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   13223: resource's metadata, $what should be either a specific key, or either
                   13224: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   13225: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   13226: 
                   13227: this function automatically caches all requests
1.191     harris41 13228: 
                   13229: =item *
                   13230: 
1.243     albertel 13231: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   13232: network of library servers; returns file handle of where SQL and regex results
                   13233: will be stored for query
1.191     harris41 13234: 
                   13235: =item *
                   13236: 
1.243     albertel 13237: symbread($filename) : return symbolic list entry (filename argument optional);
                   13238: returns the data handle
1.191     harris41 13239: 
                   13240: =item *
                   13241: 
1.1172.2.17  raeburn  13242: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  13243: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 13244: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  13245: on failure, user must be in a course, as it assumes the existence of
                   13246: the course initial hash, and uses $env('request.course.id'}.  The third
                   13247: arg is an optional reference to a scalar.  If this arg is passed in the
                   13248: call to symbverify, it will be set to 1 if the symb has been set to be 
                   13249: encrypted; otherwise it will be null.
1.243     albertel 13250: 
1.191     harris41 13251: =item *
                   13252: 
1.243     albertel 13253: symbclean($symb) : removes versions numbers from a symb, returns the
                   13254: cleaned symb
1.191     harris41 13255: 
                   13256: =item *
                   13257: 
1.243     albertel 13258: is_on_map($uri) : checks if the $uri is somewhere on the current
                   13259: course map, user must be in a course for it to work.
1.191     harris41 13260: 
                   13261: =item *
                   13262: 
1.243     albertel 13263: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 13264: 
                   13265: =item *
                   13266: 
1.243     albertel 13267: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   13268: a random seed, all arguments are optional, if they aren't sent it uses the
                   13269: environment to derive them. Note: if symb isn't sent and it can't get one
                   13270: from &symbread it will use the current time as its return value
1.191     harris41 13271: 
                   13272: =item *
                   13273: 
1.243     albertel 13274: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   13275: unfakeable, receipt
1.191     harris41 13276: 
                   13277: =item *
                   13278: 
1.620     albertel 13279: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 13280: 
                   13281: =item *
                   13282: 
1.243     albertel 13283: countacc($url) : count the number of accesses to a given URL
1.191     harris41 13284: 
                   13285: =item *
                   13286: 
1.243     albertel 13287: 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 13288: 
                   13289: =item *
                   13290: 
1.243     albertel 13291: 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 13292: 
                   13293: =item *
                   13294: 
1.243     albertel 13295: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 13296: 
                   13297: =item *
                   13298: 
1.243     albertel 13299: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   13300: forcing spreadsheet to reevaluate the resource scores next time.
                   13301: 
1.1172.2.13  raeburn  13302: =item *
                   13303: 
                   13304: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   13305: when viewing in course context.
                   13306: 
                   13307:  input: six args -- filename (decluttered), course number, course domain,
                   13308:                     url, symb (if registered) and group (if this is a
                   13309:                     group item -- e.g., bulletin board, group page etc.).
                   13310: 
                   13311:  output: array of five scalars --
                   13312:          $cfile -- url for file editing if editable on current server
                   13313:          $home -- homeserver of resource (i.e., for author if published,
                   13314:                                           or course if uploaded.).
                   13315:          $switchserver --  1 if server switch will be needed.
                   13316:          $forceedit -- 1 if icon/link should be to go to edit mode
                   13317:          $forceview -- 1 if icon/link should be to go to view mode
                   13318: 
                   13319: =item *
                   13320: 
                   13321: is_course_upload($file,$cnum,$cdom)
                   13322: 
                   13323: Used in course context to determine if current file was uploaded to
                   13324: the course (i.e., would be found in /userfiles/docs on the course's
                   13325: homeserver.
                   13326: 
                   13327:   input: 3 args -- filename (decluttered), course number and course domain.
                   13328:   output: boolean -- 1 if file was uploaded.
                   13329: 
1.243     albertel 13330: =back
                   13331: 
                   13332: =head2 Storing/Retreiving Data
                   13333: 
                   13334: =over 4
1.191     harris41 13335: 
                   13336: =item *
                   13337: 
1.243     albertel 13338: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   13339: for this url; hashref needs to be given and should be a \%hashname; the
                   13340: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 13341: be derived from the env
1.191     harris41 13342: 
                   13343: =item *
                   13344: 
1.243     albertel 13345: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   13346: uses critical subroutine
1.191     harris41 13347: 
                   13348: =item *
                   13349: 
1.243     albertel 13350: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   13351: all args are optional
1.191     harris41 13352: 
                   13353: =item *
                   13354: 
1.717     albertel 13355: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   13356: dumps the complete (or key matching regexp) namespace into a hash
                   13357: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   13358: normally &store()ed into
                   13359: 
                   13360: $range should be either an integer '100' (give me the first 100
                   13361:                                            matching records)
                   13362:               or be  two integers sperated by a - with no spaces
                   13363:                  '30-50' (give me the 30th through the 50th matching
                   13364:                           records)
                   13365: 
                   13366: 
                   13367: =item *
                   13368: 
1.1172.2.59  raeburn  13369: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 13370: replaces a &store() version of data with a replacement set of data
                   13371: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  13372: reference. If $tolog is true, the transaction is logged in the courselog
                   13373: with an action=PUTSTORE.
1.717     albertel 13374: 
                   13375: =item *
                   13376: 
1.243     albertel 13377: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   13378: works very similar to store/cstore, but all data is stored in a
                   13379: temporary location and can be reset using tmpreset, $storehash should
                   13380: be a hash reference, returns nothing on success
1.191     harris41 13381: 
                   13382: =item *
                   13383: 
1.243     albertel 13384: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   13385: similar to restore, but all data is stored in a temporary location and
                   13386: can be reset using tmpreset. Returns a hash of values on success,
                   13387: error string otherwise.
1.191     harris41 13388: 
                   13389: =item *
                   13390: 
1.243     albertel 13391: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   13392: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 13393: 
                   13394: =item *
                   13395: 
1.243     albertel 13396: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13397: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 13398: 
                   13399: =item *
                   13400: 
1.243     albertel 13401: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   13402: namesp ($udom and $uname are optional)
1.191     harris41 13403: 
                   13404: =item *
                   13405: 
1.702     albertel 13406: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 13407: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 13408: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  13409: 
1.702     albertel 13410: $range should be either an integer '100' (give me the first 100
                   13411:                                            matching records)
                   13412:               or be  two integers sperated by a - with no spaces
                   13413:                  '30-50' (give me the 30th through the 50th matching
                   13414:                           records)
1.449     matthew  13415: =item *
                   13416: 
                   13417: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   13418: $store can be a scalar, an array reference, or if the amount to be 
                   13419: incremented is > 1, a hash reference.
                   13420: 
                   13421: ($udom and $uname are optional)
1.191     harris41 13422: 
                   13423: =item *
                   13424: 
1.243     albertel 13425: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   13426: ($udom and $uname are optional)
1.191     harris41 13427: 
                   13428: =item *
                   13429: 
1.243     albertel 13430: cput($namespace,$storehash,$udom,$uname) : critical put
                   13431: ($udom and $uname are optional)
1.191     harris41 13432: 
                   13433: =item *
                   13434: 
1.748     albertel 13435: newput($namespace,$storehash,$udom,$uname) :
                   13436: 
                   13437: Attempts to store the items in the $storehash, but only if they don't
                   13438: currently exist, if this succeeds you can be certain that you have 
                   13439: successfully created a new key value pair in the $namespace db.
                   13440: 
                   13441: 
                   13442: Args:
                   13443:  $namespace: name of database to store values to
                   13444:  $storehash: hashref to store to the db
                   13445:  $udom: (optional) domain of user containing the db
                   13446:  $uname: (optional) name of user caontaining the db
                   13447: 
                   13448: Returns:
                   13449:  'ok' -> succeeded in storing all keys of $storehash
                   13450:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   13451:                         least <key> already existed in the db (other
                   13452:                         requested keys may also already exist)
1.967     bisitz   13453:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 13454:  'con_lost' -> unable to contact request server
                   13455:  'refused' -> action was not allowed by remote machine
                   13456: 
                   13457: 
                   13458: =item *
                   13459: 
1.243     albertel 13460: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13461: reference filled in from namesp (encrypts the return communication)
                   13462: ($udom and $uname are optional)
1.191     harris41 13463: 
                   13464: =item *
                   13465: 
1.243     albertel 13466: log($udom,$name,$home,$message) : write to permanent log for user; use
                   13467: critical subroutine
                   13468: 
1.806     raeburn  13469: =item *
                   13470: 
1.860     raeburn  13471: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   13472: array reference filled in from namespace found in domain level on either
                   13473: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  13474: 
                   13475: =item *
                   13476: 
1.860     raeburn  13477: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   13478: domain level either on specified domain server ($uhome) or primary domain 
                   13479: server ($udom and $uhome are optional)
1.806     raeburn  13480: 
1.943     raeburn  13481: =item * 
                   13482: 
1.1172.2.35  raeburn  13483: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   13484: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   13485: the target domain.
                   13486: 
                   13487: May also include additional key => value pairs for the following groups:
                   13488: 
                   13489: =over
                   13490: 
                   13491: =item
                   13492: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   13493: 
                   13494: =over
                   13495: 
                   13496: =item defaultquota, authorquota
                   13497: 
                   13498: =back
                   13499: 
                   13500: =item
                   13501: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   13502: portfolio for users).
                   13503: 
                   13504: =over
                   13505: 
                   13506: =item
                   13507: aboutme, blog, webdav, portfolio
                   13508: 
                   13509: =back
                   13510: 
                   13511: =item
                   13512: requestcourses: ability to request courses, and how requests are processed.
                   13513: 
                   13514: =over
                   13515: 
                   13516: =item
1.1172.2.37  raeburn  13517: official, unofficial, community, textbook
1.1172.2.35  raeburn  13518: 
                   13519: =back
                   13520: 
                   13521: =item
                   13522: inststatus: types of institutional affiliation, and order in which they are displayed.
                   13523: 
                   13524: =over
                   13525: 
                   13526: =item
1.1172.2.44  raeburn  13527: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  13528: 
                   13529: =back
                   13530: 
                   13531: =item
                   13532: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   13533: for course's uploaded content.
                   13534: 
                   13535: =over
                   13536: 
                   13537: =item
1.1172.2.37  raeburn  13538: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, communityquota, textbookquota
1.1172.2.35  raeburn  13539: 
                   13540: =back
                   13541: 
                   13542: =item
                   13543: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   13544: on your servers.
                   13545: 
                   13546: =over
                   13547: 
                   13548: =item
                   13549: remotesessions, hostedsessions
                   13550: 
                   13551: =back
                   13552: 
                   13553: =back
                   13554: 
                   13555: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   13556: utility to create a configuration.db file on a domain's primary library server
                   13557: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   13558: -- corresponding values are authentication type (internal, krb4, krb5,
                   13559: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   13560: will be available. Values are retrieved from cache (if current), unless the
                   13561: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   13562: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   13563: 
                   13564: Typical usage:
1.943     raeburn  13565: 
1.1172.2.35  raeburn  13566: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  13567: 
1.243     albertel 13568: =back
                   13569: 
                   13570: =head2 Network Status Functions
                   13571: 
                   13572: =over 4
1.191     harris41 13573: 
                   13574: =item *
                   13575: 
1.1137    raeburn  13576: dirlist() : return directory list based on URI (first arg).
                   13577: 
                   13578: Inputs: 1 required, 5 optional.
                   13579: 
                   13580: =over
                   13581: 
                   13582: =item 
                   13583: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   13584: 
                   13585: =item
                   13586: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   13587: 
                   13588: =item
                   13589: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   13590: 
                   13591: =item
                   13592: $getpropath - boolean: 1 if prepend path using &propath(). 
                   13593: 
                   13594: =item
                   13595: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   13596: 
                   13597: =item 
                   13598: $alternateRoot - path to prepend in place of path from $uri.
                   13599: 
                   13600: =back
                   13601: 
                   13602: Returns: Array of up to two items.
                   13603: 
                   13604: =over
                   13605: 
                   13606: a reference to an array of files/subdirectories
                   13607: 
                   13608: =over
                   13609: 
                   13610: Each element in the array of files/subdirectories is a & separated list of
                   13611: item name and the result of running stat on the item.  If dirlist was requested
                   13612: for a file instead of a directory, the item name will be ''. For a directory 
                   13613: listing, if the item is a metadata file, the element will end &N&M 
                   13614: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   13615: default copyright set (1).  
                   13616: 
                   13617: =back
                   13618: 
                   13619: a scalar containing error condition (if encountered).
                   13620: 
                   13621: =over
                   13622: 
                   13623: =item 
                   13624: no_host (no homeserver identified for $username:$domain).
                   13625: 
                   13626: =item 
                   13627: no_such_host (server contacted for listing not identified as valid host).
                   13628: 
                   13629: =item 
                   13630: con_lost (connection to remote server failed).
                   13631: 
                   13632: =item 
                   13633: refused (invalid $username:$domain received on lond side).
                   13634: 
                   13635: =item 
                   13636: no_such_dir (directory at specified path on lond side does not exist). 
                   13637: 
                   13638: =item 
                   13639: empty (directory at specified path on lond side is empty).
                   13640: 
                   13641: =over
                   13642: 
                   13643: This is currently not encountered because the &ls3, &ls2, 
                   13644: &ls (_handler) routines on the lond side do not filter out
                   13645: . and .. from a directory listing. 
                   13646: 
                   13647: =back
                   13648: 
                   13649: =back
                   13650: 
                   13651: =back
1.191     harris41 13652: 
                   13653: =item *
                   13654: 
1.243     albertel 13655: spareserver() : find server with least workload from spare.tab
                   13656: 
1.986     foxr     13657: 
                   13658: =item *
                   13659: 
                   13660: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   13661: if there is no corresponding loncapa host.
                   13662: 
1.243     albertel 13663: =back
                   13664: 
1.986     foxr     13665: 
1.243     albertel 13666: =head2 Apache Request
                   13667: 
                   13668: =over 4
1.191     harris41 13669: 
                   13670: =item *
                   13671: 
1.243     albertel 13672: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   13673: localhost, posts hash
                   13674: 
                   13675: =back
                   13676: 
                   13677: =head2 Data to String to Data
                   13678: 
                   13679: =over 4
1.191     harris41 13680: 
                   13681: =item *
                   13682: 
1.243     albertel 13683: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   13684: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 13685: 
                   13686: =item *
                   13687: 
1.243     albertel 13688: hashref2str($hashref) : convert a hashref into a string complete with
                   13689: escaping and '=' and '&' separators, supports elements that are
                   13690: arrayrefs and hashrefs
1.191     harris41 13691: 
                   13692: =item *
                   13693: 
1.243     albertel 13694: arrayref2str($arrayref) : convert an arrayref into a string complete
                   13695: with escaping and '&' separators, supports elements that are arrayrefs
                   13696: and hashrefs
1.191     harris41 13697: 
                   13698: =item *
                   13699: 
1.243     albertel 13700: str2hash($string) : convert string to hash using unescaping and
                   13701: splitting on '=' and '&', supports elements that are arrayrefs and
                   13702: hashrefs
1.191     harris41 13703: 
                   13704: =item *
                   13705: 
1.243     albertel 13706: str2array($string) : convert string to hash using unescaping and
                   13707: splitting on '&', supports elements that are arrayrefs and hashrefs
                   13708: 
                   13709: =back
                   13710: 
                   13711: =head2 Logging Routines
                   13712: 
                   13713: 
                   13714: These routines allow one to make log messages in the lonnet.log and
                   13715: lonnet.perm logfiles.
1.191     harris41 13716: 
1.1119    foxr     13717: =over 4
                   13718: 
1.191     harris41 13719: =item *
                   13720: 
1.243     albertel 13721: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 13722: 
                   13723: =item *
                   13724: 
1.243     albertel 13725: logthis() : append message to the normal lonnet.log file, it gets
                   13726: preiodically rolled over and deleted.
1.191     harris41 13727: 
                   13728: =item *
                   13729: 
1.243     albertel 13730: logperm() : append a permanent message to lonnet.perm.log, this log
                   13731: file never gets deleted by any automated portion of the system, only
                   13732: messages of critical importance should go in here.
                   13733: 
1.1119    foxr     13734: 
1.243     albertel 13735: =back
                   13736: 
                   13737: =head2 General File Helper Routines
                   13738: 
                   13739: =over 4
1.191     harris41 13740: 
                   13741: =item *
                   13742: 
1.481     raeburn  13743: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   13744: (a) files in /uploaded
                   13745:   (i) If a local copy of the file exists - 
                   13746:       compares modification date of local copy with last-modified date for 
                   13747:       definitive version stored on home server for course. If local copy is 
                   13748:       stale, requests a new version from the home server and stores it. 
                   13749:       If the original has been removed from the home server, then local copy 
                   13750:       is unlinked.
                   13751:   (ii) If local copy does not exist -
                   13752:       requests the file from the home server and stores it. 
                   13753:   
                   13754:   If $caller is 'uploadrep':  
                   13755:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   13756:     for request for files originally uploaded via DOCS. 
                   13757:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   13758:   
                   13759:   Otherwise:
                   13760:      This indicates a call from the content generation phase of the request.
                   13761:      -  returns the entire contents of the file or -1.
                   13762:      
                   13763: (b) files in /res
                   13764:    - returns the entire contents of a file or -1; 
                   13765:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 13766: 
1.712     albertel 13767: 
                   13768: =item *
                   13769: 
                   13770: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   13771:                   reference
                   13772: 
                   13773: returns either a stat() list of data about the file or an empty list
                   13774: if the file doesn't exist or couldn't find out about it (connection
                   13775: problems or user unknown)
                   13776: 
1.191     harris41 13777: =item *
                   13778: 
1.243     albertel 13779: filelocation($dir,$file) : returns file system location of a file
                   13780: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   13781: directory that relative $file lookups are to looked in ($dir of /a/dir
                   13782: and a file of ../bob will become /a/bob)
1.191     harris41 13783: 
                   13784: =item *
                   13785: 
                   13786: hreflocation($dir,$file) : returns file system location or a URL; same as
                   13787: filelocation except for hrefs
                   13788: 
                   13789: =item *
                   13790: 
1.1172.2.49  raeburn  13791: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   13792: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 13793: 
1.243     albertel 13794: =back
                   13795: 
1.608     albertel 13796: =head2 Usererfile file routines (/uploaded*)
                   13797: 
                   13798: =over 4
                   13799: 
                   13800: =item *
                   13801: 
                   13802: userfileupload(): main rotine for putting a file in a user or course's
                   13803:                   filespace, arguments are,
                   13804: 
1.620     albertel 13805:  formname - required - this is the name of the element in $env where the
1.608     albertel 13806:            filename, and the contents of the file to create/modifed exist
1.620     albertel 13807:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   13808:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  13809:  context - if coursedoc, store the file in the course of the active role
                   13810:              of the current user; 
                   13811:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   13812:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 13813:  subdir - required - subdirectory to put the file in under ../userfiles/
                   13814:          if undefined, it will be placed in "unknown"
                   13815: 
                   13816:  (This routine calls clean_filename() to remove any dangerous
                   13817:  characters from the filename, and then calls finuserfileupload() to
                   13818:  complete the transaction)
                   13819: 
                   13820:  returns either the url of the uploaded file (/uploaded/....) if successful
                   13821:  and /adm/notfound.html if unsuccessful
                   13822: 
                   13823: =item *
                   13824: 
                   13825: clean_filename(): routine for cleaing a filename up for storage in
                   13826:                  userfile space, argument is:
                   13827: 
                   13828:  filename - proposed filename
                   13829: 
                   13830: returns: the new clean filename
                   13831: 
                   13832: =item *
                   13833: 
1.1090    raeburn  13834: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 13835: userspace, probably shouldn't be called directly
                   13836: 
                   13837:   docuname: username or courseid of destination for the file
                   13838:   docudom: domain of user/course of destination for the file
                   13839:   formname: same as for userfileupload()
1.1090    raeburn  13840:   fname: filename (including subdirectories) for the file
                   13841:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   13842:   allfiles: reference to hash used to store objects found by parser
                   13843:   codebase: reference to hash used for codebases of java objects found by parser
                   13844:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   13845:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   13846:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   13847:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   13848:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   13849:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  13850:   mimetype: reference to scalar to accommodate mime type determined
                   13851:             from File::MMagic if $parser = parse.
1.608     albertel 13852: 
                   13853:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  13854:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   13855:  was 'overwrite').
                   13856:  
1.608     albertel 13857: 
                   13858: =item *
                   13859: 
                   13860: renameuserfile(): renames an existing userfile to a new name
                   13861: 
                   13862:   Args:
                   13863:    docuname: username or courseid of destination for the file
                   13864:    docudom: domain of user/course of destination for the file
                   13865:    old: current file name (including any subdirs under userfiles)
                   13866:    new: desired file name (including any subdirs under userfiles)
                   13867: 
                   13868: =item *
                   13869: 
                   13870: mkdiruserfile(): creates a directory is a userfiles dir
                   13871: 
                   13872:   Args:
                   13873:    docuname: username or courseid of destination for the file
                   13874:    docudom: domain of user/course of destination for the file
                   13875:    dir: dir to create (including any subdirs under userfiles)
                   13876: 
                   13877: =item *
                   13878: 
                   13879: removeuserfile(): removes a file that exists in userfiles
                   13880: 
                   13881:   Args:
                   13882:    docuname: username or courseid of destination for the file
                   13883:    docudom: domain of user/course of destination for the file
                   13884:    fname: filname to delete (including any subdirs under userfiles)
                   13885: 
                   13886: =item *
                   13887: 
                   13888: removeuploadedurl(): convience function for removeuserfile()
                   13889: 
                   13890:   Args:
                   13891:    url:  a full /uploaded/... url to delete
                   13892: 
1.747     albertel 13893: =item * 
                   13894: 
                   13895: get_portfile_permissions():
                   13896:   Args:
                   13897:     domain: domain of user or course contain the portfolio files
                   13898:     user: name of user or num of course contain the portfolio files
                   13899:   Returns:
                   13900:     hashref of a dump of the proper file_permissions.db
                   13901:    
                   13902: 
                   13903: =item * 
                   13904: 
                   13905: get_access_controls():
                   13906: 
                   13907: Args:
                   13908:   current_permissions: the hash ref returned from get_portfile_permissions()
                   13909:   group: (optional) the group you want the files associated with
                   13910:   file: (optional) the file you want access info on
                   13911: 
                   13912: Returns:
1.749     raeburn  13913:     a hash (keys are file names) of hashes containing
                   13914:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   13915:         values are XML containing access control settings (see below) 
1.747     albertel 13916: 
                   13917: Internal notes:
                   13918: 
1.749     raeburn  13919:  access controls are stored in file_permissions.db as key=value pairs.
                   13920:     key -> path to file/file_name\0uniqueID:scope_end_start
                   13921:         where scope -> public,guest,course,group,domains or users.
                   13922:               end -> UNIX time for end of access (0 -> no end date)
                   13923:               start -> UNIX time for start of access
                   13924: 
                   13925:     value -> XML description of access control
                   13926:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   13927:             <start></start>
                   13928:             <end></end>
                   13929: 
                   13930:             <password></password>  for scope type = guest
                   13931: 
                   13932:             <domain></domain>     for scope type = course or group
                   13933:             <number></number>
                   13934:             <roles id="">
                   13935:              <role></role>
                   13936:              <access></access>
                   13937:              <section></section>
                   13938:              <group></group>
                   13939:             </roles>
                   13940: 
                   13941:             <dom></dom>         for scope type = domains
                   13942: 
                   13943:             <users>             for scope type = users
                   13944:              <user>
                   13945:               <uname></uname>
                   13946:               <udom></udom>
                   13947:              </user>
                   13948:             </users>
                   13949:            </scope> 
                   13950:               
                   13951:  Access data is also aggregated for each file in an additional key=value pair:
                   13952:  key -> path to file/file_name\0accesscontrol 
                   13953:  value -> reference to hash
                   13954:           hash contains key = value pairs
                   13955:           where key = uniqueID:scope_end_start
                   13956:                 value = UNIX time record was last updated
                   13957: 
                   13958:           Used to improve speed of look-ups of access controls for each file.  
                   13959:  
                   13960:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   13961: 
1.1172.2.13  raeburn  13962: =item *
                   13963: 
1.749     raeburn  13964: modify_access_controls():
                   13965: 
                   13966: Modifies access controls for a portfolio file
                   13967: Args
                   13968: 1. file name
                   13969: 2. reference to hash of required changes,
                   13970: 3. domain
                   13971: 4. username
                   13972:   where domain,username are the domain of the portfolio owner 
                   13973:   (either a user or a course) 
                   13974: 
                   13975: Returns:
                   13976: 1. result of additions or updates ('ok' or 'error', with error message). 
                   13977: 2. result of deletions ('ok' or 'error', with error message).
                   13978: 3. reference to hash of any new or updated access controls.
                   13979: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   13980:    key = integer (inbound ID)
1.1172.2.13  raeburn  13981:    value = uniqueID
                   13982: 
                   13983: =item *
                   13984: 
                   13985: get_timebased_id():
                   13986: 
                   13987: Attempts to get a unique timestamp-based suffix for use with items added to a
                   13988: course via the Course Editor (e.g., folders, composite pages,
                   13989: group bulletin boards).
                   13990: 
                   13991: Args: (first three required; six others optional)
                   13992: 
                   13993: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   13994:    docssequence, or name of group
                   13995: 
                   13996: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   13997:    e.g., num, boardids
                   13998: 
                   13999: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   14000:    file will be named nohist_namespace.db
                   14001: 
                   14002: 4. cdom: domain of course; default is current course domain from %env
                   14003: 
                   14004: 5. cnum: course number; default is current course number from %env
                   14005: 
                   14006: 6. idtype: set to concat if an additional digit is to be appended to the
                   14007:    unix timestamp to form the suffix, if the plain timestamp is already
                   14008:    in use.  Default is to not do this, but simply increment the unix
                   14009:    timestamp by 1 until a unique key is obtained.
                   14010: 
                   14011: 7. who: holder of locking key; defaults to user:domain for user.
                   14012: 
                   14013: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   14014:    retrying); default is 3.
                   14015: 
                   14016: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   14017: 
                   14018: Returns:
                   14019: 
                   14020: 1. suffix obtained (numeric)
                   14021: 
                   14022: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   14023: 
                   14024: 3. error: contains (localized) error message if an error occurred.
                   14025: 
1.747     albertel 14026: 
1.608     albertel 14027: =back
                   14028: 
1.243     albertel 14029: =head2 HTTP Helper Routines
                   14030: 
                   14031: =over 4
                   14032: 
1.191     harris41 14033: =item *
                   14034: 
                   14035: escape() : unpack non-word characters into CGI-compatible hex codes
                   14036: 
                   14037: =item *
                   14038: 
                   14039: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   14040: 
1.243     albertel 14041: =back
                   14042: 
                   14043: =head1 PRIVATE SUBROUTINES
                   14044: 
                   14045: =head2 Underlying communication routines (Shouldn't call)
                   14046: 
                   14047: =over 4
                   14048: 
                   14049: =item *
                   14050: 
                   14051: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   14052: 
                   14053: =item *
                   14054: 
                   14055: reply() : uses subreply to send a message to remote machine, logs all failures
                   14056: 
                   14057: =item *
                   14058: 
                   14059: critical() : passes a critical message to another server; if cannot
                   14060: get through then place message in connection buffer directory and
                   14061: returns con_delayed, if incapable of saving message, returns
                   14062: con_failed
                   14063: 
                   14064: =item *
                   14065: 
                   14066: reconlonc() : tries to reconnect lonc client processes.
                   14067: 
                   14068: =back
                   14069: 
                   14070: =head2 Resource Access Logging
                   14071: 
                   14072: =over 4
                   14073: 
                   14074: =item *
                   14075: 
                   14076: flushcourselogs() : flush (save) buffer logs and access logs
                   14077: 
                   14078: =item *
                   14079: 
                   14080: courselog($what) : save message for course in hash
                   14081: 
                   14082: =item *
                   14083: 
                   14084: courseacclog($what) : save message for course using &courselog().  Perform
                   14085: special processing for specific resource types (problems, exams, quizzes, etc).
                   14086: 
1.191     harris41 14087: =item *
                   14088: 
                   14089: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   14090: as a PerlChildExitHandler
1.243     albertel 14091: 
                   14092: =back
                   14093: 
                   14094: =head2 Other
                   14095: 
                   14096: =over 4
                   14097: 
                   14098: =item *
                   14099: 
                   14100: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 14101: 
                   14102: =back
                   14103: 
                   14104: =cut
1.877     foxr     14105: 

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