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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.22! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.21 2013/03/18 00:30:46 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.18  raeburn    78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $apache
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 {
                    355:     my ($lonhost,$name,$id) = @_;
1.1130    raeburn   356:     my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
1.1124    raeburn   357:     return $response;
                    358: }
                    359: 
1.1       albertel  360: # -------------------------------------------------- Non-critical communication
                    361: sub subreply {
                    362:     my ($cmd,$server)=@_;
1.838     albertel  363:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      364:     #
                    365:     #  With loncnew process trimming, there's a timing hole between lonc server
                    366:     #  process exit and the master server picking up the listen on the AF_UNIX
                    367:     #  socket.  In that time interval, a lock file will exist:
                    368: 
                    369:     my $lockfile=$peerfile.".lock";
                    370:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    371: 	sleep(1);
                    372:     }
                    373:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      374:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      375:     #
1.550     foxr      376:     #   We'll give the connection a few tries before abandoning it.  If
                    377:     #   connection is not possible, we'll con_lost back to the client.
                    378:     #   
                    379:     my $client;
                    380:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    381: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    382: 				      Type    => SOCK_STREAM,
                    383: 				      Timeout => 10);
1.869     albertel  384: 	if ($client) {
1.550     foxr      385: 	    last;		# Connected!
1.850     albertel  386: 	} else {
1.853     albertel  387: 	    &create_connection(&hostname($server),$server);
1.550     foxr      388: 	}
1.850     albertel  389:         sleep(1);		# Try again later if failed connection.
1.550     foxr      390:     }
                    391:     my $answer;
                    392:     if ($client) {
1.704     albertel  393: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      394: 	$answer=<$client>;
                    395: 	if (!$answer) { $answer="con_lost"; }
                    396: 	chomp($answer);
                    397:     } else {
                    398: 	$answer = 'con_lost';	# Failed connection.
                    399:     }
1.1       albertel  400:     return $answer;
                    401: }
                    402: 
                    403: sub reply {
                    404:     my ($cmd,$server)=@_;
1.838     albertel  405:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  406:     my $answer=subreply($cmd,$server);
1.65      www       407:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  408:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       409:                 " $cmd to $server returned $answer</font>");
                    410:     }
1.1       albertel  411:     return $answer;
                    412: }
                    413: 
                    414: # ----------------------------------------------------------- Send USR1 to lonc
                    415: 
                    416: sub reconlonc {
1.891     albertel  417:     my ($lonid) = @_;
                    418:     my $hostname = &hostname($lonid);
                    419:     if ($lonid) {
                    420: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    421: 	if ($hostname && -e $peerfile) {
                    422: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    423: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    424: 					     Type    => SOCK_STREAM,
                    425: 					     Timeout => 10);
                    426: 	    if ($client) {
                    427: 		print $client ("reset_retries\n");
                    428: 		my $answer=<$client>;
                    429: 		#reset just this one.
                    430: 	    }
                    431: 	}
                    432: 	return;
                    433:     }
                    434: 
1.836     www       435:     &logthis("Trying to reconnect lonc");
1.1       albertel  436:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  437:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  438: 	my $loncpid=<$fh>;
                    439:         chomp($loncpid);
                    440:         if (kill 0 => $loncpid) {
                    441: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    442:             kill USR1 => $loncpid;
                    443:             sleep 1;
1.836     www       444:          } else {
1.12      www       445: 	    &logthis(
1.672     albertel  446:                "<font color=\"blue\">WARNING:".
1.12      www       447:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  448:         }
                    449:     } else {
1.836     www       450: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  451:     }
                    452: }
                    453: 
                    454: # ------------------------------------------------------ Critical communication
1.12      www       455: 
1.1       albertel  456: sub critical {
                    457:     my ($cmd,$server)=@_;
1.838     albertel  458:     unless (&hostname($server)) {
1.672     albertel  459:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       460:                " Critical message to unknown server ($server)</font>");
                    461:         return 'no_such_host';
                    462:     }
1.1       albertel  463:     my $answer=reply($cmd,$server);
                    464:     if ($answer eq 'con_lost') {
                    465: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  466: 	my $answer=reply($cmd,$server);
1.1       albertel  467:         if ($answer eq 'con_lost') {
                    468:             my $now=time;
                    469:             my $middlename=$cmd;
1.5       www       470:             $middlename=substr($middlename,0,16);
1.1       albertel  471:             $middlename=~s/\W//g;
                    472:             my $dfilename=
1.305     www       473:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    474:             $dumpcount++;
1.1       albertel  475:             {
1.448     albertel  476: 		my $dfh;
                    477: 		if (open($dfh,">$dfilename")) {
                    478: 		    print $dfh "$cmd\n"; 
                    479: 		    close($dfh);
                    480: 		}
1.1       albertel  481:             }
                    482:             sleep 2;
                    483:             my $wcmd='';
                    484:             {
1.448     albertel  485: 		my $dfh;
                    486: 		if (open($dfh,"<$dfilename")) {
                    487: 		    $wcmd=<$dfh>; 
                    488: 		    close($dfh);
                    489: 		}
1.1       albertel  490:             }
                    491:             chomp($wcmd);
1.7       www       492:             if ($wcmd eq $cmd) {
1.672     albertel  493: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       494:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  495:                 &logperm("D:$server:$cmd");
                    496: 	        return 'con_delayed';
                    497:             } else {
1.672     albertel  498:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       499:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  500:                 &logperm("F:$server:$cmd");
                    501:                 return 'con_failed';
                    502:             }
                    503:         }
                    504:     }
                    505:     return $answer;
1.405     albertel  506: }
                    507: 
1.755     albertel  508: # ------------------------------------------- check if return value is an error
                    509: 
                    510: sub error {
                    511:     my ($result) = @_;
1.756     albertel  512:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  513: 	if ($2 == 2) { return undef; }
                    514: 	return $1;
                    515:     }
                    516:     return undef;
                    517: }
                    518: 
1.783     albertel  519: sub convert_and_load_session_env {
                    520:     my ($lonidsdir,$handle)=@_;
                    521:     my @profile;
                    522:     {
1.917     albertel  523: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    524: 	if (!$opened) {
1.915     albertel  525: 	    return 0;
                    526: 	}
1.783     albertel  527: 	flock($idf,LOCK_SH);
                    528: 	@profile=<$idf>;
                    529: 	close($idf);
                    530:     }
                    531:     my %temp_env;
                    532:     foreach my $line (@profile) {
1.786     albertel  533: 	if ($line !~ m/=/) {
                    534: 	    return 0;
                    535: 	}
1.783     albertel  536: 	chomp($line);
                    537: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    538: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    539:     }
                    540:     unlink("$lonidsdir/$handle.id");
                    541:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    542: 	    0640)) {
                    543: 	%disk_env = %temp_env;
                    544: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    545: 	untie(%disk_env);
                    546:     }
1.786     albertel  547:     return 1;
1.783     albertel  548: }
                    549: 
1.374     www       550: # ------------------------------------------- Transfer profile into environment
1.780     albertel  551: my $env_loaded;
                    552: sub transfer_profile_to_env {
1.788     albertel  553:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    554:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       555: 
1.720     albertel  556:     if (!defined($lonidsdir)) {
                    557: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    558:     }
                    559:     if (!defined($handle)) {
                    560:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    561:     }
                    562: 
1.786     albertel  563:     my $convert;
                    564:     {
1.917     albertel  565:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    566: 	if (!$opened) {
1.915     albertel  567: 	    return;
                    568: 	}
1.786     albertel  569: 	flock($idf,LOCK_SH);
                    570: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    571: 		&GDBM_READER(),0640)) {
                    572: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    573: 	    untie(%disk_env);
                    574: 	} else {
                    575: 	    $convert = 1;
                    576: 	}
                    577:     }
                    578:     if ($convert) {
                    579: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    580: 	    &logthis("Failed to load session, or convert session.");
                    581: 	}
1.374     www       582:     }
1.783     albertel  583: 
1.786     albertel  584:     my %remove;
1.783     albertel  585:     while ( my $envname = each(%env) ) {
1.433     matthew   586:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    587:             if ($time < time-300) {
1.783     albertel  588:                 $remove{$key}++;
1.433     matthew   589:             }
                    590:         }
                    591:     }
1.783     albertel  592: 
1.619     albertel  593:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  594:     $env_loaded=1;
1.783     albertel  595:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   596:         &delenv($expired_key);
1.374     www       597:     }
1.1       albertel  598: }
                    599: 
1.916     albertel  600: # ---------------------------------------------------- Check for valid session 
                    601: sub check_for_valid_session {
1.1155    raeburn   602:     my ($r,$name) = @_;
1.916     albertel  603:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155    raeburn   604:     if ($name eq '') {
                    605:         $name = 'lonID';
                    606:     }
                    607:     my $lonid=$cookies{$name};
1.916     albertel  608:     return undef if (!$lonid);
                    609: 
                    610:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155    raeburn   611:     my $lonidsdir;
                    612:     if ($name eq 'lonDAV') {
                    613:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    614:     } else {
                    615:         $lonidsdir=$r->dir_config('lonIDsDir');
                    616:     }
1.916     albertel  617:     return undef if (!-e "$lonidsdir/$handle.id");
                    618: 
1.917     albertel  619:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    620:     return undef if (!$opened);
1.916     albertel  621: 
                    622:     flock($idf,LOCK_SH);
                    623:     my %disk_env;
                    624:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    625: 	    &GDBM_READER(),0640)) {
                    626: 	return undef;	
                    627:     }
                    628: 
                    629:     if (!defined($disk_env{'user.name'})
                    630: 	|| !defined($disk_env{'user.domain'})) {
                    631: 	return undef;
                    632:     }
1.1172.2.18  raeburn   633: 
                    634:     if (($r->user() eq '') && ($apache >= 2.4)) {
                    635:         if ($disk_env{'user.domain'} eq $r->dir_config('lonDefDomain')) {
                    636:             $r->user($disk_env{'user.name'});
                    637:         } else {
                    638:             $r->user($disk_env{'user.name'}.':'.$disk_env{'user.domain'});
                    639:         }
                    640:     }
                    641: 
1.916     albertel  642:     return $handle;
                    643: }
                    644: 
1.830     albertel  645: sub timed_flock {
                    646:     my ($file,$lock_type) = @_;
                    647:     my $failed=0;
                    648:     eval {
                    649: 	local $SIG{__DIE__}='DEFAULT';
                    650: 	local $SIG{ALRM}=sub {
                    651: 	    $failed=1;
                    652: 	    die("failed lock");
                    653: 	};
                    654: 	alarm(13);
                    655: 	flock($file,$lock_type);
                    656: 	alarm(0);
                    657:     };
                    658:     if ($failed) {
                    659: 	return undef;
                    660:     } else {
                    661: 	return 1;
                    662:     }
                    663: }
                    664: 
1.5       www       665: # ---------------------------------------------------------- Append Environment
                    666: 
                    667: sub appenv {
1.949     raeburn   668:     my ($newenv,$roles) = @_;
                    669:     if (ref($newenv) eq 'HASH') {
                    670:         foreach my $key (keys(%{$newenv})) {
                    671:             my $refused = 0;
                    672: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    673:                 $refused = 1;
                    674:                 if (ref($roles) eq 'ARRAY') {
                    675:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    676:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    677:                         $refused = 0;
                    678:                     }
                    679:                 }
                    680:             }
                    681:             if ($refused) {
                    682:                 &logthis("<font color=\"blue\">WARNING: ".
                    683:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    684:                          .'</font>');
                    685: 	        delete($newenv->{$key});
                    686:             } else {
                    687:                 $env{$key}=$newenv->{$key};
                    688:             }
                    689:         }
                    690:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    691:         if ($opened
                    692: 	    && &timed_flock($env_file,LOCK_EX)
                    693: 	    &&
                    694: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    695: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    696: 	    while (my ($key,$value) = each(%{$newenv})) {
                    697: 	        $disk_env{$key} = $value;
                    698: 	    }
                    699: 	    untie(%disk_env);
1.35      www       700:         }
1.191     harris41  701:     }
1.56      www       702:     return 'ok';
                    703: }
                    704: # ----------------------------------------------------- Delete from Environment
                    705: 
                    706: sub delenv {
1.1104    raeburn   707:     my ($delthis,$regexp,$roles) = @_;
                    708:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    709:         my $refused = 1;
                    710:         if (ref($roles) eq 'ARRAY') {
                    711:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    712:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    713:                 $refused = 0;
                    714:             }
                    715:         }
                    716:         if ($refused) {
                    717:             &logthis("<font color=\"blue\">WARNING: ".
                    718:                      "Attempt to delete from environment ".$delthis);
                    719:             return 'error';
                    720:         }
1.56      www       721:     }
1.917     albertel  722:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    723:     if ($opened
1.915     albertel  724: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  725: 	&&
                    726: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    727: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  728: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   729: 	    if ($regexp) {
                    730:                 if ($key=~/^$delthis/) {
                    731:                     delete($env{$key});
                    732:                     delete($disk_env{$key});
                    733:                 } 
                    734:             } else {
                    735:                 if ($key=~/^\Q$delthis\E/) {
                    736: 		    delete($env{$key});
                    737: 		    delete($disk_env{$key});
                    738: 	        }
                    739:             }
1.448     albertel  740: 	}
1.783     albertel  741: 	untie(%disk_env);
1.5       www       742:     }
                    743:     return 'ok';
1.369     albertel  744: }
                    745: 
1.790     albertel  746: sub get_env_multiple {
                    747:     my ($name) = @_;
                    748:     my @values;
                    749:     if (defined($env{$name})) {
                    750:         # exists is it an array
                    751:         if (ref($env{$name})) {
                    752:             @values=@{ $env{$name} };
                    753:         } else {
                    754:             $values[0]=$env{$name};
                    755:         }
                    756:     }
                    757:     return(@values);
                    758: }
                    759: 
1.958     www       760: # ------------------------------------------------------------------- Locking
                    761: 
                    762: sub set_lock {
                    763:     my ($text)=@_;
                    764:     $locknum++;
                    765:     my $id=$$.'-'.$locknum;
                    766:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    767:              'session.lock.'.$id => $text});
                    768:     return $id;
                    769: }
                    770: 
                    771: sub get_locks {
                    772:     my $num=0;
                    773:     my %texts=();
                    774:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    775:        if ($lock=~/\w/) {
                    776:           $num++;
                    777:           $texts{$lock}=$env{'session.lock.'.$lock};
                    778:        }
                    779:    }
                    780:    return ($num,%texts);
                    781: }
                    782: 
                    783: sub remove_lock {
                    784:     my ($id)=@_;
                    785:     my $newlocks='';
                    786:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    787:        if (($lock=~/\w/) && ($lock ne $id)) {
                    788:           $newlocks.=','.$lock;
                    789:        }
                    790:     }
                    791:     &appenv({'session.locks' => $newlocks});
                    792:     &delenv('session.lock.'.$id);
                    793: }
                    794: 
                    795: sub remove_all_locks {
                    796:     my $activelocks=$env{'session.locks'};
                    797:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    798:        if ($lock=~/\w/) {
                    799:           &remove_lock($lock);
                    800:        }
                    801:     }
                    802: }
                    803: 
                    804: 
1.369     albertel  805: # ------------------------------------------ Find out current server userload
                    806: sub userload {
                    807:     my $numusers=0;
                    808:     {
                    809: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    810: 	my $filename;
                    811: 	my $curtime=time;
                    812: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  813: 	    next if ($filename eq '.' || $filename eq '..');
                    814: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  815: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  816: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  817: 	}
                    818: 	closedir(LONIDS);
                    819:     }
                    820:     my $userloadpercent=0;
                    821:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    822:     if ($maxuserload) {
1.371     albertel  823: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  824:     }
1.372     albertel  825:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  826:     return $userloadpercent;
1.283     www       827: }
                    828: 
1.1       albertel  829: # ------------------------------ Find server with least workload from spare.tab
1.11      www       830: 
1.1       albertel  831: sub spareserver {
1.1083    raeburn   832:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  833:     my $spare_server;
1.370     albertel  834:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  835:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    836:                                                      :  $userloadpercent;
1.1083    raeburn   837:     my ($uint_dom,$remotesessions);
                    838:     if (($udom ne '') && (&domain($udom) ne '')) {
                    839:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    840:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    841:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    842:         $remotesessions = $udomdefaults{'remotesessions'};
                    843:     }
1.1123    raeburn   844:     my $spareshash = &this_host_spares($udom);
                    845:     if (ref($spareshash) eq 'HASH') {
                    846:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    847:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    848:                 if ($uint_dom) {
                    849:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    850:                                                  $try_server));
                    851:                 }
                    852: 	        ($spare_server, $lowest_load) =
                    853: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    854:             }
1.1083    raeburn   855:         }
1.784     albertel  856: 
1.1123    raeburn   857:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    858: 
                    859:         if (!$found_server) {
                    860:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    861: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
                    862:                     if ($uint_dom) {
                    863:                         next unless (&spare_can_host($udom,$uint_dom,
                    864:                                                      $remotesessions,$try_server));
                    865:                     }
                    866: 	            ($spare_server, $lowest_load) =
                    867: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    868:                 }
                    869: 	    }
                    870:         }
1.784     albertel  871:     }
                    872: 
                    873:     if (!$want_server_name) {
1.968     raeburn   874:         my $protocol = 'http';
                    875:         if ($protocol{$spare_server} eq 'https') {
                    876:             $protocol = $protocol{$spare_server};
                    877:         }
1.1001    raeburn   878:         if (defined($spare_server)) {
                    879:             my $hostname = &hostname($spare_server);
1.1083    raeburn   880:             if (defined($hostname)) {
1.1001    raeburn   881: 	        $spare_server = $protocol.'://'.$hostname;
                    882:             }
                    883:         }
1.784     albertel  884:     }
                    885:     return $spare_server;
                    886: }
                    887: 
                    888: sub compare_server_load {
                    889:     my ($try_server, $spare_server, $lowest_load) = @_;
                    890: 
                    891:     my $loadans     = &reply('load',    $try_server);
                    892:     my $userloadans = &reply('userload',$try_server);
                    893: 
                    894:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   895: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  896:     }
                    897: 
                    898:     my $load;
                    899:     if ($loadans =~ /\d/) {
                    900: 	if ($userloadans =~ /\d/) {
                    901: 	    #both are numbers, pick the bigger one
                    902: 	    $load = ($loadans > $userloadans) ? $loadans 
                    903: 		                              : $userloadans;
1.411     albertel  904: 	} else {
1.784     albertel  905: 	    $load = $loadans;
1.411     albertel  906: 	}
1.784     albertel  907:     } else {
                    908: 	$load = $userloadans;
                    909:     }
                    910: 
                    911:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    912: 	$spare_server = $try_server;
                    913: 	$lowest_load  = $load;
1.370     albertel  914:     }
1.784     albertel  915:     return ($spare_server,$lowest_load);
1.202     matthew   916: }
1.914     albertel  917: 
                    918: # --------------------------- ask offload servers if user already has a session
                    919: sub find_existing_session {
                    920:     my ($udom,$uname) = @_;
1.1123    raeburn   921:     my $spareshash = &this_host_spares($udom);
                    922:     if (ref($spareshash) eq 'HASH') {
                    923:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    924:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    925:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    926:             }
                    927:         }
                    928:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    929:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    930:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    931:             }
                    932:         }
1.914     albertel  933:     }
                    934:     return;
                    935: }
                    936: 
                    937: # -------------------------------- ask if server already has a session for user
                    938: sub has_user_session {
                    939:     my ($lonid,$udom,$uname) = @_;
                    940:     my $result = &reply(join(':','userhassession',
                    941: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    942:     return 1 if ($result eq 'ok');
                    943: 
                    944:     return 0;
                    945: }
                    946: 
1.1076    raeburn   947: # --------- determine least loaded server in a user's domain which allows login
                    948: 
                    949: sub choose_server {
1.1115    raeburn   950:     my ($udom,$checkloginvia) = @_;
1.1076    raeburn   951:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   952:     my %servers = &get_servers($udom);
1.1076    raeburn   953:     my $lowest_load = 30000;
1.1151    raeburn   954:     my ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   955:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   956:         my $loginvia;
                    957:         if ($checkloginvia) {
                    958:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   959:             if ($loginvia) {
                    960:                 my ($server,$path) = split(/:/,$loginvia);
                    961:                 ($login_host, $lowest_load) =
                    962:                     &compare_server_load($server, $login_host, $lowest_load);
                    963:                 if ($login_host eq $server) {
                    964:                     $portal_path = $path;
1.1151    raeburn   965:                     $isredirect = 1;
1.1116    raeburn   966:                 }
                    967:             } else {
                    968:                 ($login_host, $lowest_load) =
                    969:                     &compare_server_load($lonhost, $login_host, $lowest_load);
                    970:                 if ($login_host eq $lonhost) {
                    971:                     $portal_path = '';
1.1151    raeburn   972:                     $isredirect = ''; 
1.1116    raeburn   973:                 }
                    974:             }
                    975:         } else {
1.1076    raeburn   976:             ($login_host, $lowest_load) =
1.1116    raeburn   977:                 &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076    raeburn   978:         }
                    979:     }
                    980:     if ($login_host ne '') {
1.1116    raeburn   981:         $hostname = &hostname($login_host);
1.1076    raeburn   982:     }
1.1151    raeburn   983:     return ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   984: }
                    985: 
1.202     matthew   986: # --------------------------------------------- Try to change a user's password
                    987: 
                    988: sub changepass {
1.799     raeburn   989:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   990:     $currentpass = &escape($currentpass);
                    991:     $newpass     = &escape($newpass);
1.1030    raeburn   992:     my $lonhost = $perlvar{'lonHostID'};
                    993:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   994: 		       $server);
                    995:     if (! $answer) {
                    996: 	&logthis("No reply on password change request to $server ".
                    997: 		 "by $uname in domain $udom.");
                    998:     } elsif ($answer =~ "^ok") {
                    999:         &logthis("$uname in $udom successfully changed their password ".
                   1000: 		 "on $server.");
                   1001:     } elsif ($answer =~ "^pwchange_failure") {
                   1002: 	&logthis("$uname in $udom was unable to change their password ".
                   1003: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1004: 		 "or pwchange");
                   1005:     } elsif ($answer =~ "^non_authorized") {
                   1006:         &logthis("$uname in $udom did not get their password correct when ".
                   1007: 		 "attempting to change it on $server.");
                   1008:     } elsif ($answer =~ "^auth_mode_error") {
                   1009:         &logthis("$uname in $udom attempted to change their password despite ".
                   1010: 		 "not being locally or internally authenticated on $server.");
                   1011:     } elsif ($answer =~ "^unknown_user") {
                   1012:         &logthis("$uname in $udom attempted to change their password ".
                   1013: 		 "on $server but were unable to because $server is not ".
                   1014: 		 "their home server.");
                   1015:     } elsif ($answer =~ "^refused") {
                   1016: 	&logthis("$server refused to change $uname in $udom password because ".
                   1017: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1018:     } elsif ($answer =~ "invalid_client") {
                   1019:         &logthis("$server refused to change $uname in $udom password because ".
                   1020:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1021:     }
                   1022:     return $answer;
1.1       albertel 1023: }
                   1024: 
1.169     harris41 1025: # ----------------------- Try to determine user's current authentication scheme
                   1026: 
                   1027: sub queryauthenticate {
                   1028:     my ($uname,$udom)=@_;
1.456     albertel 1029:     my $uhome=&homeserver($uname,$udom);
                   1030:     if (!$uhome) {
                   1031: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1032: 	return 'no_host';
                   1033:     }
                   1034:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1035:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1036: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1037:     }
1.456     albertel 1038:     return $answer;
1.169     harris41 1039: }
                   1040: 
1.1       albertel 1041: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1042: 
1.1       albertel 1043: sub authenticate {
1.1073    raeburn  1044:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1045:     $upass=&escape($upass);
                   1046:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1047:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1048:     my $newhome;
1.836     www      1049:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1050: # Maybe the machine was offline and only re-appeared again recently?
                   1051:         &reconlonc();
                   1052: # One more
1.952     raeburn  1053: 	$uhome=&homeserver($uname,$udom,1);
                   1054:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1055:             if (defined(&domain($udom,'primary'))) {
                   1056:                 $newhome=&domain($udom,'primary');
                   1057:             }
                   1058:             if ($newhome ne '') {
                   1059:                 $uhome = $newhome;
                   1060:             }
                   1061:         }
1.836     www      1062: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1063: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1064: 	    return 'no_host';
                   1065:         }
1.1       albertel 1066:     }
1.1073    raeburn  1067:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1068:     if ($answer eq 'authorized') {
1.952     raeburn  1069:         if ($newhome) {
                   1070:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1071:             return 'no_account_on_host'; 
                   1072:         } else {
                   1073:             &logthis("User $uname at $udom authorized by $uhome");
                   1074:             return $uhome;
                   1075:         }
1.471     albertel 1076:     }
                   1077:     if ($answer eq 'non_authorized') {
                   1078: 	&logthis("User $uname at $udom rejected by $uhome");
                   1079: 	return 'no_host'; 
1.9       www      1080:     }
1.471     albertel 1081:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1082:     return 'no_host';
                   1083: }
                   1084: 
1.1073    raeburn  1085: sub can_host_session {
1.1074    raeburn  1086:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1087:     my $canhost = 1;
1.1074    raeburn  1088:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1089:     if (ref($remotesessions) eq 'HASH') {
                   1090:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1091:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1092:                 $canhost = 0;
                   1093:             } else {
                   1094:                 $canhost = 1;
                   1095:             }
                   1096:         }
                   1097:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1098:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1099:                 $canhost = 1;
                   1100:             } else {
                   1101:                 $canhost = 0;
                   1102:             }
                   1103:         }
                   1104:         if ($canhost) {
                   1105:             if ($remotesessions->{'version'} ne '') {
                   1106:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1107:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1108:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1109:                         my $major = $1;
                   1110:                         my $minor = $2;
                   1111:                         if (($major < $reqmajor ) ||
                   1112:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1113:                             $canhost = 0;
                   1114:                         }
                   1115:                     } else {
                   1116:                         $canhost = 0;
                   1117:                     }
                   1118:                 }
                   1119:             }
                   1120:         }
                   1121:     }
                   1122:     if ($canhost) {
                   1123:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1124:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1125:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1126:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1127:                 if (($uint_dom ne '') && 
                   1128:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1129:                     $canhost = 0;
                   1130:                 } else {
                   1131:                     $canhost = 1;
                   1132:                 }
                   1133:             }
                   1134:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1135:                 if (($uint_dom ne '') && 
                   1136:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1137:                     $canhost = 1;
                   1138:                 } else {
                   1139:                     $canhost = 0;
                   1140:                 }
                   1141:             }
                   1142:         }
                   1143:     }
                   1144:     return $canhost;
                   1145: }
                   1146: 
1.1083    raeburn  1147: sub spare_can_host {
                   1148:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1149:     my $canhost=1;
                   1150:     my @intdoms;
                   1151:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1152:     if (ref($internet_names) eq 'ARRAY') {
                   1153:         @intdoms = @{$internet_names};
                   1154:     }
                   1155:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1156:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1157:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1158:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1159:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1160:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1161:                                      $remotesessions,
                   1162:                                      $defdomdefaults{'hostedsessions'});
                   1163:     }
                   1164:     return $canhost;
                   1165: }
                   1166: 
1.1123    raeburn  1167: sub this_host_spares {
                   1168:     my ($dom) = @_;
1.1126    raeburn  1169:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1170:     my @hosts = &current_machine_ids();
                   1171:     foreach my $lonhost (@hosts) {
                   1172:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1173:             $dom_in_use = $dom;
                   1174:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1175:             last;
                   1176:         }
                   1177:     }
1.1126    raeburn  1178:     if ($dom_in_use ne '') {
                   1179:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1180:     }
                   1181:     if (ref($result) ne 'HASH') {
                   1182:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1183:         $dom_in_use = &host_domain($lonhost_in_use);
                   1184:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1185:         if (ref($result) ne 'HASH') {
                   1186:             $result = \%spareid;
                   1187:         }
                   1188:     }
                   1189:     return $result;
                   1190: }
                   1191: 
                   1192: sub spares_for_offload  {
                   1193:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1194:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1195:     if (defined($cached)) {
                   1196:         return $result;
                   1197:     } else {
1.1126    raeburn  1198:         my $cachetime = 60*60*24;
                   1199:         my %domconfig =
                   1200:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1201:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1202:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1203:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1204:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1205:                 }
                   1206:             }
                   1207:         }
                   1208:     }
1.1126    raeburn  1209:     return;
1.1123    raeburn  1210: }
                   1211: 
1.1129    raeburn  1212: sub get_lonbalancer_config {
                   1213:     my ($servers) = @_;
                   1214:     my ($currbalancer,$currtargets);
                   1215:     if (ref($servers) eq 'HASH') {
                   1216:         foreach my $server (keys(%{$servers})) {
                   1217:             my %what = (
                   1218:                          spareid => 1,
                   1219:                          perlvar => 1,
                   1220:                        );
                   1221:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1222:             if ($result eq 'ok') {
                   1223:                 if (ref($returnhash) eq 'HASH') {
                   1224:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1225:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1226:                             $currbalancer = $server;
                   1227:                             $currtargets = {};
                   1228:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1229:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1230:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1231:                                 }
                   1232:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1233:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1234:                                 }
                   1235:                             }
                   1236:                             last;
                   1237:                         }
                   1238:                     }
                   1239:                 }
                   1240:             }
                   1241:         }
                   1242:     }
                   1243:     return ($currbalancer,$currtargets);
                   1244: }
                   1245: 
                   1246: sub check_loadbalancing {
                   1247:     my ($uname,$udom) = @_;
1.1172.2.12  raeburn  1248:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1249:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1250:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1251:     my @hosts = &current_machine_ids();
1.1129    raeburn  1252:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1253:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1254:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1255:     my $serverhomedom = &host_domain($lonhost);
                   1256: 
                   1257:     my $cachetime = 60*60*24;
                   1258: 
                   1259:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1260:         $dom_in_use = $udom;
                   1261:         $homeintdom = 1;
                   1262:     } else {
                   1263:         $dom_in_use = $serverhomedom;
                   1264:     }
                   1265:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1266:     unless (defined($cached)) {
                   1267:         my %domconfig =
                   1268:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1269:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1270:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1271:         }
                   1272:     }
                   1273:     if (ref($result) eq 'HASH') {
1.1172.2.12  raeburn  1274:         ($is_balancer,$currtargets,$currrules) =
                   1275:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1276:         if ($is_balancer) {
                   1277:             if (ref($currrules) eq 'HASH') {
                   1278:                 if ($homeintdom) {
                   1279:                     if ($uname ne '') {
                   1280:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1281:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1282:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1283:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1284:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1285:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1286:                             }
                   1287:                         }
                   1288:                         if ($rule_in_effect eq '') {
                   1289:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1290:                             if ($userenv{'inststatus'} ne '') {
                   1291:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1292:                                 my ($othertitle,$usertypes,$types) =
                   1293:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1294:                                 if (ref($types) eq 'ARRAY') {
                   1295:                                     foreach my $type (@{$types}) {
                   1296:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1297:                                             if (exists($currrules->{$type})) {
                   1298:                                                 $rule_in_effect = $currrules->{$type};
                   1299:                                             }
                   1300:                                         }
                   1301:                                     }
                   1302:                                 }
                   1303:                             } else {
                   1304:                                 if (exists($currrules->{'default'})) {
                   1305:                                     $rule_in_effect = $currrules->{'default'};
                   1306:                                 }
                   1307:                             }
                   1308:                         }
                   1309:                     } else {
                   1310:                         if (exists($currrules->{'default'})) {
                   1311:                             $rule_in_effect = $currrules->{'default'};
                   1312:                         }
                   1313:                     }
                   1314:                 } else {
                   1315:                     if ($currrules->{'_LC_external'} ne '') {
                   1316:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1317:                     }
                   1318:                 }
                   1319:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1320:                                                        $uname,$udom);
                   1321:             }
                   1322:         }
                   1323:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
                   1324:         my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
                   1325:         unless (defined($cached)) {
                   1326:             my %domconfig =
                   1327:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1328:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1329:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1330:             }
                   1331:         }
                   1332:         if (ref($result) eq 'HASH') {
1.1172.2.12  raeburn  1333:             ($is_balancer,$currtargets,$currrules) =
                   1334:                 &check_balancer_result($result,@hosts);
                   1335:             if ($is_balancer) {
1.1129    raeburn  1336:                 if (ref($currrules) eq 'HASH') {
                   1337:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1338:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1339:                     }
                   1340:                 }
                   1341:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1342:                                                        $uname,$udom);
                   1343:             }
                   1344:         } else {
                   1345:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1346:                 $is_balancer = 1;
                   1347:                 $offloadto = &this_host_spares($dom_in_use);
                   1348:             }
                   1349:         }
                   1350:     } else {
                   1351:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1352:             $is_balancer = 1;
                   1353:             $offloadto = &this_host_spares($dom_in_use);
                   1354:         }
                   1355:     }
1.1172.2.5  raeburn  1356:     if ($is_balancer) {
                   1357:         my $lowest_load = 30000;
                   1358:         if (ref($offloadto) eq 'HASH') {
                   1359:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1360:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1361:                     ($otherserver,$lowest_load) =
                   1362:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1363:                 }
1.1129    raeburn  1364:             }
1.1172.2.5  raeburn  1365:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1366: 
1.1172.2.5  raeburn  1367:             if (!$found_server) {
                   1368:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1369:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1370:                         ($otherserver,$lowest_load) =
                   1371:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1372:                     }
                   1373:                 }
                   1374:             }
                   1375:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1376:             if (@{$offloadto} == 1) {
                   1377:                 $otherserver = $offloadto->[0];
                   1378:             } elsif (@{$offloadto} > 1) {
                   1379:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1380:                     ($otherserver,$lowest_load) =
                   1381:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1382:                 }
                   1383:             }
                   1384:         }
1.1172.2.5  raeburn  1385:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1386:             $is_balancer = 0;
                   1387:             if ($uname ne '' && $udom ne '') {
                   1388:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1389: 
                   1390:                     &appenv({'user.loadbalexempt'     => $lonhost,
                   1391:                              'user.loadbalcheck.time' => time});
                   1392:                 }
1.1129    raeburn  1393:             }
                   1394:         }
                   1395:     }
                   1396:     return ($is_balancer,$otherserver);
                   1397: }
                   1398: 
1.1172.2.12  raeburn  1399: sub check_balancer_result {
                   1400:     my ($result,@hosts) = @_;
                   1401:     my ($is_balancer,$currtargets,$currrules);
                   1402:     if (ref($result) eq 'HASH') {
                   1403:         if ($result->{'lonhost'} ne '') {
                   1404:             my $currbalancer = $result->{'lonhost'};
                   1405:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1406:                 $is_balancer = 1;
                   1407:                 $currtargets = $result->{'targets'};
                   1408:                 $currrules = $result->{'rules'};
                   1409:             }
                   1410:         } else {
                   1411:             foreach my $key (keys(%{$result})) {
                   1412:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1413:                     (ref($result->{$key}) eq 'HASH')) {
                   1414:                     $is_balancer = 1;
                   1415:                     $currrules = $result->{$key}{'rules'};
                   1416:                     $currtargets = $result->{$key}{'targets'};
                   1417:                     last;
                   1418:                 }
                   1419:             }
                   1420:         }
                   1421:     }
                   1422:     return ($is_balancer,$currtargets,$currrules);
                   1423: }
                   1424: 
1.1129    raeburn  1425: sub get_loadbalancer_targets {
                   1426:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1427:     my $offloadto;
1.1172.2.4  raeburn  1428:     if ($rule_in_effect eq 'none') {
                   1429:         return [$perlvar{'lonHostID'}];
                   1430:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1431:         $offloadto = $currtargets;
                   1432:     } else {
                   1433:         if ($rule_in_effect eq 'homeserver') {
                   1434:             my $homeserver = &homeserver($uname,$udom);
                   1435:             if ($homeserver ne 'no_host') {
                   1436:                 $offloadto = [$homeserver];
                   1437:             }
                   1438:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1439:             my %domconfig =
                   1440:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1441:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1442:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1443:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1444:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1445:                     }
                   1446:                 }
                   1447:             } else {
1.1172.2.7  raeburn  1448:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1449:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1450:                 if (&hostname($remotebalancer) ne '') {
                   1451:                     $offloadto = [$remotebalancer];
                   1452:                 }
                   1453:             }
                   1454:         } elsif (&hostname($rule_in_effect) ne '') {
                   1455:             $offloadto = [$rule_in_effect];
                   1456:         }
                   1457:     }
                   1458:     return $offloadto;
                   1459: }
                   1460: 
1.1127    raeburn  1461: sub internet_dom_servers {
                   1462:     my ($dom) = @_;
                   1463:     my (%uniqservers,%servers);
                   1464:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1465:     my @machinedoms = &machine_domains($primaryserver);
                   1466:     foreach my $mdom (@machinedoms) {
                   1467:         my %currservers = %servers;
                   1468:         my %server = &get_servers($mdom);
                   1469:         %servers = (%currservers,%server);
                   1470:     }
                   1471:     my %by_hostname;
                   1472:     foreach my $id (keys(%servers)) {
                   1473:         push(@{$by_hostname{$servers{$id}}},$id);
                   1474:     }
                   1475:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1476:         if (@{$by_hostname{$hostname}} > 1) {
                   1477:             my $match = 0;
                   1478:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1479:                 if (&host_domain($id) eq $dom) {
                   1480:                     $uniqservers{$id} = $hostname;
                   1481:                     $match = 1;
                   1482:                 }
                   1483:             }
                   1484:             unless ($match) {
                   1485:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1486:             }
                   1487:         } else {
                   1488:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1489:         }
                   1490:     }
                   1491:     return %uniqservers;
                   1492: }
                   1493: 
1.1       albertel 1494: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1495: 
1.599     albertel 1496: my %homecache;
1.1       albertel 1497: sub homeserver {
1.230     stredwic 1498:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1499:     my $index="$uname:$udom";
1.426     albertel 1500: 
1.599     albertel 1501:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1502: 
                   1503:     my %servers = &get_servers($udom,'library');
                   1504:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1505:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1506: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1507: 
                   1508: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1509: 	if ($answer eq 'found') {
                   1510: 	    delete($badServerCache{$tryserver}); 
                   1511: 	    return $homecache{$index}=$tryserver;
                   1512: 	} elsif ($answer eq 'no_host') {
                   1513: 	    $badServerCache{$tryserver}=1;
                   1514: 	}
1.1       albertel 1515:     }    
                   1516:     return 'no_host';
1.70      www      1517: }
                   1518: 
                   1519: # ------------------------------------- Find the usernames behind a list of IDs
                   1520: 
                   1521: sub idget {
                   1522:     my ($udom,@ids)=@_;
                   1523:     my %returnhash=();
                   1524:     
1.841     albertel 1525:     my %servers = &get_servers($udom,'library');
                   1526:     foreach my $tryserver (keys(%servers)) {
                   1527: 	my $idlist=join('&',@ids);
                   1528: 	$idlist=~tr/A-Z/a-z/; 
                   1529: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1530: 	my @answer=();
                   1531: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1532: 	    @answer=split(/\&/,$reply);
                   1533: 	}                    ;
                   1534: 	my $i;
                   1535: 	for ($i=0;$i<=$#ids;$i++) {
                   1536: 	    if ($answer[$i]) {
                   1537: 		$returnhash{$ids[$i]}=$answer[$i];
                   1538: 	    } 
                   1539: 	}
                   1540:     } 
1.70      www      1541:     return %returnhash;
                   1542: }
                   1543: 
                   1544: # ------------------------------------- Find the IDs behind a list of usernames
                   1545: 
                   1546: sub idrget {
                   1547:     my ($udom,@unames)=@_;
                   1548:     my %returnhash=();
1.800     albertel 1549:     foreach my $uname (@unames) {
                   1550:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1551:     }
1.70      www      1552:     return %returnhash;
                   1553: }
                   1554: 
                   1555: # ------------------------------- Store away a list of names and associated IDs
                   1556: 
                   1557: sub idput {
                   1558:     my ($udom,%ids)=@_;
                   1559:     my %servers=();
1.800     albertel 1560:     foreach my $uname (keys(%ids)) {
                   1561: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1562:         my $uhom=&homeserver($uname,$udom);
1.70      www      1563:         if ($uhom ne 'no_host') {
1.800     albertel 1564:             my $id=&escape($ids{$uname});
1.70      www      1565:             $id=~tr/A-Z/a-z/;
1.800     albertel 1566:             my $esc_unam=&escape($uname);
1.70      www      1567: 	    if ($servers{$uhom}) {
1.800     albertel 1568: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1569:             } else {
1.800     albertel 1570:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1571:             }
                   1572:         }
1.191     harris41 1573:     }
1.800     albertel 1574:     foreach my $server (keys(%servers)) {
                   1575:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1576:     }
1.344     www      1577: }
                   1578: 
1.1023    raeburn  1579: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1580: sub dump_dom {
1.1165    droeschl 1581:     my ($namespace, $udom, $regexp) = @_;
                   1582: 
                   1583:     $udom ||= $env{'user.domain'};
                   1584: 
                   1585:     return () unless $udom;
                   1586: 
                   1587:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1588: }
                   1589: 
1.1023    raeburn  1590: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1591: 
                   1592: sub get_dom {
1.860     raeburn  1593:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1594:     my $items='';
                   1595:     foreach my $item (@$storearr) {
                   1596:         $items.=&escape($item).'&';
                   1597:     }
                   1598:     $items=~s/\&$//;
1.860     raeburn  1599:     if (!$udom) {
                   1600:         $udom=$env{'user.domain'};
                   1601:         if (defined(&domain($udom,'primary'))) {
                   1602:             $uhome=&domain($udom,'primary');
                   1603:         } else {
1.874     albertel 1604:             undef($uhome);
1.860     raeburn  1605:         }
                   1606:     } else {
                   1607:         if (!$uhome) {
                   1608:             if (defined(&domain($udom,'primary'))) {
                   1609:                 $uhome=&domain($udom,'primary');
                   1610:             }
                   1611:         }
                   1612:     }
                   1613:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1614:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1615:         my %returnhash;
1.875     albertel 1616:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1617:             return %returnhash;
                   1618:         }
1.806     raeburn  1619:         my @pairs=split(/\&/,$rep);
                   1620:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1621:             return @pairs;
                   1622:         }
                   1623:         my $i=0;
                   1624:         foreach my $item (@$storearr) {
                   1625:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1626:             $i++;
                   1627:         }
                   1628:         return %returnhash;
                   1629:     } else {
1.880     banghart 1630:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1631:     }
                   1632: }
                   1633: 
                   1634: # -------------------------------------------- put items in domain db files 
                   1635: 
                   1636: sub put_dom {
1.860     raeburn  1637:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1638:     if (!$udom) {
                   1639:         $udom=$env{'user.domain'};
                   1640:         if (defined(&domain($udom,'primary'))) {
                   1641:             $uhome=&domain($udom,'primary');
                   1642:         } else {
1.874     albertel 1643:             undef($uhome);
1.860     raeburn  1644:         }
                   1645:     } else {
                   1646:         if (!$uhome) {
                   1647:             if (defined(&domain($udom,'primary'))) {
                   1648:                 $uhome=&domain($udom,'primary');
                   1649:             }
                   1650:         }
                   1651:     } 
                   1652:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1653:         my $items='';
                   1654:         foreach my $item (keys(%$storehash)) {
                   1655:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1656:         }
                   1657:         $items=~s/\&$//;
                   1658:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1659:     } else {
1.860     raeburn  1660:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1661:     }
                   1662: }
                   1663: 
1.1023    raeburn  1664: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1665: sub newput_dom {
1.1023    raeburn  1666:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1667:     my $result;
                   1668:     if (!$udom) {
                   1669:         $udom=$env{'user.domain'};
                   1670:     }
1.1023    raeburn  1671:     if ($udom) {
                   1672:         my $uname = &get_domainconfiguser($udom);
                   1673:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1674:     }
                   1675:     return $result;
                   1676: }
                   1677: 
1.1023    raeburn  1678: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1679: sub del_dom {
1.1023    raeburn  1680:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1681:     if (ref($storearr) eq 'ARRAY') {
                   1682:         if (!$udom) {
                   1683:             $udom=$env{'user.domain'};
                   1684:         }
1.1023    raeburn  1685:         if ($udom) {
                   1686:             my $uname = &get_domainconfiguser($udom); 
                   1687:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1688:         }
                   1689:     }
                   1690: }
                   1691: 
1.1023    raeburn  1692: # ----------------------------------construct domainconfig user for a domain 
                   1693: sub get_domainconfiguser {
                   1694:     my ($udom) = @_;
                   1695:     return $udom.'-domainconfig';
                   1696: }
                   1697: 
1.837     raeburn  1698: sub retrieve_inst_usertypes {
                   1699:     my ($udom) = @_;
                   1700:     my (%returnhash,@order);
1.989     raeburn  1701:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1702:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1703:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1704:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1705:         @order = @{$domdefs{'inststatusorder'}};
                   1706:     } else {
                   1707:         if (defined(&domain($udom,'primary'))) {
                   1708:             my $uhome=&domain($udom,'primary');
                   1709:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1710:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1711:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1712:                 return (\%returnhash,\@order);
                   1713:             }
                   1714:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1715:             my @pairs=split(/\&/,$hashitems);
                   1716:             foreach my $item (@pairs) {
                   1717:                 my ($key,$value)=split(/=/,$item,2);
                   1718:                 $key = &unescape($key);
                   1719:                 next if ($key =~ /^error: 2 /);
                   1720:                 $returnhash{$key}=&thaw_unescape($value);
                   1721:             }
                   1722:             my @esc_order = split(/\&/,$orderitems);
                   1723:             foreach my $item (@esc_order) {
                   1724:                 push(@order,&unescape($item));
                   1725:             }
                   1726:         } else {
                   1727:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1728:         }
                   1729:     }
                   1730:     return (\%returnhash,\@order);
                   1731: }
                   1732: 
1.868     raeburn  1733: sub is_domainimage {
                   1734:     my ($url) = @_;
                   1735:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1736:         if (&domain($1) ne '') {
                   1737:             return '1';
                   1738:         }
                   1739:     }
                   1740:     return;
                   1741: }
                   1742: 
1.899     raeburn  1743: sub inst_directory_query {
                   1744:     my ($srch) = @_;
                   1745:     my $udom = $srch->{'srchdomain'};
                   1746:     my %results;
                   1747:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1748:     my $outcome;
1.899     raeburn  1749:     if ($homeserver ne '') {
1.904     albertel 1750: 	my $queryid=&reply("querysend:instdirsearch:".
                   1751: 			   &escape($srch->{'srchby'}).':'.
                   1752: 			   &escape($srch->{'srchterm'}).':'.
                   1753: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1754: 	my $host=&hostname($homeserver);
                   1755: 	if ($queryid !~/^\Q$host\E\_/) {
                   1756: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1757: 	    return;
                   1758: 	}
                   1759: 	my $response = &get_query_reply($queryid);
                   1760: 	my $maxtries = 5;
                   1761: 	my $tries = 1;
                   1762: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1763: 	    $response = &get_query_reply($queryid);
                   1764: 	    $tries ++;
                   1765: 	}
                   1766: 
                   1767:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1768:             if ($response eq 'unavailable') {
                   1769:                 $outcome = $response;
                   1770:             } else {
                   1771:                 $outcome = 'ok';
                   1772:                 my @matches = split(/\n/,$response);
                   1773:                 foreach my $match (@matches) {
                   1774:                     my ($key,$value) = split(/=/,$match);
                   1775:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1776:                 }
1.899     raeburn  1777:             }
                   1778:         }
                   1779:     }
1.909     raeburn  1780:     return ($outcome,%results);
1.899     raeburn  1781: }
                   1782: 
                   1783: sub usersearch {
                   1784:     my ($srch) = @_;
                   1785:     my $dom = $srch->{'srchdomain'};
                   1786:     my %results;
                   1787:     my %libserv = &all_library();
                   1788:     my $query = 'usersearch';
                   1789:     foreach my $tryserver (keys(%libserv)) {
                   1790:         if (&host_domain($tryserver) eq $dom) {
                   1791:             my $host=&hostname($tryserver);
                   1792:             my $queryid=
1.911     raeburn  1793:                 &reply("querysend:".&escape($query).':'.
                   1794:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1795:                        &escape($srch->{'srchtype'}).':'.
                   1796:                        &escape($srch->{'srchterm'}),$tryserver);
                   1797:             if ($queryid !~/^\Q$host\E\_/) {
                   1798:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1799:                 next;
1.899     raeburn  1800:             }
                   1801:             my $reply = &get_query_reply($queryid);
                   1802:             my $maxtries = 1;
                   1803:             my $tries = 1;
                   1804:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1805:                 $reply = &get_query_reply($queryid);
                   1806:                 $tries ++;
                   1807:             }
                   1808:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1809:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1810:             } else {
1.911     raeburn  1811:                 my @matches;
                   1812:                 if ($reply =~ /\n/) {
                   1813:                     @matches = split(/\n/,$reply);
                   1814:                 } else {
                   1815:                     @matches = split(/\&/,$reply);
                   1816:                 }
1.899     raeburn  1817:                 foreach my $match (@matches) {
                   1818:                     my ($uname,$udom,%userhash);
1.911     raeburn  1819:                     foreach my $entry (split(/:/,$match)) {
                   1820:                         my ($key,$value) =
                   1821:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1822:                         $userhash{$key} = $value;
                   1823:                         if ($key eq 'username') {
                   1824:                             $uname = $value;
                   1825:                         } elsif ($key eq 'domain') {
                   1826:                             $udom = $value;
1.911     raeburn  1827:                         }
1.899     raeburn  1828:                     }
                   1829:                     $results{$uname.':'.$udom} = \%userhash;
                   1830:                 }
                   1831:             }
                   1832:         }
                   1833:     }
                   1834:     return %results;
                   1835: }
                   1836: 
1.912     raeburn  1837: sub get_instuser {
                   1838:     my ($udom,$uname,$id) = @_;
                   1839:     my $homeserver = &domain($udom,'primary');
                   1840:     my ($outcome,%results);
                   1841:     if ($homeserver ne '') {
                   1842:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1843:                            &escape($id).':'.&escape($udom),$homeserver);
                   1844:         my $host=&hostname($homeserver);
                   1845:         if ($queryid !~/^\Q$host\E\_/) {
                   1846:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1847:             return;
                   1848:         }
                   1849:         my $response = &get_query_reply($queryid);
                   1850:         my $maxtries = 5;
                   1851:         my $tries = 1;
                   1852:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1853:             $response = &get_query_reply($queryid);
                   1854:             $tries ++;
                   1855:         }
                   1856:         if (!&error($response) && $response ne 'refused') {
                   1857:             if ($response eq 'unavailable') {
                   1858:                 $outcome = $response;
                   1859:             } else {
                   1860:                 $outcome = 'ok';
                   1861:                 my @matches = split(/\n/,$response);
                   1862:                 foreach my $match (@matches) {
                   1863:                     my ($key,$value) = split(/=/,$match);
                   1864:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1865:                 }
                   1866:             }
                   1867:         }
                   1868:     }
                   1869:     my %userinfo;
                   1870:     if (ref($results{$uname}) eq 'HASH') {
                   1871:         %userinfo = %{$results{$uname}};
                   1872:     } 
                   1873:     return ($outcome,%userinfo);
                   1874: }
                   1875: 
                   1876: sub inst_rulecheck {
1.923     raeburn  1877:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1878:     my %returnhash;
                   1879:     if ($udom ne '') {
                   1880:         if (ref($rules) eq 'ARRAY') {
                   1881:             @{$rules} = map {&escape($_);} (@{$rules});
                   1882:             my $rulestr = join(':',@{$rules});
                   1883:             my $homeserver=&domain($udom,'primary');
                   1884:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1885:                 my $response;
                   1886:                 if ($item eq 'username') {                
                   1887:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1888:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1889:                                               $homeserver));
1.923     raeburn  1890:                 } elsif ($item eq 'id') {
                   1891:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1892:                                               ':'.&escape($id).':'.$rulestr,
                   1893:                                               $homeserver));
1.945     raeburn  1894:                 } elsif ($item eq 'selfcreate') {
                   1895:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1896:                                                &escape($udom).':'.&escape($uname).
                   1897:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1898:                 }
1.912     raeburn  1899:                 if ($response ne 'refused') {
                   1900:                     my @pairs=split(/\&/,$response);
                   1901:                     foreach my $item (@pairs) {
                   1902:                         my ($key,$value)=split(/=/,$item,2);
                   1903:                         $key = &unescape($key);
                   1904:                         next if ($key =~ /^error: 2 /);
                   1905:                         $returnhash{$key}=&thaw_unescape($value);
                   1906:                     }
                   1907:                 }
                   1908:             }
                   1909:         }
                   1910:     }
                   1911:     return %returnhash;
                   1912: }
                   1913: 
                   1914: sub inst_userrules {
1.923     raeburn  1915:     my ($udom,$check) = @_;
1.912     raeburn  1916:     my (%ruleshash,@ruleorder);
                   1917:     if ($udom ne '') {
                   1918:         my $homeserver=&domain($udom,'primary');
                   1919:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1920:             my $response;
                   1921:             if ($check eq 'id') {
                   1922:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1923:                                  $homeserver);
1.943     raeburn  1924:             } elsif ($check eq 'email') {
                   1925:                 $response=&reply('instemailrules:'.&escape($udom),
                   1926:                                  $homeserver);
1.923     raeburn  1927:             } else {
                   1928:                 $response=&reply('instuserrules:'.&escape($udom),
                   1929:                                  $homeserver);
                   1930:             }
1.912     raeburn  1931:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1932:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1933:                 ($response ne 'no_such_host')) {
                   1934:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1935:                 my @pairs=split(/\&/,$hashitems);
                   1936:                 foreach my $item (@pairs) {
                   1937:                     my ($key,$value)=split(/=/,$item,2);
                   1938:                     $key = &unescape($key);
                   1939:                     next if ($key =~ /^error: 2 /);
                   1940:                     $ruleshash{$key}=&thaw_unescape($value);
                   1941:                 }
                   1942:                 my @esc_order = split(/\&/,$orderitems);
                   1943:                 foreach my $item (@esc_order) {
                   1944:                     push(@ruleorder,&unescape($item));
                   1945:                 }
                   1946:             }
                   1947:         }
                   1948:     }
                   1949:     return (\%ruleshash,\@ruleorder);
                   1950: }
                   1951: 
1.976     raeburn  1952: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1953: 
                   1954: sub get_domain_defaults {
                   1955:     my ($domain) = @_;
                   1956:     my $cachetime = 60*60*24;
                   1957:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1958:     if (defined($cached)) {
                   1959:         if (ref($result) eq 'HASH') {
                   1960:             return %{$result};
                   1961:         }
                   1962:     }
                   1963:     my %domdefaults;
                   1964:     my %domconfig =
1.989     raeburn  1965:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1966:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  1967:                                   'coursedefaults','usersessions',
                   1968:                                   'requestauthor'],$domain);
1.943     raeburn  1969:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1970:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1971:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1972:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1973:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1974:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  1975:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  1976:     } else {
                   1977:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1978:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1979:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1980:     }
1.976     raeburn  1981:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1982:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1983:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1984:         } else {
                   1985:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1986:         } 
1.1172.2.6  raeburn  1987:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  1988:         foreach my $item (@usertools) {
                   1989:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1990:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1991:             }
                   1992:         }
                   1993:     }
1.985     raeburn  1994:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1995:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1996:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1997:         }
                   1998:     }
1.1172.2.9  raeburn  1999:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2000:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2001:     }
1.989     raeburn  2002:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   2003:         foreach my $item ('inststatustypes','inststatusorder') {
                   2004:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2005:         }
                   2006:     }
1.1047    raeburn  2007:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.19  raeburn  2008:         if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2009:             $domdefaults{'officialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'official'};
                   2010:             $domdefaults{'unofficialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'unofficial'};
1.1047    raeburn  2011:         }
                   2012:     }
1.1073    raeburn  2013:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2014:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2015:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2016:         }
                   2017:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2018:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2019:         }
                   2020:     }
1.943     raeburn  2021:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   2022:                                   $cachetime);
                   2023:     return %domdefaults;
                   2024: }
                   2025: 
1.344     www      2026: # --------------------------------------------------- Assign a key to a student
                   2027: 
                   2028: sub assign_access_key {
1.364     www      2029: #
                   2030: # a valid key looks like uname:udom#comments
                   2031: # comments are being appended
                   2032: #
1.498     www      2033:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2034:     $kdom=
1.620     albertel 2035:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2036:     $knum=
1.620     albertel 2037:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2038:     $cdom=
1.620     albertel 2039:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2040:     $cnum=
1.620     albertel 2041:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2042:     $udom=$env{'user.name'} unless (defined($udom));
                   2043:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2044:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2045:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2046:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2047:                                                   # assigned to this person
                   2048:                                                   # - this should not happen,
1.345     www      2049:                                                   # unless something went wrong
                   2050:                                                   # the first time around
                   2051: # ready to assign
1.364     www      2052:         $logentry=$1.'; '.$logentry;
1.496     www      2053:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2054:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2055: # key now belongs to user
1.346     www      2056: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2057:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2058:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2059:                 return 'ok';
                   2060:             } else {
                   2061:                 return 
                   2062:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2063: 	    }
                   2064:         } else {
                   2065:             return 'error: Could not assign key, try again later.';
                   2066:         }
1.364     www      2067:     } elsif (!$existing{$ckey}) {
1.345     www      2068: # the key does not exist
                   2069: 	return 'error: The key does not exist';
                   2070:     } else {
                   2071: # the key is somebody else's
                   2072: 	return 'error: The key is already in use';
                   2073:     }
1.344     www      2074: }
                   2075: 
1.364     www      2076: # ------------------------------------------ put an additional comment on a key
                   2077: 
                   2078: sub comment_access_key {
                   2079: #
                   2080: # a valid key looks like uname:udom#comments
                   2081: # comments are being appended
                   2082: #
                   2083:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2084:     $cdom=
1.620     albertel 2085:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2086:     $cnum=
1.620     albertel 2087:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2088:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2089:     if ($existing{$ckey}) {
                   2090:         $existing{$ckey}.='; '.$logentry;
                   2091: # ready to assign
1.367     www      2092:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2093:                                                  $cdom,$cnum) eq 'ok') {
                   2094: 	    return 'ok';
                   2095:         } else {
                   2096: 	    return 'error: Count not store comment.';
                   2097:         }
                   2098:     } else {
                   2099: # the key does not exist
                   2100: 	return 'error: The key does not exist';
                   2101:     }
                   2102: }
                   2103: 
1.344     www      2104: # ------------------------------------------------------ Generate a set of keys
                   2105: 
                   2106: sub generate_access_keys {
1.364     www      2107:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2108:     $cdom=
1.620     albertel 2109:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2110:     $cnum=
1.620     albertel 2111:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2112:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2113:     unless (($cdom) && ($cnum)) { return 0; }
                   2114:     if ($number>10000) { return 0; }
                   2115:     sleep(2); # make sure don't get same seed twice
                   2116:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2117:     my $total=0;
                   2118:     for (my $i=1;$i<=$number;$i++) {
                   2119:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2120:                   sprintf("%lx",int(100000*rand)).'-'.
                   2121:                   sprintf("%lx",int(100000*rand));
                   2122:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2123:        $newkey=~s/0/h/g; # and also 0 and O
                   2124:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2125:        if ($existing{$newkey}) {
                   2126:            $i--;
                   2127:        } else {
1.364     www      2128: 	  if (&put('accesskeys',
                   2129:               { $newkey => '# generated '.localtime().
1.620     albertel 2130:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2131:                            '; '.$logentry },
                   2132: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2133:               $total++;
                   2134: 	  }
                   2135:        }
                   2136:     }
1.620     albertel 2137:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2138:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2139:     return $total;
                   2140: }
                   2141: 
                   2142: # ------------------------------------------------------- Validate an accesskey
                   2143: 
                   2144: sub validate_access_key {
                   2145:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2146:     $cdom=
1.620     albertel 2147:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2148:     $cnum=
1.620     albertel 2149:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2150:     $udom=$env{'user.domain'} unless (defined($udom));
                   2151:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2152:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2153:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2154: }
                   2155: 
                   2156: # ------------------------------------- Find the section of student in a course
1.652     albertel 2157: sub devalidate_getsection_cache {
                   2158:     my ($udom,$unam,$courseid)=@_;
                   2159:     my $hashid="$udom:$unam:$courseid";
                   2160:     &devalidate_cache_new('getsection',$hashid);
                   2161: }
1.298     matthew  2162: 
1.815     albertel 2163: sub courseid_to_courseurl {
                   2164:     my ($courseid) = @_;
                   2165:     #already url style courseid
                   2166:     return $courseid if ($courseid =~ m{^/});
                   2167: 
                   2168:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2169: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2170: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2171: 	return "/$cdom/$cnum";
                   2172:     }
                   2173: 
                   2174:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2175:     if (exists($courseinfo{'num'})) {
                   2176: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2177:     }
                   2178: 
                   2179:     return undef;
                   2180: }
                   2181: 
1.298     matthew  2182: sub getsection {
                   2183:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2184:     my $cachetime=1800;
1.551     albertel 2185: 
                   2186:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2187:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2188:     if (defined($cached)) { return $result; }
                   2189: 
1.298     matthew  2190:     my %Pending; 
                   2191:     my %Expired;
                   2192:     #
                   2193:     # Each role can either have not started yet (pending), be active, 
                   2194:     #    or have expired.
                   2195:     #
                   2196:     # If there is an active role, we are done.
                   2197:     #
                   2198:     # If there is more than one role which has not started yet, 
                   2199:     #     choose the one which will start sooner
                   2200:     # If there is one role which has not started yet, return it.
                   2201:     #
                   2202:     # If there is more than one expired role, choose the one which ended last.
                   2203:     # If there is a role which has expired, return it.
                   2204:     #
1.815     albertel 2205:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2206:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2207:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2208:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2209:         my $section=$1;
                   2210:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2211:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2212:         my $now=time;
1.548     albertel 2213:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2214:             $Expired{$end}=$section;
                   2215:             next;
                   2216:         }
1.548     albertel 2217:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2218:             $Pending{$start}=$section;
                   2219:             next;
                   2220:         }
1.599     albertel 2221:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2222:     }
                   2223:     #
                   2224:     # Presumedly there will be few matching roles from the above
                   2225:     # loop and the sorting time will be negligible.
                   2226:     if (scalar(keys(%Pending))) {
                   2227:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2228:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2229:     } 
                   2230:     if (scalar(keys(%Expired))) {
                   2231:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2232:         my $time = pop(@sorted);
1.599     albertel 2233:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2234:     }
1.599     albertel 2235:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2236: }
1.70      www      2237: 
1.599     albertel 2238: sub save_cache {
                   2239:     &purge_remembered();
1.722     albertel 2240:     #&Apache::loncommon::validate_page();
1.620     albertel 2241:     undef(%env);
1.780     albertel 2242:     undef($env_loaded);
1.599     albertel 2243: }
1.452     albertel 2244: 
1.599     albertel 2245: my $to_remember=-1;
                   2246: my %remembered;
                   2247: my %accessed;
                   2248: my $kicks=0;
                   2249: my $hits=0;
1.849     albertel 2250: sub make_key {
                   2251:     my ($name,$id) = @_;
1.872     albertel 2252:     if (length($id) > 65 
                   2253: 	&& length(&escape($id)) > 200) {
                   2254: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2255:     }
1.849     albertel 2256:     return &escape($name.':'.$id);
                   2257: }
                   2258: 
1.599     albertel 2259: sub devalidate_cache_new {
                   2260:     my ($name,$id,$debug) = @_;
                   2261:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2262:     $id=&make_key($name,$id);
1.599     albertel 2263:     $memcache->delete($id);
                   2264:     delete($remembered{$id});
                   2265:     delete($accessed{$id});
                   2266: }
                   2267: 
                   2268: sub is_cached_new {
                   2269:     my ($name,$id,$debug) = @_;
1.849     albertel 2270:     $id=&make_key($name,$id);
1.599     albertel 2271:     if (exists($remembered{$id})) {
1.1133    foxr     2272: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2273: 	$accessed{$id}=[&gettimeofday()];
                   2274: 	$hits++;
                   2275: 	return ($remembered{$id},1);
                   2276:     }
                   2277:     my $value = $memcache->get($id);
                   2278:     if (!(defined($value))) {
                   2279: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2280: 	return (undef,undef);
1.416     albertel 2281:     }
1.599     albertel 2282:     if ($value eq '__undef__') {
                   2283: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2284: 	$value=undef;
                   2285:     }
                   2286:     &make_room($id,$value,$debug);
                   2287:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2288:     return ($value,1);
                   2289: }
                   2290: 
                   2291: sub do_cache_new {
                   2292:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2293:     $id=&make_key($name,$id);
1.599     albertel 2294:     my $setvalue=$value;
                   2295:     if (!defined($setvalue)) {
                   2296: 	$setvalue='__undef__';
                   2297:     }
1.623     albertel 2298:     if (!defined($time) ) {
                   2299: 	$time=600;
                   2300:     }
1.599     albertel 2301:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2302:     my $result = $memcache->set($id,$setvalue,$time);
                   2303:     if (! $result) {
1.872     albertel 2304: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2305: 	$memcache->disconnect_all();
1.872     albertel 2306:     }
1.600     albertel 2307:     # need to make a copy of $value
1.919     albertel 2308:     &make_room($id,$value,$debug);
1.599     albertel 2309:     return $value;
                   2310: }
                   2311: 
                   2312: sub make_room {
                   2313:     my ($id,$value,$debug)=@_;
1.919     albertel 2314: 
                   2315:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2316:                                     : $value;
1.599     albertel 2317:     if ($to_remember<0) { return; }
                   2318:     $accessed{$id}=[&gettimeofday()];
                   2319:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2320:     my $to_kick;
                   2321:     my $max_time=0;
                   2322:     foreach my $other (keys(%accessed)) {
                   2323: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2324: 	    $to_kick=$other;
                   2325: 	    $max_time=&tv_interval($accessed{$other});
                   2326: 	}
                   2327:     }
                   2328:     delete($remembered{$to_kick});
                   2329:     delete($accessed{$to_kick});
                   2330:     $kicks++;
                   2331:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2332:     return;
                   2333: }
                   2334: 
1.599     albertel 2335: sub purge_remembered {
1.604     albertel 2336:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2337:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2338:     undef(%remembered);
                   2339:     undef(%accessed);
1.428     albertel 2340: }
1.70      www      2341: # ------------------------------------- Read an entry from a user's environment
                   2342: 
                   2343: sub userenvironment {
                   2344:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2345:     my $items;
                   2346:     foreach my $item (@what) {
                   2347:         $items.=&escape($item).'&';
                   2348:     }
                   2349:     $items=~s/\&$//;
1.70      www      2350:     my %returnhash=();
1.1009    raeburn  2351:     my $uhome = &homeserver($unam,$udom);
                   2352:     unless ($uhome eq 'no_host') {
                   2353:         my @answer=split(/\&/, 
                   2354:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2355:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2356:             return %returnhash;
                   2357:         }
1.1009    raeburn  2358:         my $i;
                   2359:         for ($i=0;$i<=$#what;$i++) {
                   2360: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2361:         }
1.70      www      2362:     }
                   2363:     return %returnhash;
1.1       albertel 2364: }
                   2365: 
1.617     albertel 2366: # ---------------------------------------------------------- Get a studentphoto
                   2367: sub studentphoto {
                   2368:     my ($udom,$unam,$ext) = @_;
                   2369:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2370:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2371:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2372:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2373:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2374:             } else {
                   2375:                 my ($result,$perm_reqd)=
1.707     albertel 2376: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2377:                 if ($result eq 'ok') {
                   2378:                     if (!($perm_reqd eq 'yes')) {
                   2379:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2380:                     }
                   2381:                 }
                   2382:             }
                   2383:         }
                   2384:     } else {
                   2385:         my ($result,$perm_reqd) = 
1.707     albertel 2386: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2387:         if ($result eq 'ok') {
                   2388:             if (!($perm_reqd eq 'yes')) {
                   2389:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2390:             }
                   2391:         }
                   2392:     }
                   2393:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2394: }
                   2395: 
                   2396: sub retrievestudentphoto {
                   2397:     my ($udom,$unam,$ext,$type) = @_;
                   2398:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2399:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2400:     if ($ret eq 'ok') {
                   2401:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2402:         if ($type eq 'thumbnail') {
                   2403:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2404:         }
                   2405:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2406:         return $tokenurl;
                   2407:     } else {
                   2408:         if ($type eq 'thumbnail') {
                   2409:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2410:         } else { 
                   2411:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2412:         }
1.617     albertel 2413:     }
                   2414: }
                   2415: 
1.263     www      2416: # -------------------------------------------------------------------- New chat
                   2417: 
                   2418: sub chatsend {
1.724     raeburn  2419:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2420:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2421:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2422:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2423:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2424: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2425: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2426: }
                   2427: 
                   2428: # ------------------------------------------ Find current version of a resource
                   2429: 
                   2430: sub getversion {
                   2431:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2432:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2433:     return &currentversion(&filelocation('',$fname));
                   2434: }
                   2435: 
                   2436: sub currentversion {
                   2437:     my $fname=shift;
                   2438:     my $author=$fname;
                   2439:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2440:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2441:     my $home=&homeserver($uname,$udom);
1.292     www      2442:     if ($home eq 'no_host') { 
                   2443:         return -1; 
                   2444:     }
1.1112    www      2445:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2446:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2447: 	return -1;
                   2448:     }
1.1112    www      2449:     return $answer;
1.263     www      2450: }
                   2451: 
1.1111    www      2452: #
                   2453: # Return special version number of resource if set by override, empty otherwise
                   2454: #
                   2455: sub usedversion {
                   2456:     my $fname=shift;
                   2457:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2458:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2459:     if ($urlversion) { return $urlversion; }
                   2460:     return '';
                   2461: }
                   2462: 
1.1       albertel 2463: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2464: 
1.1       albertel 2465: sub subscribe {
                   2466:     my $fname=shift;
1.761     raeburn  2467:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2468:     $fname=~s/[\n\r]//g;
1.1       albertel 2469:     my $author=$fname;
                   2470:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2471:     my ($udom,$uname)=split(/\//,$author);
                   2472:     my $home=homeserver($uname,$udom);
1.335     albertel 2473:     if ($home eq 'no_host') {
                   2474:         return 'not_found';
1.1       albertel 2475:     }
                   2476:     my $answer=reply("sub:$fname",$home);
1.64      www      2477:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2478: 	$answer.=' by '.$home;
                   2479:     }
1.1       albertel 2480:     return $answer;
                   2481: }
                   2482:     
1.8       www      2483: # -------------------------------------------------------------- Replicate file
                   2484: 
                   2485: sub repcopy {
                   2486:     my $filename=shift;
1.23      www      2487:     $filename=~s/\/+/\//g;
1.1142    raeburn  2488:     my $londocroot = $perlvar{'lonDocRoot'};
                   2489:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2490:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2491:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2492: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2493: 	return &repcopy_userfile($filename);
                   2494:     }
1.532     albertel 2495:     $filename=~s/[\n\r]//g;
1.8       www      2496:     my $transname="$filename.in.transfer";
1.828     www      2497: # FIXME: this should flock
1.607     raeburn  2498:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2499:     my $remoteurl=subscribe($filename);
1.64      www      2500:     if ($remoteurl =~ /^con_lost by/) {
                   2501: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2502:            return 'unavailable';
1.8       www      2503:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2504: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2505: 	   return 'not_found';
1.64      www      2506:     } elsif ($remoteurl =~ /^rejected by/) {
                   2507: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2508:            return 'forbidden';
1.20      www      2509:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2510:            return 'ok';
1.8       www      2511:     } else {
1.290     www      2512:         my $author=$filename;
                   2513:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2514:         my ($udom,$uname)=split(/\//,$author);
                   2515:         my $home=homeserver($uname,$udom);
                   2516:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2517:            my @parts=split(/\//,$filename);
                   2518:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2519:            if ($path ne "$londocroot/res") {
1.8       www      2520:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2521: 	       return 'bad_request';
1.8       www      2522:            }
                   2523:            my $count;
                   2524:            for ($count=5;$count<$#parts;$count++) {
                   2525:                $path.="/$parts[$count]";
                   2526:                if ((-e $path)!=1) {
                   2527: 		   mkdir($path,0777);
                   2528:                }
                   2529:            }
                   2530:            my $ua=new LWP::UserAgent;
                   2531:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2532:            my $response=$ua->request($request,$transname);
                   2533:            if ($response->is_error()) {
                   2534: 	       unlink($transname);
                   2535:                my $message=$response->status_line;
1.672     albertel 2536:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2537:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2538:                return 'unavailable';
1.8       www      2539:            } else {
1.16      www      2540: 	       if ($remoteurl!~/\.meta$/) {
                   2541:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2542:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2543:                   if ($mresponse->is_error()) {
                   2544: 		      unlink($filename.'.meta');
                   2545:                       &logthis(
1.672     albertel 2546:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2547:                   }
                   2548: 	       }
1.8       www      2549:                rename($transname,$filename);
1.607     raeburn  2550:                return 'ok';
1.8       www      2551:            }
1.290     www      2552:        }
1.8       www      2553:     }
1.330     www      2554: }
                   2555: 
                   2556: # ------------------------------------------------ Get server side include body
                   2557: sub ssi_body {
1.381     albertel 2558:     my ($filelink,%form)=@_;
1.606     matthew  2559:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2560:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2561:     }
1.953     www      2562:     my $output='';
                   2563:     my $response;
1.980     raeburn  2564:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2565:        ($output,$response)=&externalssi($filelink);
1.953     www      2566:     } else {
1.1004    droeschl 2567:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2568:        $filelink .= 'inhibitmenu=yes';
1.953     www      2569:        ($output,$response)=&ssi($filelink,%form);
                   2570:     }
1.778     albertel 2571:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2572:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2573:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2574:     if (wantarray) {
                   2575:         return ($output, $response);
                   2576:     } else {
                   2577:         return $output;
                   2578:     }
1.8       www      2579: }
                   2580: 
1.15      www      2581: # --------------------------------------------------------- Server Side Include
                   2582: 
1.782     albertel 2583: sub absolute_url {
                   2584:     my ($host_name) = @_;
                   2585:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2586:     if ($host_name eq '') {
                   2587: 	$host_name = $ENV{'SERVER_NAME'};
                   2588:     }
                   2589:     return $protocol.$host_name;
                   2590: }
                   2591: 
1.942     foxr     2592: #
                   2593: #   Server side include.
                   2594: # Parameters:
                   2595: #  fn     Possibly encrypted resource name/id.
                   2596: #  form   Hash that describes how the rendering should be done
                   2597: #         and other things.
1.944     foxr     2598: # Returns:
1.950     raeburn  2599: #   Scalar context: The content of the response.
                   2600: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2601: #     
1.15      www      2602: sub ssi {
                   2603: 
1.944     foxr     2604:     my ($fn,%form)=@_;
1.15      www      2605:     my $ua=new LWP::UserAgent;
1.23      www      2606:     my $request;
1.711     albertel 2607: 
                   2608:     $form{'no_update_last_known'}=1;
1.895     albertel 2609:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2610:     if (%form) {
1.782     albertel 2611:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2612:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2613:     } else {
1.782     albertel 2614:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2615:     }
                   2616: 
1.15      www      2617:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2  raeburn  2618:     my $response= $ua->request($request);
1.944     foxr     2619:     if (wantarray) {
1.1172.2.3  raeburn  2620: 	return ($response->content, $response);
1.944     foxr     2621:     } else {
1.1172.2.3  raeburn  2622: 	return $response->content;
1.942     foxr     2623:     }
1.324     www      2624: }
                   2625: 
                   2626: sub externalssi {
                   2627:     my ($url)=@_;
                   2628:     my $ua=new LWP::UserAgent;
                   2629:     my $request=new HTTP::Request('GET',$url);
                   2630:     my $response=$ua->request($request);
1.954     raeburn  2631:     if (wantarray) {
                   2632:         return ($response->content, $response);
                   2633:     } else {
                   2634:         return $response->content;
                   2635:     }
1.15      www      2636: }
1.254     www      2637: 
1.492     albertel 2638: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2639: 
                   2640: sub allowuploaded {
                   2641:     my ($srcurl,$url)=@_;
                   2642:     $url=&clutter(&declutter($url));
                   2643:     my $dir=$url;
                   2644:     $dir=~s/\/[^\/]+$//;
                   2645:     my %httpref=();
                   2646:     my $httpurl=&hreflocation('',$url);
                   2647:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2648:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2649: }
1.477     raeburn  2650: 
1.1172.2.13  raeburn  2651: #
                   2652: # Determine if the current user should be able to edit a particular resource,
                   2653: # when viewing in course context.
                   2654: # (a) When viewing resource used to determine if "Edit" item is included in
                   2655: #     Functions.
                   2656: # (b) When displaying folder contents in course editor, used to determine if
                   2657: #     "Edit" link will be displayed alongside resource.
                   2658: #
                   2659: #  input: six args -- filename (decluttered), course number, course domain,
                   2660: #                   url, symb (if registered) and group (if this is a group
                   2661: #                   item -- e.g., bulletin board, group page etc.).
                   2662: #  output: array of five scalars --
                   2663: #          $cfile -- url for file editing if editable on current server
                   2664: #          $home -- homeserver of resource (i.e., for author if published,
                   2665: #                                           or course if uploaded.).
                   2666: #          $switchserver --  1 if server switch will be needed.
                   2667: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   2668: #          $forceview -- 1 if icon/link should be to go to view mode
                   2669: #
                   2670: 
                   2671: sub can_edit_resource {
                   2672:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   2673:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   2674: #
                   2675: # For aboutme pages user can only edit his/her own.
                   2676: #
                   2677:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   2678:         my ($sdom,$sname) = ($1,$2);
                   2679:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   2680:             $home = $env{'user.home'};
                   2681:             $cfile = $resurl;
                   2682:             if ($env{'form.forceedit'}) {
                   2683:                 $forceview = 1;
                   2684:             } else {
                   2685:                 $forceedit = 1;
                   2686:             }
                   2687:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2688:         } else {
                   2689:             return;
                   2690:         }
                   2691:     }
                   2692: 
                   2693:     if ($env{'request.course.id'}) {
                   2694:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   2695:         if ($group ne '') {
                   2696: # if this is a group homepage or group bulletin board, check group privs
                   2697:             my $allowed = 0;
                   2698:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   2699:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   2700:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2701:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2702:                     $allowed = 1;
                   2703:                 }
                   2704:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   2705:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2706:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2707:                     $allowed = 1;
                   2708:                 }
                   2709:             }
                   2710:             if ($allowed) {
                   2711:                 $home=&homeserver($cnum,$cdom);
                   2712:                 if ($env{'form.forceedit'}) {
                   2713:                     $forceview = 1;
                   2714:                 } else {
                   2715:                     $forceedit = 1;
                   2716:                 }
                   2717:                 $cfile = $resurl;
                   2718:             } else {
                   2719:                 return;
                   2720:             }
                   2721:         } else {
1.1172.2.15  raeburn  2722:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2723:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   2724:                     return;
                   2725:                 }
                   2726:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  2727: #
                   2728: # No edit allowed where CC has switched to student role.
                   2729: #
                   2730:                 return;
                   2731:             }
                   2732:         }
                   2733:     }
                   2734: 
                   2735:     if ($file ne '') {
                   2736:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   2737:             if (&is_course_upload($file,$cnum,$cdom)) {
                   2738:                 $uploaded = 1;
                   2739:                 $incourse = 1;
                   2740:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   2741:                     $cfile = &hreflocation('',$file);
                   2742:                     if ($env{'form.forceedit'}) {
                   2743:                         $forceview = 1;
                   2744:                     } else {
                   2745:                         $forceedit = 1;
                   2746:                     }
                   2747:                 }
                   2748:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   2749:                 $incourse = 1;
                   2750:                 if ($env{'form.forceedit'}) {
                   2751:                     $forceview = 1;
                   2752:                 } else {
                   2753:                     $forceedit = 1;
                   2754:                 }
                   2755:                 $cfile = $resurl;
                   2756:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   2757:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   2758:                     $incourse = 1;
                   2759:                     if ($env{'form.forceedit'}) {
                   2760:                         $forceview = 1;
                   2761:                     } else {
                   2762:                         $forceedit = 1;
                   2763:                     }
                   2764:                     $cfile = $resurl;
                   2765:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   2766:                     $incourse = 1;
                   2767:                     $cfile = $resurl.'/smpedit';
                   2768:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   2769:                     $incourse = 1;
                   2770:                     if ($env{'form.forceedit'}) {
                   2771:                         $forceview = 1;
                   2772:                     } else {
                   2773:                         $forceedit = 1;
                   2774:                     }
                   2775:                     $cfile = $resurl;
1.1172.2.15  raeburn  2776:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2777:                     $incourse = 1;
                   2778:                     if ($env{'form.forceedit'}) {
                   2779:                         $forceview = 1;
                   2780:                     } else {
                   2781:                         $forceedit = 1;
                   2782:                     }
                   2783:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  2784:                 }
                   2785:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   2786:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   2787:                 if (&is_on_map($template)) {
                   2788:                     $incourse = 1;
                   2789:                     $forceview = 1;
                   2790:                     $cfile = $template;
                   2791:                 }
                   2792:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   2793:                     $incourse = 1;
                   2794:                     if ($env{'form.forceedit'}) {
                   2795:                         $forceview = 1;
                   2796:                     } else {
                   2797:                         $forceedit = 1;
                   2798:                     }
                   2799:                     $cfile = $resurl;
                   2800:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   2801:                 $incourse = 1;
                   2802:                 $forceview = 1;
                   2803:                 if ($symb) {
                   2804:                     my ($map,$id,$res)=&decode_symb($symb);
                   2805:                     $env{'request.symb'} = $symb;
                   2806:                     $cfile = &clutter($res);
                   2807:                 } else {
                   2808:                     $cfile = $env{'form.suppurl'};
                   2809:                     $cfile =~ s{^http://}{};
                   2810:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   2811:                 }
                   2812:             }
                   2813:         }
                   2814:         if ($uploaded || $incourse) {
                   2815:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  2816:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  2817:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   2818:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   2819:             # Check that the user has permission to edit this resource
                   2820:             my $setpriv = 1;
                   2821:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   2822:             if (defined($cfudom)) {
                   2823:                 $home=&homeserver($cfuname,$cfudom);
                   2824:                 $cfile=$file;
                   2825:             }
                   2826:         }
                   2827:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   2828:             (($home ne '') && ($home ne 'no_host'))) {
                   2829:             my @ids=&current_machine_ids();
                   2830:             unless (grep(/^\Q$home\E$/,@ids)) {
                   2831:                 $switchserver=1;
                   2832:             }
                   2833:         }
                   2834:     }
                   2835:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2836: }
                   2837: 
                   2838: sub is_course_upload {
                   2839:     my ($file,$cnum,$cdom) = @_;
                   2840:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   2841:     $uploadpath =~ s{^\/}{};
                   2842:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   2843:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   2844:         return 1;
                   2845:     }
                   2846:     return;
                   2847: }
                   2848: 
                   2849: sub in_course {
                   2850:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   2851:     if ($hideprivileged) {
                   2852:         my $skipuser;
                   2853:         if (&privileged($uname,$udom)) {
                   2854:             $skipuser = 1;
                   2855:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   2856:             if ($coursehash{'nothideprivileged'}) {
                   2857:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2858:                     my $user;
                   2859:                     if ($item =~ /:/) {
                   2860:                         $user = $item;
                   2861:                     } else {
                   2862:                         $user = join(':',split(/[\@]/,$item));
                   2863:                     }
                   2864:                     if ($user eq $uname.':'.$udom) {
                   2865:                         undef($skipuser);
                   2866:                         last;
                   2867:                     }
                   2868:                 }
                   2869:             }
                   2870:             if ($skipuser) {
                   2871:                 return 0;
                   2872:             }
                   2873:         }
                   2874:     }
                   2875:     $type ||= 'any';
                   2876:     if (!defined($cdom) || !defined($cnum)) {
                   2877:         my $cid  = $env{'request.course.id'};
                   2878:         $cdom = $env{'course.'.$cid.'.domain'};
                   2879:         $cnum = $env{'course.'.$cid.'.num'};
                   2880:     }
                   2881:     my $typesref;
                   2882:     if (($type eq 'any') || ($type eq 'all')) {
                   2883:         $typesref = ['active','previous','future'];
                   2884:     } elsif ($type eq 'previous' || $type eq 'future') {
                   2885:         $typesref = [$type];
                   2886:     }
                   2887:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   2888:                               $typesref,undef,[$cdom]);
                   2889:     my ($tmp) = keys(%roles);
                   2890:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   2891:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   2892:     if (@course_roles > 0) {
                   2893:         return 1;
                   2894:     }
                   2895:     return 0;
                   2896: }
                   2897: 
1.478     albertel 2898: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2899: # input: action, courseID, current domain, intended
1.637     raeburn  2900: #        path to file, source of file, instruction to parse file for objects,
                   2901: #        ref to hash for embedded objects,
                   2902: #        ref to hash for codebase of java objects.
1.1095    raeburn  2903: #        reference to scalar to accommodate mime type determined
                   2904: #          from File::MMagic if $parser = parse.
1.637     raeburn  2905: #
1.485     raeburn  2906: # output: url to file (if action was uploaddoc), 
                   2907: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2908: #
1.478     albertel 2909: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2910: # course.
1.477     raeburn  2911: #
1.478     albertel 2912: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2913: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2914: #          course's home server.
1.477     raeburn  2915: #
1.478     albertel 2916: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2917: #          be copied from $source (current location) to 
                   2918: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2919: #         and will then be copied to
                   2920: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2921: #         course's home server.
1.485     raeburn  2922: #
1.481     raeburn  2923: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2924: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2925: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2926: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2927: #         in course's home server.
1.637     raeburn  2928: #
1.477     raeburn  2929: 
                   2930: sub process_coursefile {
1.1095    raeburn  2931:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2932:         $mimetype)=@_;
1.477     raeburn  2933:     my $fetchresult;
1.638     albertel 2934:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2935:     if ($action eq 'propagate') {
1.638     albertel 2936:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2937: 			     $home);
1.481     raeburn  2938:     } else {
1.477     raeburn  2939:         my $fpath = '';
                   2940:         my $fname = $file;
1.478     albertel 2941:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2942:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2943:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2944:         if ($action eq 'copy') {
                   2945:             if ($source eq '') {
                   2946:                 $fetchresult = 'no source file';
                   2947:                 return $fetchresult;
                   2948:             } else {
                   2949:                 my $destination = $filepath.'/'.$fname;
                   2950:                 rename($source,$destination);
                   2951:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2952:                                  $home);
1.481     raeburn  2953:             }
                   2954:         } elsif ($action eq 'uploaddoc') {
                   2955:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2956:             print $fh $env{'form.'.$source};
1.481     raeburn  2957:             close($fh);
1.637     raeburn  2958:             if ($parser eq 'parse') {
1.1024    raeburn  2959:                 my $mm = new File::MMagic;
1.1095    raeburn  2960:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2961:                 if ($type eq 'text/html') {
1.1024    raeburn  2962:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2963:                     unless ($parse_result eq 'ok') {
                   2964:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2965:                     }
1.637     raeburn  2966:                 }
1.1095    raeburn  2967:                 if (ref($mimetype)) {
                   2968:                     $$mimetype = $type;
                   2969:                 } 
1.637     raeburn  2970:             }
1.477     raeburn  2971:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2972:                                  $home);
1.481     raeburn  2973:             if ($fetchresult eq 'ok') {
                   2974:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2975:             } else {
                   2976:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2977:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2978:                 return '/adm/notfound.html';
                   2979:             }
1.477     raeburn  2980:         }
                   2981:     }
1.485     raeburn  2982:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2983:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2984:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2985:     }
                   2986:     return $fetchresult;
                   2987: }
                   2988: 
1.637     raeburn  2989: sub build_filepath {
                   2990:     my ($fpath) = @_;
                   2991:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2992:     unless ($fpath eq '') {
                   2993:         my @parts=split('/',$fpath);
                   2994:         foreach my $part (@parts) {
                   2995:             $filepath.= '/'.$part;
                   2996:             if ((-e $filepath)!=1) {
                   2997:                 mkdir($filepath,0777);
                   2998:             }
                   2999:         }
                   3000:     }
                   3001:     return $filepath;
                   3002: }
                   3003: 
                   3004: sub store_edited_file {
1.638     albertel 3005:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3006:     my $file = $primary_url;
                   3007:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3008:     my $fpath = '';
                   3009:     my $fname = $file;
                   3010:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3011:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3012:     my $filepath = &build_filepath($fpath);
                   3013:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3014:     print $fh $content;
                   3015:     close($fh);
1.638     albertel 3016:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3017:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3018: 			  $home);
1.637     raeburn  3019:     if ($$fetchresult eq 'ok') {
                   3020:         return '/uploaded/'.$fpath.'/'.$fname;
                   3021:     } else {
1.638     albertel 3022:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3023: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3024:         return '/adm/notfound.html';
                   3025:     }
                   3026: }
                   3027: 
1.531     albertel 3028: sub clean_filename {
1.831     albertel 3029:     my ($fname,$args)=@_;
1.315     www      3030: # Replace Windows backslashes by forward slashes
1.257     www      3031:     $fname=~s/\\/\//g;
1.831     albertel 3032:     if (!$args->{'keep_path'}) {
                   3033:         # Get rid of everything but the actual filename
                   3034: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3035:     }
1.315     www      3036: # Replace spaces by underscores
                   3037:     $fname=~s/\s+/\_/g;
                   3038: # Replace all other weird characters by nothing
1.831     albertel 3039:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3040: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3041: # numbers
                   3042:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3043:     return $fname;
                   3044: }
1.1051    raeburn  3045: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3046: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3047: # image with the same aspect ratio as the original, but with dimensions which do 
                   3048: # not exceed $resizewidth and $resizeheight.
                   3049:  
1.984     neumanie 3050: sub resizeImage {
1.1051    raeburn  3051:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3052:     my $ima = Image::Magick->new;
                   3053:     my $resized;
                   3054:     if (-e $img_path) {
                   3055:         $ima->Read($img_path);
                   3056:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3057:             my $width = $ima->Get('width');
                   3058:             my $height = $ima->Get('height');
                   3059:             if ($width > $resizewidth) {
                   3060: 	        my $factor = $width/$resizewidth;
                   3061:                 my $newheight = $height/$factor;
                   3062:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3063:                 $resized = 1;
                   3064:             }
                   3065:         }
                   3066:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3067:             my $width = $ima->Get('width');
                   3068:             my $height = $ima->Get('height');
                   3069:             if ($height > $resizeheight) {
                   3070:                 my $factor = $height/$resizeheight;
                   3071:                 my $newwidth = $width/$factor;
                   3072:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3073:                 $resized = 1;
                   3074:             }
                   3075:         }
                   3076:         if ($resized) {
                   3077:             $ima->Write($img_path);
                   3078:         }
                   3079:     }
                   3080:     return;
1.977     amueller 3081: }
                   3082: 
1.608     albertel 3083: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3084: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3085: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3086: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3087: #                                    canceloverwrite, or ''. 
                   3088: #                   if 'coursedoc': upload to the current course
                   3089: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3090: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3091: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3092: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3093: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3094: #        $allfiles - reference to hash for embedded objects
                   3095: #        $codebase - reference to hash for codebase of java objects
                   3096: #        $desuname - username for permanent storage of uploaded file
                   3097: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3098: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3099: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3100: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3101: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3102: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3103: #                    from File::MMagic.
1.858     raeburn  3104: # 
1.686     albertel 3105: # output: url of file in userspace, or error: <message> 
                   3106: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3107: 
1.531     albertel 3108: sub userfileupload {
1.1090    raeburn  3109:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3110:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3111:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3112:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3113:     $fname=&clean_filename($fname);
1.1090    raeburn  3114:     # See if there is anything left
1.257     www      3115:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3116:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3117:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3118:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3119:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3120:         my $now = time;
1.1090    raeburn  3121:         my $filepath;
1.1095    raeburn  3122:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3123:              $filepath = 'tmp/helprequests/'.$now;
                   3124:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3125:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3126:                          '_'.$env{'user.domain'}.'/pending';
                   3127:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3128:             my ($docuname,$docudom);
                   3129:             if ($destudom) {
                   3130:                 $docudom = $destudom;
                   3131:             } else {
                   3132:                 $docudom = $env{'user.domain'};
                   3133:             }
                   3134:             if ($destuname) {
                   3135:                 $docuname = $destuname;
                   3136:             } else {
                   3137:                 $docuname = $env{'user.name'};
                   3138:             }
                   3139:             if (exists($env{'form.group'})) {
                   3140:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3141:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3142:             }
                   3143:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3144:             if ($context eq 'canceloverwrite') {
                   3145:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3146:                 if (-e  $tempfile) {
                   3147:                     my @info = stat($tempfile);
                   3148:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3149:                         unlink($tempfile);
                   3150:                     }
                   3151:                 }
                   3152:                 return;
1.523     raeburn  3153:             }
                   3154:         }
1.1090    raeburn  3155:         # Create the directory if not present
1.741     raeburn  3156:         my @parts=split(/\//,$filepath);
                   3157:         my $fullpath = $perlvar{'lonDaemons'};
                   3158:         for (my $i=0;$i<@parts;$i++) {
                   3159:             $fullpath .= '/'.$parts[$i];
                   3160:             if ((-e $fullpath)!=1) {
                   3161:                 mkdir($fullpath,0777);
                   3162:             }
                   3163:         }
                   3164:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3165:         print $fh $env{'form.'.$formname};
                   3166:         close($fh);
1.1090    raeburn  3167:         if ($context eq 'existingfile') {
                   3168:             my @info = stat($fullpath.'/'.$fname);
                   3169:             return ($fullpath.'/'.$fname,$info[9]);
                   3170:         } else {
                   3171:             return $fullpath.'/'.$fname;
                   3172:         }
1.523     raeburn  3173:     }
1.995     raeburn  3174:     if ($subdir eq 'scantron') {
                   3175:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3176:     } else {
1.995     raeburn  3177:         $fname="$subdir/$fname";
                   3178:     }
1.1090    raeburn  3179:     if ($context eq 'coursedoc') {
1.638     albertel 3180: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3181: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3182:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3183:             return &finishuserfileupload($docuname,$docudom,
                   3184: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3185: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3186:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3187:         } else {
1.1172.2.21  raeburn  3188:             if ($env{'form.folder'}) {
                   3189:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3190:             }
1.638     albertel 3191:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3192: 				       $fname,$formname,$parser,
1.1095    raeburn  3193: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3194:         }
1.719     banghart 3195:     } elsif (defined($destuname)) {
                   3196:         my $docuname=$destuname;
                   3197:         my $docudom=$destudom;
1.860     raeburn  3198: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3199: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3200:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3201:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3202:     } else {
1.638     albertel 3203:         my $docuname=$env{'user.name'};
                   3204:         my $docudom=$env{'user.domain'};
1.714     raeburn  3205:         if (exists($env{'form.group'})) {
                   3206:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3207:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3208:         }
1.860     raeburn  3209: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3210: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3211:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3212:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3213:     }
1.271     www      3214: }
                   3215: 
                   3216: sub finishuserfileupload {
1.860     raeburn  3217:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3218:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3219:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3220:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3221:   
1.860     raeburn  3222:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3223:     $file=$fname;
                   3224:     if ($fname=~m|/|) {
                   3225:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3226: 	$path.=$fnamepath.'/';
                   3227:     }
1.259     www      3228:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3229:     my $count;
                   3230:     for ($count=4;$count<=$#parts;$count++) {
                   3231:         $filepath.="/$parts[$count]";
                   3232:         if ((-e $filepath)!=1) {
                   3233: 	    mkdir($filepath,0777);
                   3234:         }
                   3235:     }
1.984     neumanie 3236: 
1.258     www      3237: # Save the file
                   3238:     {
1.701     albertel 3239: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3240: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3241: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3242: 	    return '/adm/notfound.html';
                   3243: 	}
1.1090    raeburn  3244:         if ($context eq 'overwrite') {
1.1117    foxr     3245:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3246:             my $target = $filepath.'/'.$file;
                   3247:             if (-e $source) {
                   3248:                 my @info = stat($source);
                   3249:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3250:                     unless (&File::Copy::move($source,$target)) {
                   3251:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3252:                         return "Moving from $source failed";
                   3253:                     }
                   3254:                 } else {
                   3255:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3256:                 }
                   3257:             } else {
                   3258:                 return "Temporary file: $source missing";
                   3259:             }
                   3260:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3261: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3262: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3263: 	    return '/adm/notfound.html';
                   3264: 	}
1.570     albertel 3265: 	close(FH);
1.1051    raeburn  3266:         if ($resizewidth && $resizeheight) {
                   3267:             my $mm = new File::MMagic;
                   3268:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3269:             if ($mime_type =~ m{^image/}) {
                   3270: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3271:             }  
1.977     amueller 3272: 	}
1.258     www      3273:     }
1.1152    raeburn  3274:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3275:         if (ref($mimetype)) {
                   3276:             if ($$mimetype eq '') {
                   3277:                 my $mm = new File::MMagic;
                   3278:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3279:                 $$mimetype = $type;
                   3280:             }
                   3281:         }
                   3282:     }
1.637     raeburn  3283:     if ($parser eq 'parse') {
1.1152    raeburn  3284:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3285:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3286:                                                        $allfiles,$codebase);
                   3287:             unless ($parse_result eq 'ok') {
                   3288:                 &logthis('Failed to parse '.$filepath.$file.
                   3289: 	   	         ' for embedded media: '.$parse_result); 
                   3290:             }
1.637     raeburn  3291:         }
                   3292:     }
1.860     raeburn  3293:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3294:         my $input = $filepath.'/'.$file;
                   3295:         my $output = $filepath.'/'.'tn-'.$file;
                   3296:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3297:         system("convert -sample $thumbsize $input $output");
                   3298:         if (-e $filepath.'/'.'tn-'.$file) {
                   3299:             $fetchthumb  = 1; 
                   3300:         }
                   3301:     }
1.858     raeburn  3302:  
1.259     www      3303: # Notify homeserver to grep it
                   3304: #
1.984     neumanie 3305:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3306:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3307:     if ($fetchresult eq 'ok') {
1.860     raeburn  3308:         if ($fetchthumb) {
                   3309:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3310:             if ($thumbresult ne 'ok') {
                   3311:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3312:                          $docuhome.': '.$thumbresult);
                   3313:             }
                   3314:         }
1.259     www      3315: #
1.258     www      3316: # Return the URL to it
1.494     albertel 3317:         return '/uploaded/'.$path.$file;
1.263     www      3318:     } else {
1.494     albertel 3319:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3320: 		 ': '.$fetchresult);
1.263     www      3321:         return '/adm/notfound.html';
1.858     raeburn  3322:     }
1.493     albertel 3323: }
                   3324: 
1.637     raeburn  3325: sub extract_embedded_items {
1.961     raeburn  3326:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3327:     my @state = ();
1.1164    raeburn  3328:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3329:     my %javafiles = (
                   3330:                       codebase => '',
                   3331:                       code => '',
                   3332:                       archive => ''
                   3333:                     );
                   3334:     my %mediafiles = (
                   3335:                       src => '',
                   3336:                       movie => '',
                   3337:                      );
1.648     raeburn  3338:     my $p;
                   3339:     if ($content) {
                   3340:         $p = HTML::LCParser->new($content);
                   3341:     } else {
1.961     raeburn  3342:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3343:     }
1.641     albertel 3344:     while (my $t=$p->get_token()) {
1.640     albertel 3345: 	if ($t->[0] eq 'S') {
                   3346: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3347: 	    push(@state, $tagname);
1.648     raeburn  3348:             if (lc($tagname) eq 'allow') {
                   3349:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3350:             }
1.640     albertel 3351: 	    if (lc($tagname) eq 'img') {
                   3352: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3353: 	    }
1.886     albertel 3354: 	    if (lc($tagname) eq 'a') {
                   3355: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   3356: 	    }
1.645     raeburn  3357:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3358:                 my $src;
1.645     raeburn  3359:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3360:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3361:                 } else {
1.1164    raeburn  3362:                     if ($attr->{'src'} ne '') {
                   3363:                         $src = $attr->{'src'};
                   3364:                         &add_filetype($allfiles,$src,'src');
                   3365:                     }
                   3366:                 }
                   3367:                 my $text = $p->get_trimmed_text();
                   3368:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3369:                     my @swfargs = split(/,/,$1);
                   3370:                     foreach my $item (@swfargs) {
                   3371:                         $item =~ s/["']//g;
                   3372:                         $item =~ s/^\s+//;
                   3373:                         $item =~ s/\s+$//;
                   3374:                     }
                   3375:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3376:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3377:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3378:                         } else {
                   3379:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3380:                         }
                   3381:                     }
1.645     raeburn  3382:                 }
                   3383:             }
                   3384:             if (lc($tagname) eq 'link') {
                   3385:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3386:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3387:                 }
                   3388:             }
1.640     albertel 3389: 	    if (lc($tagname) eq 'object' ||
                   3390: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3391: 		foreach my $item (keys(%javafiles)) {
                   3392: 		    $javafiles{$item} = '';
                   3393: 		}
1.1164    raeburn  3394:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3395:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3396:                 }
1.640     albertel 3397: 	    }
                   3398: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3399: 		my $name = lc($attr->{'name'});
                   3400: 		foreach my $item (keys(%javafiles)) {
                   3401: 		    if ($name eq $item) {
                   3402: 			$javafiles{$item} = $attr->{'value'};
                   3403: 			last;
                   3404: 		    }
                   3405: 		}
1.1164    raeburn  3406:                 my $pathfrom;
1.640     albertel 3407: 		foreach my $item (keys(%mediafiles)) {
                   3408: 		    if ($name eq $item) {
1.1164    raeburn  3409:                         $pathfrom = $attr->{'value'};
                   3410:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3411: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3412: 			last;
                   3413: 		    }
                   3414: 		}
1.1164    raeburn  3415:                 if ($name eq 'flashvars') {
                   3416:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3417:                 }
                   3418:                 if ($pathfrom ne '') {
                   3419:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3420:                                          $pathfrom);
                   3421:                 }
1.640     albertel 3422: 	    }
                   3423: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3424: 		foreach my $item (keys(%javafiles)) {
                   3425: 		    if ($attr->{$item}) {
                   3426: 			$javafiles{$item} = $attr->{$item};
                   3427: 			last;
                   3428: 		    }
                   3429: 		}
                   3430: 		foreach my $item (keys(%mediafiles)) {
                   3431: 		    if ($attr->{$item}) {
                   3432: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3433: 			last;
                   3434: 		    }
                   3435: 		}
1.1164    raeburn  3436:                 if (lc($tagname) eq 'embed') {
                   3437:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3438:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3439:                                              $attr->{'src'});
                   3440:                     }
                   3441:                 }
1.640     albertel 3442: 	    }
1.1164    raeburn  3443:             if ($t->[4] =~ m{/>$}) {
                   3444:                 pop(@state);  
                   3445:             }
1.640     albertel 3446: 	} elsif ($t->[0] eq 'E') {
                   3447: 	    my ($tagname) = ($t->[1]);
                   3448: 	    if ($javafiles{'codebase'} ne '') {
                   3449: 		$javafiles{'codebase'} .= '/';
                   3450: 	    }  
                   3451: 	    if (lc($tagname) eq 'applet' ||
                   3452: 		lc($tagname) eq 'object' ||
                   3453: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3454: 		) {
                   3455: 		foreach my $item (keys(%javafiles)) {
                   3456: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3457: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3458: 			&add_filetype($allfiles,$file,$item);
                   3459: 		    }
                   3460: 		}
                   3461: 	    } 
                   3462: 	    pop @state;
                   3463: 	}
                   3464:     }
1.1164    raeburn  3465:     foreach my $id (sort(keys(%flashvars))) {
                   3466:         if ($shockwave{$id} ne '') {
                   3467:             my @pairs = split(/\&/,$flashvars{$id});
                   3468:             foreach my $pair (@pairs) {
                   3469:                 my ($key,$value) = split(/\=/,$pair);
                   3470:                 if ($key eq 'thumb') {
                   3471:                     &add_filetype($allfiles,$value,$key);
                   3472:                 } elsif ($key eq 'content') {
                   3473:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3474:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3475:                     if ($ext ne '') {
                   3476:                         &add_filetype($allfiles,$path.$value,$ext);
                   3477:                     }
                   3478:                 }
                   3479:             }
                   3480:         }
                   3481:     }
1.637     raeburn  3482:     return 'ok';
                   3483: }
                   3484: 
1.639     albertel 3485: sub add_filetype {
                   3486:     my ($allfiles,$file,$type)=@_;
                   3487:     if (exists($allfiles->{$file})) {
                   3488: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3489: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3490: 	}
                   3491:     } else {
                   3492: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3493:     }
                   3494: }
                   3495: 
1.1164    raeburn  3496: sub embedded_dependency {
                   3497:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3498:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3499:         if (($identifier ne '') &&
                   3500:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3501:             ($pathfrom ne '')) {
                   3502:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3503:             foreach my $dep (@{$related->{$identifier}}) {
                   3504:                 &add_filetype($allfiles,$path.$dep,'object');
                   3505:             }
                   3506:         }
                   3507:     }
                   3508:     return;
                   3509: }
                   3510: 
1.493     albertel 3511: sub removeuploadedurl {
1.984     neumanie 3512:     my ($url)=@_;	
                   3513:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3514:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3515: }
                   3516: 
                   3517: sub removeuserfile {
                   3518:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3519:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3520:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3521:     if ($result eq 'ok') {	
1.798     raeburn  3522:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3523:             my $metafile = $fname.'.meta';
                   3524:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3525: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3526:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3527:             my $sqlresult = 
1.823     albertel 3528:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3529:                                         'portfolio_metadata',$group,
                   3530:                                         'delete');
1.798     raeburn  3531:         }
                   3532:     }
                   3533:     return $result;
1.257     www      3534: }
1.15      www      3535: 
1.530     albertel 3536: sub mkdiruserfile {
                   3537:     my ($docuname,$docudom,$dir)=@_;
                   3538:     my $home=&homeserver($docuname,$docudom);
                   3539:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3540: }
                   3541: 
1.531     albertel 3542: sub renameuserfile {
                   3543:     my ($docuname,$docudom,$old,$new)=@_;
                   3544:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3545:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3546:                         &escape("$old").':'.&escape("$new"),$home);
                   3547:     if ($result eq 'ok') {
                   3548:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3549:             my $oldmeta = $old.'.meta';
                   3550:             my $newmeta = $new.'.meta';
                   3551:             my $metaresult = 
                   3552:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3553: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3554:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3555:             my $sqlresult = 
1.823     albertel 3556:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3557:                                         'portfolio_metadata',$group,
                   3558:                                         'delete');
1.798     raeburn  3559:         }
                   3560:     }
                   3561:     return $result;
1.531     albertel 3562: }
                   3563: 
1.14      www      3564: # ------------------------------------------------------------------------- Log
                   3565: 
                   3566: sub log {
                   3567:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3568:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3569: }
                   3570: 
                   3571: # ------------------------------------------------------------------ Course Log
1.352     www      3572: #
                   3573: # This routine flushes several buffers of non-mission-critical nature
                   3574: #
1.157     www      3575: 
                   3576: sub flushcourselogs {
1.352     www      3577:     &logthis('Flushing log buffers');
                   3578: #
                   3579: # course logs
                   3580: # This is a log of all transactions in a course, which can be used
                   3581: # for data mining purposes
                   3582: #
                   3583: # It also collects the courseid database, which lists last transaction
                   3584: # times and course titles for all courseids
                   3585: #
                   3586:     my %courseidbuffer=();
1.921     raeburn  3587:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3588:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3589: 		          &escape($courselogs{$crsid}),
                   3590: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3591: 	    delete $courselogs{$crsid};
                   3592:         } else {
                   3593:             &logthis('Failed to flush log buffer for '.$crsid);
                   3594:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3595:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3596:                         " exceeded maximum size, deleting.</font>");
                   3597:                delete $courselogs{$crsid};
                   3598:             }
1.352     www      3599:         }
1.920     raeburn  3600:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3601:             'description' => $coursedescrbuf{$crsid},
                   3602:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3603:             'type'        => $coursetypebuf{$crsid},
                   3604:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3605:         };
1.191     harris41 3606:     }
1.352     www      3607: #
                   3608: # Write course id database (reverse lookup) to homeserver of courses 
                   3609: # Is used in pickcourse
                   3610: #
1.840     albertel 3611:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3612:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3613:                                     $courseidbuffer{$crs_home},
                   3614:                                     $crs_home,'timeonly');
1.352     www      3615:     }
                   3616: #
                   3617: # File accesses
                   3618: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3619: #
1.449     matthew  3620:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3621:         if ($entry =~ /___count$/) {
                   3622:             my ($dom,$name);
1.807     albertel 3623:             ($dom,$name,undef)=
1.811     albertel 3624: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3625:             if (! defined($dom) || $dom eq '' || 
                   3626:                 ! defined($name) || $name eq '') {
1.620     albertel 3627:                 my $cid = $env{'request.course.id'};
                   3628:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3629:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3630:             }
1.450     matthew  3631:             my $value = $accesshash{$entry};
                   3632:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3633:             my %temphash=($url => $value);
1.449     matthew  3634:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3635:             if ($result eq 'ok') {
                   3636:                 delete $accesshash{$entry};
                   3637:             }
                   3638:         } else {
1.811     albertel 3639:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3640:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3641:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3642:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3643:                 delete $accesshash{$entry};
                   3644:             }
1.185     www      3645:         }
1.191     harris41 3646:     }
1.352     www      3647: #
                   3648: # Roles
                   3649: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3650: #
1.800     albertel 3651:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3652:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3653: 	    split(/\:/,$entry);
                   3654:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3655:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3656:                 $rudom,$runame) eq 'ok') {
                   3657: 	    delete $userrolehash{$entry};
                   3658:         }
                   3659:     }
1.662     raeburn  3660: #
                   3661: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3662: #
                   3663:     my %domrolebuffer = ();
1.1000    raeburn  3664:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3665:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3666:         if ($domrolebuffer{$rudom}) {
                   3667:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3668:                       '='.&escape($domainrolehash{$entry});
                   3669:         } else {
                   3670:             $domrolebuffer{$rudom}.=&escape($entry).
                   3671:                       '='.&escape($domainrolehash{$entry});
                   3672:         }
                   3673:         delete $domainrolehash{$entry};
                   3674:     }
                   3675:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3676: 	my %servers = &get_servers($dom,'library');
                   3677: 	foreach my $tryserver (keys(%servers)) {
                   3678: 	    unless (&reply('domroleput:'.$dom.':'.
                   3679: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3680: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3681: 	    }
1.662     raeburn  3682:         }
                   3683:     }
1.186     www      3684:     $dumpcount++;
1.157     www      3685: }
                   3686: 
                   3687: sub courselog {
                   3688:     my $what=shift;
1.158     www      3689:     $what=time.':'.$what;
1.620     albertel 3690:     unless ($env{'request.course.id'}) { return ''; }
                   3691:     $coursedombuf{$env{'request.course.id'}}=
                   3692:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3693:     $coursenumbuf{$env{'request.course.id'}}=
                   3694:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3695:     $coursehombuf{$env{'request.course.id'}}=
                   3696:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3697:     $coursedescrbuf{$env{'request.course.id'}}=
                   3698:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3699:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3700:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3701:     $courseownerbuf{$env{'request.course.id'}}=
                   3702:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3703:     $coursetypebuf{$env{'request.course.id'}}=
                   3704:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3705:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3706: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3707:     } else {
1.620     albertel 3708: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3709:     }
1.620     albertel 3710:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3711: 	&flushcourselogs();
                   3712:     }
1.158     www      3713: }
                   3714: 
                   3715: sub courseacclog {
                   3716:     my $fnsymb=shift;
1.620     albertel 3717:     unless ($env{'request.course.id'}) { return ''; }
                   3718:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3719:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3720:         $what.=':POST';
1.583     matthew  3721:         # FIXME: Probably ought to escape things....
1.800     albertel 3722: 	foreach my $key (keys(%env)) {
                   3723:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3724:                 my $formitem = $1;
                   3725:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3726:                     $what.=':'.$formitem.'='.$env{$key};
                   3727:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3728:                     $what.=':'.$formitem.'='.$env{$key};
                   3729:                 }
1.158     www      3730:             }
1.191     harris41 3731:         }
1.583     matthew  3732:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3733:         # FIXME: We should not be depending on a form parameter that someone
                   3734:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3735:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3736:             $what.= ':POST';
                   3737:             # FIXME: Probably ought to escape things....
                   3738:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3739:                                  'crsdiscuss') {
1.620     albertel 3740:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3741:             }
                   3742:         }
1.158     www      3743:     }
                   3744:     &courselog($what);
1.149     www      3745: }
                   3746: 
1.185     www      3747: sub countacc {
                   3748:     my $url=&declutter(shift);
1.458     matthew  3749:     return if (! defined($url) || $url eq '');
1.620     albertel 3750:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3751: #
                   3752: # Mark that this url was used in this course
                   3753: #
1.620     albertel 3754:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3755: #
                   3756: # Increase the access count for this resource in this child process
                   3757: #
1.281     www      3758:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3759:     $accesshash{$key}++;
1.185     www      3760: }
1.349     www      3761: 
1.361     www      3762: sub linklog {
                   3763:     my ($from,$to)=@_;
                   3764:     $from=&declutter($from);
                   3765:     $to=&declutter($to);
                   3766:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3767:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3768: }
1.1160    www      3769: 
                   3770: sub statslog {
                   3771:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   3772:     if ($users<2) { return; }
                   3773:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   3774:             'course'       => $env{'request.course.id'},
                   3775:             'sections'     => '"all"',
                   3776:             'num_students' => $users,
                   3777:             'part'         => $part,
                   3778:             'symb'         => $symb,
                   3779:             'mean_tries'   => $av_attempts,
                   3780:             'deg_of_diff'  => $degdiff});
                   3781:     foreach my $key (keys(%dynstore)) {
                   3782:         $accesshash{$key}=$dynstore{$key};
                   3783:     }
                   3784: }
1.361     www      3785:   
1.349     www      3786: sub userrolelog {
                   3787:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 3788:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      3789:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3790:        $userrolehash
                   3791:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3792:                     =$tend.':'.$tstart;
1.662     raeburn  3793:     }
1.1169    droeschl 3794:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 3795:        $userrolehash
                   3796:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3797:                     =$tend.':'.$tstart;
                   3798:     }
1.1169    droeschl 3799:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  3800:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3801:        $domainrolehash
                   3802:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3803:                     = $tend.':'.$tstart;
                   3804:     }
1.351     www      3805: }
                   3806: 
1.957     raeburn  3807: sub courserolelog {
                   3808:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  3809:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3810:         my $cdom = $1;
                   3811:         my $cnum = $2;
                   3812:         my $sec = $3;
                   3813:         my $namespace = 'rolelog';
                   3814:         my %storehash = (
                   3815:                            role    => $trole,
                   3816:                            start   => $tstart,
                   3817:                            end     => $tend,
                   3818:                            selfenroll => $selfenroll,
                   3819:                            context    => $context,
                   3820:                         );
                   3821:         if ($trole eq 'gr') {
                   3822:             $namespace = 'groupslog';
                   3823:             $storehash{'group'} = $sec;
                   3824:         } else {
                   3825:             $storehash{'section'} = $sec;
                   3826:         }
                   3827:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   3828:                    $domain,$cnum,$cdom);
                   3829:         if (($trole ne 'st') || ($sec ne '')) {
                   3830:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  3831:         }
                   3832:     }
                   3833:     return;
                   3834: }
                   3835: 
1.1172.2.9  raeburn  3836: sub domainrolelog {
                   3837:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3838:     if ($area =~ m{^/($match_domain)/$}) {
                   3839:         my $cdom = $1;
                   3840:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   3841:         my $namespace = 'rolelog';
                   3842:         my %storehash = (
                   3843:                            role    => $trole,
                   3844:                            start   => $tstart,
                   3845:                            end     => $tend,
                   3846:                            context => $context,
                   3847:                         );
                   3848:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   3849:                    $domain,$domconfiguser,$cdom);
                   3850:     }
                   3851:     return;
                   3852: 
                   3853: }
                   3854: 
                   3855: sub coauthorrolelog {
                   3856:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3857:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   3858:         my $audom = $1;
                   3859:         my $auname = $2;
                   3860:         my $namespace = 'rolelog';
                   3861:         my %storehash = (
                   3862:                            role    => $trole,
                   3863:                            start   => $tstart,
                   3864:                            end     => $tend,
                   3865:                            context => $context,
                   3866:                         );
                   3867:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   3868:                    $domain,$auname,$audom);
                   3869:     }
                   3870:     return;
                   3871: }
                   3872: 
1.351     www      3873: sub get_course_adv_roles {
1.948     raeburn  3874:     my ($cid,$codes) = @_;
1.620     albertel 3875:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3876:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3877:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3878:     my %nothide=();
1.800     albertel 3879:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3880:         if ($user !~ /:/) {
                   3881: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3882:         } else {
                   3883:             $nothide{$user}=1;
                   3884:         }
1.470     www      3885:     }
1.351     www      3886:     my %returnhash=();
                   3887:     my %dumphash=
                   3888:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3889:     my $now=time;
1.997     raeburn  3890:     my %privileged;
1.1000    raeburn  3891:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3892: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3893:         if (($tstart) && ($tstart<0)) { next; }
                   3894:         if (($tend) && ($tend<$now)) { next; }
                   3895:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3896:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3897: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3898:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3899:             my %dompersonnel =
1.998     raeburn  3900:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3901:             $privileged{$domain} = {};
                   3902:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3903:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3904:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3905:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3906:                         $privileged{$udom}{$uname} = 1;
                   3907:                     }
                   3908:                 }
                   3909:             }
                   3910:         }
                   3911:         if ((exists($privileged{$domain}{$username})) && 
                   3912:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3913: 	if ($role eq 'cr') { next; }
1.948     raeburn  3914:         if ($codes) {
                   3915:             if ($section) { $role .= ':'.$section; }
                   3916:             if ($returnhash{$role}) {
                   3917:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3918:             } else {
                   3919:                 $returnhash{$role}=$username.':'.$domain;
                   3920:             }
1.351     www      3921:         } else {
1.988     raeburn  3922:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3923:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3924:             if ($returnhash{$key}) {
                   3925: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3926:             } else {
                   3927:                 $returnhash{$key}=$username.':'.$domain;
                   3928:             }
1.351     www      3929:         }
1.948     raeburn  3930:     }
1.400     www      3931:     return %returnhash;
                   3932: }
                   3933: 
                   3934: sub get_my_roles {
1.937     raeburn  3935:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3936:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3937:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3938:     my (%dumphash,%nothide);
1.1086    raeburn  3939:     if ($context eq 'userroles') {
1.1166    raeburn  3940:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  3941:     } else {
                   3942:         %dumphash=
1.400     www      3943:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3944:         if ($hidepriv) {
                   3945:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3946:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3947:                 if ($user !~ /:/) {
                   3948:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3949:                 } else {
                   3950:                     $nothide{$user} = 1;
                   3951:                 }
                   3952:             }
                   3953:         }
1.858     raeburn  3954:     }
1.400     www      3955:     my %returnhash=();
                   3956:     my $now=time;
1.999     raeburn  3957:     my %privileged;
1.800     albertel 3958:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3959:         my ($role,$tend,$tstart);
                   3960:         if ($context eq 'userroles') {
1.1149    raeburn  3961:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  3962: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3963:         } else {
                   3964:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3965:         }
1.400     www      3966:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3967:         my $status = 'active';
1.939     raeburn  3968:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3969:             $status = 'previous';
                   3970:         } 
                   3971:         if (($tstart) && ($now<$tstart)) {
                   3972:             $status = 'future';
                   3973:         }
                   3974:         if (ref($types) eq 'ARRAY') {
                   3975:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3976:                 next;
                   3977:             } 
                   3978:         } else {
                   3979:             if ($status ne 'active') {
                   3980:                 next;
                   3981:             }
                   3982:         }
1.867     raeburn  3983:         my ($rolecode,$username,$domain,$section,$area);
                   3984:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  3985:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  3986:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3987:         } else {
                   3988:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3989:         }
1.832     raeburn  3990:         if (ref($roledoms) eq 'ARRAY') {
                   3991:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3992:                 next;
                   3993:             }
                   3994:         }
                   3995:         if (ref($roles) eq 'ARRAY') {
                   3996:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3997:                 if ($role =~ /^cr\//) {
                   3998:                     if (!grep(/^cr$/,@{$roles})) {
                   3999:                         next;
                   4000:                     }
1.1104    raeburn  4001:                 } elsif ($role =~ /^gr\//) {
                   4002:                     if (!grep(/^gr$/,@{$roles})) {
                   4003:                         next;
                   4004:                     }
1.922     raeburn  4005:                 } else {
                   4006:                     next;
                   4007:                 }
1.832     raeburn  4008:             }
1.867     raeburn  4009:         }
1.937     raeburn  4010:         if ($hidepriv) {
1.999     raeburn  4011:             if ($context eq 'userroles') {
                   4012:                 if ((&privileged($username,$domain)) &&
                   4013:                     (!$nothide{$username.':'.$domain})) {
                   4014:                     next;
                   4015:                 }
                   4016:             } else {
                   4017:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   4018:                     my %dompersonnel =
                   4019:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   4020:                     $privileged{$domain} = {};
                   4021:                     if (keys(%dompersonnel)) {
                   4022:                         foreach my $server (keys(%dompersonnel)) {
                   4023:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   4024:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   4025:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   4026:                                     $privileged{$udom}{$uname} = $trole;
                   4027:                                 }
                   4028:                             }
                   4029:                         }
                   4030:                     }
                   4031:                 }
                   4032:                 if (exists($privileged{$domain}{$username})) {
                   4033:                     if (!$nothide{$username.':'.$domain}) {
                   4034:                         next;
                   4035:                     }
                   4036:                 }
1.937     raeburn  4037:             }
                   4038:         }
1.933     raeburn  4039:         if ($withsec) {
                   4040:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4041:                 $tstart.':'.$tend;
                   4042:         } else {
                   4043:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4044:         }
1.832     raeburn  4045:     }
1.373     www      4046:     return %returnhash;
1.399     www      4047: }
                   4048: 
                   4049: # ----------------------------------------------------- Frontpage Announcements
                   4050: #
                   4051: #
                   4052: 
                   4053: sub postannounce {
                   4054:     my ($server,$text)=@_;
1.844     albertel 4055:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4056:     unless ($text=~/\w/) { $text=''; }
                   4057:     return &reply('setannounce:'.&escape($text),$server);
                   4058: }
                   4059: 
                   4060: sub getannounce {
1.448     albertel 4061: 
                   4062:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4063: 	my $announcement='';
1.800     albertel 4064: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4065: 	close($fh);
1.399     www      4066: 	if ($announcement=~/\w/) { 
                   4067: 	    return 
                   4068:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4069:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4070: 	} else {
                   4071: 	    return '';
                   4072: 	}
                   4073:     } else {
                   4074: 	return '';
                   4075:     }
1.351     www      4076: }
1.353     www      4077: 
                   4078: # ---------------------------------------------------------- Course ID routines
                   4079: # Deal with domain's nohist_courseid.db files
                   4080: #
                   4081: 
                   4082: sub courseidput {
1.921     raeburn  4083:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4084:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4085:     my $outcome;
                   4086:     if ($caller eq 'timeonly') {
                   4087:         my $cids = '';
                   4088:         foreach my $item (keys(%$storehash)) {
                   4089:             $cids.=&escape($item).'&';
                   4090:         }
                   4091:         $cids=~s/\&$//;
                   4092:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4093:                           $coursehome);       
                   4094:     } else {
                   4095:         my $items = '';
                   4096:         foreach my $item (keys(%$storehash)) {
                   4097:             $items.= &escape($item).'='.
                   4098:                      &freeze_escape($$storehash{$item}).'&';
                   4099:         }
                   4100:         $items=~s/\&$//;
                   4101:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4102:                           $coursehome);
1.918     raeburn  4103:     }
                   4104:     if ($outcome eq 'unknown_cmd') {
                   4105:         my $what;
                   4106:         foreach my $cid (keys(%$storehash)) {
                   4107:             $what .= &escape($cid).'=';
1.921     raeburn  4108:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4109:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4110:             }
                   4111:             $what =~ s/\:$/&/;
                   4112:         }
                   4113:         $what =~ s/\&$//;  
                   4114:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4115:     } else {
                   4116:         return $outcome;
                   4117:     }
1.353     www      4118: }
                   4119: 
                   4120: sub courseiddump {
1.921     raeburn  4121:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4122:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4123:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  4124:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  4125:     my $as_hash = 1;
                   4126:     my %returnhash;
                   4127:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4128:     my %libserv = &all_library();
                   4129:     foreach my $tryserver (keys(%libserv)) {
                   4130:         if ( (  $hostidflag == 1 
                   4131: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4132: 	     || (!defined($hostidflag)) ) {
                   4133: 
1.918     raeburn  4134: 	    if (($domfilter eq '') ||
                   4135: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22! raeburn  4136:                 my $rep;
        !          4137:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
        !          4138:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
        !          4139:                         join(":", (&host_domain($tryserver), $sincefilter,
        !          4140:                                 &escape($descfilter), &escape($instcodefilter),
        !          4141:                                 &escape($ownerfilter), &escape($coursefilter),
        !          4142:                                 &escape($typefilter), &escape($regexp_ok),
        !          4143:                                 $as_hash, &escape($selfenrollonly),
        !          4144:                                 &escape($catfilter), $showhidden, $caller,
        !          4145:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
        !          4146:                                 &escape($createdbefore), &escape($createdafter),
        !          4147:                                 &escape($creationcontext), $domcloner)));
        !          4148:                 } else {
        !          4149:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
        !          4150:                              $sincefilter.':'.&escape($descfilter).':'.
        !          4151:                              &escape($instcodefilter).':'.&escape($ownerfilter).
        !          4152:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
        !          4153:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
        !          4154:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
        !          4155:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
        !          4156:                              &escape($cc_clone).':'.$cloneonly.':'.
        !          4157:                              &escape($createdbefore).':'.&escape($createdafter).':'.
        !          4158:                              &escape($creationcontext).':'.$domcloner,
        !          4159:                              $tryserver);
        !          4160:                 }
        !          4161: 
1.918     raeburn  4162:                 my @pairs=split(/\&/,$rep);
                   4163:                 foreach my $item (@pairs) {
                   4164:                     my ($key,$value)=split(/\=/,$item,2);
                   4165:                     $key = &unescape($key);
                   4166:                     next if ($key =~ /^error: 2 /);
                   4167:                     my $result = &thaw_unescape($value);
                   4168:                     if (ref($result) eq 'HASH') {
                   4169:                         $returnhash{$key}=$result;
                   4170:                     } else {
1.921     raeburn  4171:                         my @responses = split(/:/,$value);
                   4172:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4173:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4174:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4175:                         }
1.1008    raeburn  4176:                     }
1.353     www      4177:                 }
                   4178:             }
                   4179:         }
                   4180:     }
                   4181:     return %returnhash;
                   4182: }
                   4183: 
1.1055    raeburn  4184: sub courselastaccess {
                   4185:     my ($cdom,$cnum,$hostidref) = @_;
                   4186:     my %returnhash;
                   4187:     if ($cdom && $cnum) {
                   4188:         my $chome = &homeserver($cnum,$cdom);
                   4189:         if ($chome ne 'no_host') {
                   4190:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4191:             &extract_lastaccess(\%returnhash,$rep);
                   4192:         }
                   4193:     } else {
                   4194:         if (!$cdom) { $cdom=''; }
                   4195:         my %libserv = &all_library();
                   4196:         foreach my $tryserver (keys(%libserv)) {
                   4197:             if (ref($hostidref) eq 'ARRAY') {
                   4198:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4199:             } 
                   4200:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4201:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4202:                 &extract_lastaccess(\%returnhash,$rep);
                   4203:             }
                   4204:         }
                   4205:     }
                   4206:     return %returnhash;
                   4207: }
                   4208: 
                   4209: sub extract_lastaccess {
                   4210:     my ($returnhash,$rep) = @_;
                   4211:     if (ref($returnhash) eq 'HASH') {
                   4212:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4213:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4214:                  $rep eq '') {
                   4215:             my @pairs=split(/\&/,$rep);
                   4216:             foreach my $item (@pairs) {
                   4217:                 my ($key,$value)=split(/\=/,$item,2);
                   4218:                 $key = &unescape($key);
                   4219:                 next if ($key =~ /^error: 2 /);
                   4220:                 $returnhash->{$key} = &thaw_unescape($value);
                   4221:             }
                   4222:         }
                   4223:     }
                   4224:     return;
                   4225: }
                   4226: 
1.658     raeburn  4227: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4228: 
                   4229: sub dcmailput {
1.685     raeburn  4230:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4231:     my $status = &Apache::lonnet::critical(
1.740     www      4232:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4233:        &escape($message),$server);
1.662     raeburn  4234:     return $status;
                   4235: }
                   4236: 
1.658     raeburn  4237: sub dcmaildump {
                   4238:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4239:     my %returnhash=();
1.846     albertel 4240: 
                   4241:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4242:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4243:                                                          &escape($enddate).':';
                   4244: 	my @esc_senders=map { &escape($_)} @$senders;
                   4245: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4246: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4247:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4248:             if (($key) && ($value)) {
                   4249:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4250:             }
                   4251:         }
                   4252:     }
                   4253:     return %returnhash;
                   4254: }
1.662     raeburn  4255: # ---------------------------------------------------------- Domain roles
                   4256: 
                   4257: sub get_domain_roles {
                   4258:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4259:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4260:         $startdate = '.';
                   4261:     }
1.1018    raeburn  4262:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4263:         $enddate = '.';
                   4264:     }
1.922     raeburn  4265:     my $rolelist;
                   4266:     if (ref($roles) eq 'ARRAY') {
                   4267:         $rolelist = join(':',@{$roles});
                   4268:     }
1.662     raeburn  4269:     my %personnel = ();
1.841     albertel 4270: 
                   4271:     my %servers = &get_servers($dom,'library');
                   4272:     foreach my $tryserver (keys(%servers)) {
                   4273: 	%{$personnel{$tryserver}}=();
                   4274: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4275: 					    &escape($startdate).':'.
                   4276: 					    &escape($enddate).':'.
                   4277: 					    &escape($rolelist), $tryserver))) {
                   4278: 	    my ($key,$value) = split(/\=/,$line,2);
                   4279: 	    if (($key) && ($value)) {
                   4280: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4281: 	    }
                   4282: 	}
1.662     raeburn  4283:     }
                   4284:     return %personnel;
                   4285: }
1.658     raeburn  4286: 
1.1057    www      4287: # ----------------------------------------------------------- Interval timing 
1.149     www      4288: 
1.1153    www      4289: {
                   4290: # Caches needed for speedup of navmaps
                   4291: # We don't want to cache this for very long at all (5 seconds at most)
                   4292: # 
                   4293: # The user for whom we cache
                   4294: my $cachedkey='';
                   4295: # The cached times for this user
                   4296: my %cachedtimes=();
                   4297: # When this was last done
                   4298: my $cachedtime=();
                   4299: 
                   4300: sub load_all_first_access {
1.1154    raeburn  4301:     my ($uname,$udom)=@_;
1.1156    www      4302:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  4303:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4304:         return;
                   4305:     }
                   4306:     $cachedtime=time;
                   4307:     $cachedkey=$uname.':'.$udom;
                   4308:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4309: }
                   4310: 
1.504     albertel 4311: sub get_first_access {
1.1162    raeburn  4312:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4313:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4314:     if ($argsymb) { $symb=$argsymb; }
                   4315:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4316:     if ($argmap) { $map = $argmap; }
1.926     albertel 4317:     if ($type eq 'course') {
                   4318: 	$res='course';
                   4319:     } elsif ($type eq 'map') {
1.588     albertel 4320: 	$res=&symbread($map);
                   4321:     } else {
                   4322: 	$res=$symb;
                   4323:     }
1.1153    www      4324:     &load_all_first_access($uname,$udom);
                   4325:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4326: }
                   4327: 
                   4328: sub set_first_access {
1.1162    raeburn  4329:     my ($type,$interval)=@_;
1.790     albertel 4330:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4331:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4332:     if ($type eq 'course') {
                   4333: 	$res='course';
                   4334:     } elsif ($type eq 'map') {
1.588     albertel 4335: 	$res=&symbread($map);
                   4336:     } else {
                   4337: 	$res=$symb;
                   4338:     }
1.1153    www      4339:     $cachedkey='';
1.1162    raeburn  4340:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4341:     if (!$firstaccess) {
1.1162    raeburn  4342:         my $start = time;
                   4343: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4344:                           $udom,$uname);
                   4345:         if ($putres eq 'ok') {
                   4346:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4347:                  $udom,$uname); 
                   4348:             &appenv(
                   4349:                      {
                   4350:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4351:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4352:                      }
                   4353:                   );
                   4354:         }
                   4355:         return $putres;
1.505     albertel 4356:     }
                   4357:     return 'already_set';
1.504     albertel 4358: }
1.1153    www      4359: }
1.110     www      4360: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4361: 
                   4362: sub expirespread {
                   4363:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4364:     my $cid=$env{'request.course.id'}; 
1.110     www      4365:     if ($cid) {
                   4366:        my $now=time;
                   4367:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4368:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4369:                             $env{'course.'.$cid.'.num'}.
1.110     www      4370: 	        	    ':nohist_expirationdates:'.
                   4371:                             &escape($key).'='.$now,
1.620     albertel 4372:                             $env{'course.'.$cid.'.home'})
1.110     www      4373:     }
                   4374:     return 'ok';
1.14      www      4375: }
                   4376: 
1.109     www      4377: # ----------------------------------------------------- Devalidate Spreadsheets
                   4378: 
                   4379: sub devalidate {
1.325     www      4380:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4381:     my $cid=$env{'request.course.id'}; 
1.109     www      4382:     if ($cid) {
1.391     matthew  4383:         # delete the stored spreadsheets for
                   4384:         # - the student level sheet of this user in course's homespace
                   4385:         # - the assessment level sheet for this resource 
                   4386:         #   for this user in user's homespace
1.553     albertel 4387: 	# - current conditional state info
1.325     www      4388: 	my $key=$uname.':'.$udom.':';
1.109     www      4389:         my $status=
1.299     matthew  4390: 	    &del('nohist_calculatedsheets',
1.391     matthew  4391: 		 [$key.'studentcalc:'],
1.620     albertel 4392: 		 $env{'course.'.$cid.'.domain'},
                   4393: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4394: 		.' '.
                   4395: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4396: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4397:         unless ($status eq 'ok ok') {
                   4398:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4399:                     $uname.' at '.$udom.' for '.
1.109     www      4400: 		    $symb.': '.$status);
1.133     albertel 4401:         }
1.553     albertel 4402: 	&delenv('user.state.'.$cid);
1.109     www      4403:     }
                   4404: }
                   4405: 
1.265     albertel 4406: sub get_scalar {
                   4407:     my ($string,$end) = @_;
                   4408:     my $value;
                   4409:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4410: 	$value = $1;
                   4411:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4412: 	$value = $1;
                   4413:     }
                   4414:     return &unescape($value);
                   4415: }
                   4416: 
                   4417: sub array2str {
                   4418:   my (@array) = @_;
                   4419:   my $result=&arrayref2str(\@array);
                   4420:   $result=~s/^__ARRAY_REF__//;
                   4421:   $result=~s/__END_ARRAY_REF__$//;
                   4422:   return $result;
                   4423: }
                   4424: 
1.204     albertel 4425: sub arrayref2str {
                   4426:   my ($arrayref) = @_;
1.265     albertel 4427:   my $result='__ARRAY_REF__';
1.204     albertel 4428:   foreach my $elem (@$arrayref) {
1.265     albertel 4429:     if(ref($elem) eq 'ARRAY') {
                   4430:       $result.=&arrayref2str($elem).'&';
                   4431:     } elsif(ref($elem) eq 'HASH') {
                   4432:       $result.=&hashref2str($elem).'&';
                   4433:     } elsif(ref($elem)) {
                   4434:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4435:     } else {
                   4436:       $result.=&escape($elem).'&';
                   4437:     }
                   4438:   }
                   4439:   $result=~s/\&$//;
1.265     albertel 4440:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4441:   return $result;
                   4442: }
                   4443: 
1.168     albertel 4444: sub hash2str {
1.204     albertel 4445:   my (%hash) = @_;
                   4446:   my $result=&hashref2str(\%hash);
1.265     albertel 4447:   $result=~s/^__HASH_REF__//;
                   4448:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4449:   return $result;
                   4450: }
                   4451: 
                   4452: sub hashref2str {
                   4453:   my ($hashref)=@_;
1.265     albertel 4454:   my $result='__HASH_REF__';
1.800     albertel 4455:   foreach my $key (sort(keys(%$hashref))) {
                   4456:     if (ref($key) eq 'ARRAY') {
                   4457:       $result.=&arrayref2str($key).'=';
                   4458:     } elsif (ref($key) eq 'HASH') {
                   4459:       $result.=&hashref2str($key).'=';
                   4460:     } elsif (ref($key)) {
1.265     albertel 4461:       $result.='=';
1.800     albertel 4462:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4463:     } else {
1.1132    raeburn  4464: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4465:     }
                   4466: 
1.800     albertel 4467:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4468:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4469:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4470:       $result.=&hashref2str($hashref->{$key}).'&';
                   4471:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4472:        $result.='&';
1.800     albertel 4473:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4474:     } else {
1.800     albertel 4475:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4476:     }
                   4477:   }
1.168     albertel 4478:   $result=~s/\&$//;
1.265     albertel 4479:   $result .= '__END_HASH_REF__';
1.168     albertel 4480:   return $result;
                   4481: }
                   4482: 
                   4483: sub str2hash {
1.265     albertel 4484:     my ($string)=@_;
                   4485:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4486:     return %$hash;
                   4487: }
                   4488: 
                   4489: sub str2hashref {
1.168     albertel 4490:   my ($string) = @_;
1.265     albertel 4491: 
                   4492:   my %hash;
                   4493: 
                   4494:   if($string !~ /^__HASH_REF__/) {
                   4495:       if (! ($string eq '' || !defined($string))) {
                   4496: 	  $hash{'error'}='Not hash reference';
                   4497:       }
                   4498:       return (\%hash, $string);
                   4499:   }
                   4500: 
                   4501:   $string =~ s/^__HASH_REF__//;
                   4502: 
                   4503:   while($string !~ /^__END_HASH_REF__/) {
                   4504:       #key
                   4505:       my $key='';
                   4506:       if($string =~ /^__HASH_REF__/) {
                   4507:           ($key, $string)=&str2hashref($string);
                   4508:           if(defined($key->{'error'})) {
                   4509:               $hash{'error'}='Bad data';
                   4510:               return (\%hash, $string);
                   4511:           }
                   4512:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4513:           ($key, $string)=&str2arrayref($string);
                   4514:           if($key->[0] eq 'Array reference error') {
                   4515:               $hash{'error'}='Bad data';
                   4516:               return (\%hash, $string);
                   4517:           }
                   4518:       } else {
                   4519:           $string =~ s/^(.*?)=//;
1.267     albertel 4520: 	  $key=&unescape($1);
1.265     albertel 4521:       }
                   4522:       $string =~ s/^=//;
                   4523: 
                   4524:       #value
                   4525:       my $value='';
                   4526:       if($string =~ /^__HASH_REF__/) {
                   4527:           ($value, $string)=&str2hashref($string);
                   4528:           if(defined($value->{'error'})) {
                   4529:               $hash{'error'}='Bad data';
                   4530:               return (\%hash, $string);
                   4531:           }
                   4532:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4533:           ($value, $string)=&str2arrayref($string);
                   4534:           if($value->[0] eq 'Array reference error') {
                   4535:               $hash{'error'}='Bad data';
                   4536:               return (\%hash, $string);
                   4537:           }
                   4538:       } else {
                   4539: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4540:       }
                   4541:       $string =~ s/^&//;
                   4542: 
                   4543:       $hash{$key}=$value;
1.204     albertel 4544:   }
1.265     albertel 4545: 
                   4546:   $string =~ s/^__END_HASH_REF__//;
                   4547: 
                   4548:   return (\%hash, $string);
1.204     albertel 4549: }
                   4550: 
                   4551: sub str2array {
1.265     albertel 4552:     my ($string)=@_;
                   4553:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4554:     return @$array;
                   4555: }
                   4556: 
                   4557: sub str2arrayref {
1.204     albertel 4558:   my ($string) = @_;
1.265     albertel 4559:   my @array;
                   4560: 
                   4561:   if($string !~ /^__ARRAY_REF__/) {
                   4562:       if (! ($string eq '' || !defined($string))) {
                   4563: 	  $array[0]='Array reference error';
                   4564:       }
                   4565:       return (\@array, $string);
                   4566:   }
                   4567: 
                   4568:   $string =~ s/^__ARRAY_REF__//;
                   4569: 
                   4570:   while($string !~ /^__END_ARRAY_REF__/) {
                   4571:       my $value='';
                   4572:       if($string =~ /^__HASH_REF__/) {
                   4573:           ($value, $string)=&str2hashref($string);
                   4574:           if(defined($value->{'error'})) {
                   4575:               $array[0] ='Array reference error';
                   4576:               return (\@array, $string);
                   4577:           }
                   4578:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4579:           ($value, $string)=&str2arrayref($string);
                   4580:           if($value->[0] eq 'Array reference error') {
                   4581:               $array[0] ='Array reference error';
                   4582:               return (\@array, $string);
                   4583:           }
                   4584:       } else {
                   4585: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4586:       }
                   4587:       $string =~ s/^&//;
                   4588: 
                   4589:       push(@array, $value);
1.191     harris41 4590:   }
1.265     albertel 4591: 
                   4592:   $string =~ s/^__END_ARRAY_REF__//;
                   4593: 
                   4594:   return (\@array, $string);
1.168     albertel 4595: }
                   4596: 
1.167     albertel 4597: # -------------------------------------------------------------------Temp Store
                   4598: 
1.168     albertel 4599: sub tmpreset {
                   4600:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4601:   if (!$symb) {
                   4602:     $symb=&symbread();
1.620     albertel 4603:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4604:   }
                   4605:   $symb=escape($symb);
                   4606: 
1.620     albertel 4607:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4608:   $namespace=~s/\//\_/g;
                   4609:   $namespace=~s/\W//g;
                   4610: 
1.620     albertel 4611:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4612:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4613:   if ($domain eq 'public' && $stuname eq 'public') {
                   4614:       $stuname=$ENV{'REMOTE_ADDR'};
                   4615:   }
1.1117    foxr     4616:   my $path=LONCAPA::tempdir();
1.168     albertel 4617:   my %hash;
                   4618:   if (tie(%hash,'GDBM_File',
                   4619: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4620: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4621:     foreach my $key (keys(%hash)) {
1.180     albertel 4622:       if ($key=~ /:$symb/) {
1.168     albertel 4623: 	delete($hash{$key});
                   4624:       }
                   4625:     }
                   4626:   }
                   4627: }
                   4628: 
1.167     albertel 4629: sub tmpstore {
1.168     albertel 4630:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4631: 
                   4632:   if (!$symb) {
                   4633:     $symb=&symbread();
1.620     albertel 4634:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4635:   }
                   4636:   $symb=escape($symb);
                   4637: 
                   4638:   if (!$namespace) {
                   4639:     # I don't think we would ever want to store this for a course.
                   4640:     # it seems this will only be used if we don't have a course.
1.620     albertel 4641:     #$namespace=$env{'request.course.id'};
1.168     albertel 4642:     #if (!$namespace) {
1.620     albertel 4643:       $namespace=$env{'request.state'};
1.168     albertel 4644:     #}
                   4645:   }
                   4646:   $namespace=~s/\//\_/g;
                   4647:   $namespace=~s/\W//g;
1.620     albertel 4648:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4649:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4650:   if ($domain eq 'public' && $stuname eq 'public') {
                   4651:       $stuname=$ENV{'REMOTE_ADDR'};
                   4652:   }
1.168     albertel 4653:   my $now=time;
                   4654:   my %hash;
1.1117    foxr     4655:   my $path=LONCAPA::tempdir();
1.168     albertel 4656:   if (tie(%hash,'GDBM_File',
                   4657: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4658: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4659:     $hash{"version:$symb"}++;
                   4660:     my $version=$hash{"version:$symb"};
                   4661:     my $allkeys=''; 
                   4662:     foreach my $key (keys(%$storehash)) {
                   4663:       $allkeys.=$key.':';
1.591     albertel 4664:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4665:     }
                   4666:     $hash{"$version:$symb:timestamp"}=$now;
                   4667:     $allkeys.='timestamp';
                   4668:     $hash{"$version:keys:$symb"}=$allkeys;
                   4669:     if (untie(%hash)) {
                   4670:       return 'ok';
                   4671:     } else {
                   4672:       return "error:$!";
                   4673:     }
                   4674:   } else {
                   4675:     return "error:$!";
                   4676:   }
                   4677: }
1.167     albertel 4678: 
1.168     albertel 4679: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4680: 
1.168     albertel 4681: sub tmprestore {
                   4682:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4683: 
1.168     albertel 4684:   if (!$symb) {
                   4685:     $symb=&symbread();
1.620     albertel 4686:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4687:   }
                   4688:   $symb=escape($symb);
                   4689: 
1.620     albertel 4690:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4691: 
1.620     albertel 4692:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4693:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4694:   if ($domain eq 'public' && $stuname eq 'public') {
                   4695:       $stuname=$ENV{'REMOTE_ADDR'};
                   4696:   }
1.168     albertel 4697:   my %returnhash;
                   4698:   $namespace=~s/\//\_/g;
                   4699:   $namespace=~s/\W//g;
                   4700:   my %hash;
1.1117    foxr     4701:   my $path=LONCAPA::tempdir();
1.168     albertel 4702:   if (tie(%hash,'GDBM_File',
                   4703: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4704: 	  &GDBM_READER(),0640)) {
1.168     albertel 4705:     my $version=$hash{"version:$symb"};
                   4706:     $returnhash{'version'}=$version;
                   4707:     my $scope;
                   4708:     for ($scope=1;$scope<=$version;$scope++) {
                   4709:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4710:       my @keys=split(/:/,$vkeys);
                   4711:       my $key;
                   4712:       $returnhash{"$scope:keys"}=$vkeys;
                   4713:       foreach $key (@keys) {
1.591     albertel 4714: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4715: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4716:       }
                   4717:     }
1.168     albertel 4718:     if (!(untie(%hash))) {
                   4719:       return "error:$!";
                   4720:     }
                   4721:   } else {
                   4722:     return "error:$!";
                   4723:   }
                   4724:   return %returnhash;
1.167     albertel 4725: }
                   4726: 
1.9       www      4727: # ----------------------------------------------------------------------- Store
                   4728: 
                   4729: sub store {
1.124     www      4730:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4731:     my $home='';
                   4732: 
1.168     albertel 4733:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4734: 
1.213     www      4735:     $symb=&symbclean($symb);
1.122     albertel 4736:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4737: 
1.620     albertel 4738:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4739:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4740: 
                   4741:     &devalidate($symb,$stuname,$domain);
1.109     www      4742: 
                   4743:     $symb=escape($symb);
1.187     www      4744:     if (!$namespace) { 
1.620     albertel 4745:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4746:           return ''; 
                   4747:        } 
                   4748:     }
1.620     albertel 4749:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4750: 
                   4751:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4752:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4753: 
1.12      www      4754:     my $namevalue='';
1.800     albertel 4755:     foreach my $key (keys(%$storehash)) {
                   4756:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4757:     }
1.12      www      4758:     $namevalue=~s/\&$//;
1.187     www      4759:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4760:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4761: }
                   4762: 
1.47      www      4763: # -------------------------------------------------------------- Critical Store
                   4764: 
                   4765: sub cstore {
1.124     www      4766:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4767:     my $home='';
                   4768: 
1.168     albertel 4769:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4770: 
1.213     www      4771:     $symb=&symbclean($symb);
1.122     albertel 4772:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4773: 
1.620     albertel 4774:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4775:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4776: 
                   4777:     &devalidate($symb,$stuname,$domain);
1.109     www      4778: 
                   4779:     $symb=escape($symb);
1.187     www      4780:     if (!$namespace) { 
1.620     albertel 4781:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4782:           return ''; 
                   4783:        } 
                   4784:     }
1.620     albertel 4785:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4786: 
                   4787:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4788:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4789: 
1.47      www      4790:     my $namevalue='';
1.800     albertel 4791:     foreach my $key (keys(%$storehash)) {
                   4792:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4793:     }
1.47      www      4794:     $namevalue=~s/\&$//;
1.187     www      4795:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4796:     return critical
                   4797:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4798: }
                   4799: 
1.9       www      4800: # --------------------------------------------------------------------- Restore
                   4801: 
                   4802: sub restore {
1.124     www      4803:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4804:     my $home='';
                   4805: 
1.168     albertel 4806:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4807: 
1.122     albertel 4808:     if (!$symb) {
                   4809:       unless ($symb=escape(&symbread())) { return ''; }
                   4810:     } else {
1.213     www      4811:       $symb=&escape(&symbclean($symb));
1.122     albertel 4812:     }
1.188     www      4813:     if (!$namespace) { 
1.620     albertel 4814:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4815:           return ''; 
                   4816:        } 
                   4817:     }
1.620     albertel 4818:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4819:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4820:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4821:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4822: 
1.12      www      4823:     my %returnhash=();
1.800     albertel 4824:     foreach my $line (split(/\&/,$answer)) {
                   4825: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4826:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4827:     }
1.75      www      4828:     my $version;
                   4829:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4830:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4831:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4832:        }
1.75      www      4833:     }
1.13      www      4834:     return %returnhash;
1.34      www      4835: }
                   4836: 
                   4837: # ---------------------------------------------------------- Course Description
1.1118    foxr     4838: #
                   4839: #  
1.34      www      4840: 
                   4841: sub coursedescription {
1.731     albertel 4842:     my ($courseid,$args)=@_;
1.34      www      4843:     $courseid=~s/^\///;
1.49      www      4844:     $courseid=~s/\_/\//g;
1.34      www      4845:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4846:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4847:     my $normalid=$cdomain.'_'.$cnum;
                   4848:     # need to always cache even if we get errors otherwise we keep 
                   4849:     # trying and trying and trying to get the course description.
                   4850:     my %envhash=();
                   4851:     my %returnhash=();
1.731     albertel 4852:     
                   4853:     my $expiretime=600;
                   4854:     if ($env{'request.course.id'} eq $normalid) {
                   4855: 	$expiretime=120;
                   4856:     }
                   4857: 
                   4858:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4859:     if (!$args->{'freshen_cache'}
                   4860: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4861: 	foreach my $key (keys(%env)) {
                   4862: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4863: 	    my ($setting) = $1;
                   4864: 	    $returnhash{$setting} = $env{$key};
                   4865: 	}
                   4866: 	return %returnhash;
                   4867:     }
                   4868: 
1.1118    foxr     4869:     # get the data again
                   4870: 
1.731     albertel 4871:     if (!$args->{'one_time'}) {
                   4872: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4873:     }
1.811     albertel 4874: 
1.34      www      4875:     if ($chome ne 'no_host') {
1.302     albertel 4876:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4877:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4878: 	   my $username = $env{'user.name'}; # Defult username
                   4879: 	   if(defined $args->{'user'}) {
                   4880: 	       $username = $args->{'user'};
                   4881: 	   }
1.129     albertel 4882:            $returnhash{'home'}= $chome;
                   4883: 	   $returnhash{'domain'} = $cdomain;
                   4884: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4885:            if (!defined($returnhash{'type'})) {
                   4886:                $returnhash{'type'} = 'Course';
                   4887:            }
1.130     albertel 4888:            while (my ($name,$value) = each %returnhash) {
1.53      www      4889:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4890:            }
1.270     www      4891:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     4892:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     4893: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      4894:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4895:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4896:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4897:        }
                   4898:     }
1.731     albertel 4899:     if (!$args->{'one_time'}) {
1.949     raeburn  4900: 	&appenv(\%envhash);
1.731     albertel 4901:     }
1.302     albertel 4902:     return %returnhash;
1.461     www      4903: }
                   4904: 
1.1080    raeburn  4905: sub update_released_required {
                   4906:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4907:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4908:         $cid = $env{'request.course.id'};
                   4909:         $cdom = $env{'course.'.$cid.'.domain'};
                   4910:         $cnum = $env{'course.'.$cid.'.num'};
                   4911:         $chome = $env{'course.'.$cid.'.home'};
                   4912:     }
                   4913:     if ($needsrelease) {
                   4914:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4915:         my $needsupdate;
                   4916:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4917:             $needsupdate = 1;
                   4918:         } else {
                   4919:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4920:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4921:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4922:                 $needsupdate = 1;
                   4923:             }
                   4924:         }
                   4925:         if ($needsupdate) {
                   4926:             my %needshash = (
                   4927:                              'internal.releaserequired' => $needsrelease,
                   4928:                             );
                   4929:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4930:             if ($putresult eq 'ok') {
                   4931:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4932:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4933:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4934:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4935:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4936:                 }
                   4937:             }
                   4938:         }
                   4939:     }
                   4940:     return;
                   4941: }
                   4942: 
1.461     www      4943: # -------------------------------------------------See if a user is privileged
                   4944: 
                   4945: sub privileged {
                   4946:     my ($username,$domain)=@_;
1.1170    droeschl 4947: 
                   4948:     my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   4949:     my $now = time;
                   4950: 
                   4951:     for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
                   4952:             my ($trole, $tend, $tstart) = split(/_/, $role);
                   4953:             if (($trole eq 'dc') || ($trole eq 'su')) {
                   4954:                 return 1 unless ($tend && $tend < $now) 
                   4955:                     or ($tstart && $tstart > $now);
                   4956:             }
1.461     www      4957: 	}
1.1170    droeschl 4958: 
1.461     www      4959:     return 0;
1.9       www      4960: }
1.1       albertel 4961: 
1.103     harris41 4962: # -------------------------------------------------------- Get user privileges
1.11      www      4963: 
                   4964: sub rolesinit {
1.1169    droeschl 4965:     my ($domain, $username) = @_;
                   4966:     my %userroles = ('user.login.time' => time);
                   4967:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   4968: 
                   4969:     # firstaccess and timerinterval are related to timed maps/resources. 
                   4970:     # also, blocking can be triggered by an activating timer
                   4971:     # it's saved in the user's %env.
                   4972:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   4973:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   4974:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   4975:         %timerintchk, %timerintenv);
                   4976: 
1.1162    raeburn  4977:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 4978:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  4979:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   4980:     }
1.1169    droeschl 4981: 
1.1162    raeburn  4982:     foreach my $key (keys(%timerinterval)) {
                   4983:         my ($cid,$rest) = split(/\0/,$key);
                   4984:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   4985:     }
1.1169    droeschl 4986: 
1.11      www      4987:     my %allroles=();
1.1162    raeburn  4988:     my %allgroups=();
1.11      www      4989: 
1.1169    droeschl 4990:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
                   4991:         my $role = $rolesdump{$area};
                   4992:         $area =~ s/\_\w\w$//;
                   4993: 
                   4994:         my ($trole, $tend, $tstart, $group_privs);
                   4995: 
                   4996:         if ($role =~ /^cr/) {
                   4997:         # Custom role, defined by a user 
                   4998:         # e.g., user.role.cr/msu/smith/mynewrole
                   4999:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5000:                 $trole = $1;
                   5001:                 ($tend, $tstart) = split('_', $2);
                   5002:             } else {
                   5003:                 $trole = $role;
                   5004:             }
                   5005:         } elsif ($role =~ m|^gr/|) {
                   5006:         # Role of member in a group, defined within a course/community
                   5007:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5008:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5009:             next if $tstart eq '-1';
                   5010:             ($trole, $group_privs) = split(/\//, $trole);
                   5011:             $group_privs = &unescape($group_privs);
                   5012:         } else {
                   5013:         # Just a normal role, defined in roles.tab
                   5014:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5015:         }
                   5016: 
                   5017:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5018:                  $username);
                   5019:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5020: 
                   5021:         # role expired or not available yet?
                   5022:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5023:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5024: 
                   5025:         next if $area eq '' or $trole eq '';
                   5026: 
                   5027:         my $spec = "$trole.$area";
                   5028:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5029: 
                   5030:         if ($trole =~ /^cr\//) {
                   5031:         # Custom role, defined by a user
                   5032:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5033:         } elsif ($trole eq 'gr') {
                   5034:         # Role of a member in a group, defined within a course/community
                   5035:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5036:             next;
                   5037:         } else {
                   5038:         # Normal role, defined in roles.tab
                   5039:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5040:         }
                   5041: 
                   5042:         my $cid = $tdomain.'_'.$trest;
                   5043:         unless ($firstaccchk{$cid}) {
                   5044:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5045:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5046:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5047:                         $coursetimerstarts{$cid}{$item}; 
                   5048:                 }
                   5049:             }
                   5050:             $firstaccchk{$cid} = 1;
                   5051:         }
                   5052:         unless ($timerintchk{$cid}) {
                   5053:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5054:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5055:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5056:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5057:                 }
1.12      www      5058:             }
1.1169    droeschl 5059:             $timerintchk{$cid} = 1;
1.191     harris41 5060:         }
1.11      www      5061:     }
1.1169    droeschl 5062: 
                   5063:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5064:         \%allroles, \%allgroups);
                   5065:     $env{'user.adv'} = $userroles{'user.adv'};
                   5066: 
1.1162    raeburn  5067:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5068: }
                   5069: 
1.567     raeburn  5070: sub set_arearole {
1.1172.2.19  raeburn  5071:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5072:     unless ($nolog) {
1.567     raeburn  5073: # log the associated role with the area
1.1172.2.19  raeburn  5074:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5075:     }
1.743     albertel 5076:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5077: }
                   5078: 
                   5079: sub custom_roleprivs {
                   5080:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5081:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   5082:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 5083:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5084:         my ($rdummy,$roledef)=
                   5085:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5086:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5087:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5088:             if (defined($syspriv)) {
1.1043    raeburn  5089:                 if ($trest =~ /^$match_community$/) {
                   5090:                     $syspriv =~ s/bre\&S//; 
                   5091:                 }
1.567     raeburn  5092:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5093:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5094:             }
                   5095:             if ($tdomain ne '') {
                   5096:                 if (defined($dompriv)) {
                   5097:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5098:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5099:                 }
                   5100:                 if (($trest ne '') && (defined($coursepriv))) {
                   5101:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5102:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5103:                 }
                   5104:             }
                   5105:         }
                   5106:     }
                   5107: }
                   5108: 
1.678     raeburn  5109: sub group_roleprivs {
                   5110:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5111:     my $access = 1;
                   5112:     my $now = time;
                   5113:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5114:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5115:     if ($access) {
1.811     albertel 5116:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5117:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5118:     }
                   5119: }
1.567     raeburn  5120: 
                   5121: sub standard_roleprivs {
                   5122:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5123:     if (defined($pr{$trole.':s'})) {
                   5124:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5125:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5126:     }
                   5127:     if ($tdomain ne '') {
                   5128:         if (defined($pr{$trole.':d'})) {
                   5129:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5130:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5131:         }
                   5132:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5133:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5134:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5135:         }
                   5136:     }
                   5137: }
                   5138: 
                   5139: sub set_userprivs {
1.1064    raeburn  5140:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5141:     my $author=0;
                   5142:     my $adv=0;
1.678     raeburn  5143:     my %grouproles = ();
                   5144:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5145:         my @groupkeys; 
1.1000    raeburn  5146:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5147:             push(@groupkeys,$role);
                   5148:         }
                   5149:         if (ref($groups_roles) eq 'HASH') {
                   5150:             foreach my $key (keys(%{$groups_roles})) {
                   5151:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5152:                     push(@groupkeys,$key);
                   5153:                 }
                   5154:             }
                   5155:         }
                   5156:         if (@groupkeys > 0) {
                   5157:             foreach my $role (@groupkeys) {
                   5158:                 my ($trole,$area,$sec,$extendedarea);
                   5159:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5160:                     $trole = $1;
                   5161:                     $area = $2;
                   5162:                     $sec = $3;
                   5163:                     $extendedarea = $area.$sec;
                   5164:                     if (exists($$allgroups{$area})) {
                   5165:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5166:                             my $spec = $trole.'.'.$extendedarea;
                   5167:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5168:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5169:                         }
1.678     raeburn  5170:                     }
                   5171:                 }
                   5172:             }
                   5173:         }
                   5174:     }
1.800     albertel 5175:     foreach my $group (keys(%grouproles)) {
                   5176:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5177:     }
1.800     albertel 5178:     foreach my $role (keys(%{$allroles})) {
                   5179:         my %thesepriv;
1.941     raeburn  5180:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5181:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5182:             if ($item ne '') {
                   5183:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5184:                 if ($restrictions eq '') {
                   5185:                     $thesepriv{$privilege}='F';
                   5186:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5187:                     $thesepriv{$privilege}.=$restrictions;
                   5188:                 }
                   5189:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5190:             }
                   5191:         }
                   5192:         my $thesestr='';
1.1104    raeburn  5193:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5194: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5195: 	}
                   5196:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5197:     }
                   5198:     return ($author,$adv);
                   5199: }
                   5200: 
1.994     raeburn  5201: sub role_status {
1.1104    raeburn  5202:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5203:     my @pwhere = ();
                   5204:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   5205:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   5206:         unless (!defined($$role) || $$role eq '') {
                   5207:             $$where=join('.',@pwhere);
                   5208:             $$trolecode=$$role.'.'.$$where;
                   5209:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5210:             $$tstatus='is';
1.1104    raeburn  5211:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5212:                 $$tstatus='future';
1.1034    raeburn  5213:                 if ($$tstart<$now) {
                   5214:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5215:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5216:                             my (%allroles,%allgroups,$group_privs,
                   5217:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5218:                             my %userroles = (
                   5219:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5220:                             );
1.1064    raeburn  5221:                             @rolecodes = ('cm'); 
1.1002    raeburn  5222:                             my $spec=$$role.'.'.$$where;
                   5223:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5224:                             if ($$role =~ /^cr\//) {
                   5225:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5226:                                 push(@rolecodes,'cr');
1.1002    raeburn  5227:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5228:                                 push(@rolecodes,$$role);
1.1002    raeburn  5229:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5230:                                                     $env{'user.name'});
1.1064    raeburn  5231:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5232:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5233:                                 $group_privs = &unescape($group_privs);
                   5234:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5235:                                 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  5236:                                 &get_groups_roles($tdomain,$trest,
                   5237:                                                   \%course_roles,\@rolecodes,
                   5238:                                                   \%groups_roles);
1.1002    raeburn  5239:                             } else {
1.1064    raeburn  5240:                                 push(@rolecodes,$$role);
1.1002    raeburn  5241:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5242:                             }
1.1064    raeburn  5243:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5244:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5245:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5246:                         }
                   5247:                     }
1.1034    raeburn  5248:                     $$tstatus = 'is';
1.1002    raeburn  5249:                 }
1.994     raeburn  5250:             }
                   5251:             if ($$tend) {
1.1104    raeburn  5252:                 if ($$tend<$update) {
1.994     raeburn  5253:                     $$tstatus='expired';
                   5254:                 } elsif ($$tend<$now) {
                   5255:                     $$tstatus='will_not';
                   5256:                 }
                   5257:             }
                   5258:         }
                   5259:     }
                   5260: }
                   5261: 
1.1104    raeburn  5262: sub get_groups_roles {
                   5263:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5264:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5265:                   (ref($rolecodes) eq 'ARRAY') && 
                   5266:                   (ref($groups_roles) eq 'HASH')); 
                   5267:     if (keys(%{$cdom_courseroles}) > 0) {
                   5268:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5269:         if ($cdom ne '' && $cnum ne '') {
                   5270:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5271:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5272:                     my $crsrole = $1;
                   5273:                     my $crssec = $2;
                   5274:                     if ($crsrole =~ /^cr/) {
                   5275:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5276:                             push(@{$rolecodes},'cr');
                   5277:                         }
                   5278:                     } else {
                   5279:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5280:                             push(@{$rolecodes},$crsrole);
                   5281:                         }
                   5282:                     }
                   5283:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5284:                     if ($crssec ne '') {
                   5285:                         $rolekey .= "/$crssec";
                   5286:                     }
                   5287:                     $rolekey .= './';
                   5288:                     $groups_roles->{$rolekey} = $rolecodes;
                   5289:                 }
                   5290:             }
                   5291:         }
                   5292:     }
                   5293:     return;
                   5294: }
                   5295: 
                   5296: sub delete_env_groupprivs {
                   5297:     my ($where,$courseroles,$possroles) = @_;
                   5298:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5299:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5300:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5301:         %{$courseroles->{$udom}} =
                   5302:             &get_my_roles('','','userroles',['active'],
                   5303:                           $possroles,[$udom],1);
                   5304:     }
                   5305:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5306:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5307:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5308:             my $area = '/'.$cdom.'/'.$cnum;
                   5309:             my $privkey = "user.priv.$crsrole.$area";
                   5310:             if ($crssec ne '') {
                   5311:                 $privkey .= '/'.$crssec;
                   5312:             }
                   5313:             $privkey .= ".$area/$group";
                   5314:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5315:         }
                   5316:     }
                   5317:     return;
                   5318: }
                   5319: 
1.994     raeburn  5320: sub check_adhoc_privs {
1.1104    raeburn  5321:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5322:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.9  raeburn  5323:     my $setprivs;
1.994     raeburn  5324:     if ($env{$cckey}) {
                   5325:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5326:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5327:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5328:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9  raeburn  5329:             $setprivs = 1;
1.994     raeburn  5330:         }
                   5331:     } else {
1.1088    raeburn  5332:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9  raeburn  5333:         $setprivs = 1;
1.994     raeburn  5334:     }
1.1172.2.9  raeburn  5335:     return $setprivs;
1.994     raeburn  5336: }
                   5337: 
                   5338: sub set_adhoc_privileges {
                   5339: # role can be cc or ca
1.1088    raeburn  5340:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5341:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5342:     my $spec = $role.'.'.$area;
                   5343:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  5344:                                   $env{'user.name'},1);
1.994     raeburn  5345:     my %ccrole = ();
                   5346:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5347:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5348:     &appenv(\%userroles,[$role,'cm']);
                   5349:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5350:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5351:         &appenv( {'request.role'        => $spec,
                   5352:                   'request.role.domain' => $dcdom,
                   5353:                   'request.course.sec'  => ''
                   5354:                  }
                   5355:                );
                   5356:         my $tadv=0;
                   5357:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5358:         &appenv({'request.role.adv'    => $tadv});
                   5359:     }
1.994     raeburn  5360: }
                   5361: 
1.12      www      5362: # --------------------------------------------------------------- get interface
                   5363: 
                   5364: sub get {
1.131     albertel 5365:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5366:    my $items='';
1.800     albertel 5367:    foreach my $item (@$storearr) {
                   5368:        $items.=&escape($item).'&';
1.191     harris41 5369:    }
1.12      www      5370:    $items=~s/\&$//;
1.620     albertel 5371:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5372:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5373:    my $uhome=&homeserver($uname,$udomain);
                   5374: 
1.133     albertel 5375:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5376:    my @pairs=split(/\&/,$rep);
1.273     albertel 5377:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5378:      return @pairs;
                   5379:    }
1.15      www      5380:    my %returnhash=();
1.42      www      5381:    my $i=0;
1.800     albertel 5382:    foreach my $item (@$storearr) {
                   5383:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5384:       $i++;
1.191     harris41 5385:    }
1.15      www      5386:    return %returnhash;
1.27      www      5387: }
                   5388: 
                   5389: # --------------------------------------------------------------- del interface
                   5390: 
                   5391: sub del {
1.133     albertel 5392:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5393:    my $items='';
1.800     albertel 5394:    foreach my $item (@$storearr) {
                   5395:        $items.=&escape($item).'&';
1.191     harris41 5396:    }
1.984     neumanie 5397: 
1.27      www      5398:    $items=~s/\&$//;
1.620     albertel 5399:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5400:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5401:    my $uhome=&homeserver($uname,$udomain);
                   5402:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5403: }
                   5404: 
                   5405: # -------------------------------------------------------------- dump interface
                   5406: 
1.1172.2.22! raeburn  5407: sub unserialize {
        !          5408:     my ($rep, $escapedkeys) = @_;
        !          5409: 
        !          5410:     return {} if $rep =~ /^error/;
        !          5411: 
        !          5412:     my %returnhash=();
        !          5413:     foreach my $item (split(/\&/,$rep)) {
        !          5414:         my ($key, $value) = split(/=/, $item, 2);
        !          5415:         $key = unescape($key) unless $escapedkeys;
        !          5416:         next if $key =~ /^error: 2 /;
        !          5417:         $returnhash{$key} = &thaw_unescape($value);
        !          5418:     }
        !          5419:     return \%returnhash;
        !          5420: }
        !          5421: 
        !          5422: # see Lond::dump_with_regexp
        !          5423: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5424: sub dump {
1.1172.2.22! raeburn  5425:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5426:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5427:     if (!$uname) { $uname=$env{'user.name'}; }
                   5428:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5429: 
1.1172.2.22! raeburn  5430:     my $reply;
        !          5431:     if (grep { $_ eq $uhome } &current_machine_ids()) {
        !          5432:         # user is hosted on this machine
        !          5433:         $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
        !          5434:                     $uname, $namespace, $regexp, $range)), $loncaparevs{$uhome});
        !          5435:         return %{&unserialize($reply, $escapedkeys)};
        !          5436:     }
1.755     albertel 5437:     if ($regexp) {
                   5438: 	$regexp=&escape($regexp);
                   5439:     } else {
                   5440: 	$regexp='.';
                   5441:     }
1.1166    raeburn  5442:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5443:     my @pairs=split(/\&/,$rep);
                   5444:     my %returnhash=();
1.1098    foxr     5445:     if (!($rep =~ /^error/ )) {
                   5446: 	foreach my $item (@pairs) {
                   5447: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22! raeburn  5448:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     5449: 	    next if ($key =~ /^error: 2 /);
                   5450: 	    $returnhash{$key}=&thaw_unescape($value);
                   5451: 	}
1.755     albertel 5452:     }
                   5453:     return %returnhash;
1.407     www      5454: }
                   5455: 
1.1098    foxr     5456: 
1.717     albertel 5457: # --------------------------------------------------------- dumpstore interface
                   5458: 
                   5459: sub dumpstore {
                   5460:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22! raeburn  5461:    # same as dump but keys must be escaped. They may contain colon separated
        !          5462:    # lists of values that may themself contain colons (e.g. symbs).
        !          5463:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5464: }
                   5465: 
1.407     www      5466: # -------------------------------------------------------------- keys interface
                   5467: 
                   5468: sub getkeys {
                   5469:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5470:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5471:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5472:    my $uhome=&homeserver($uname,$udomain);
                   5473:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5474:    my @keyarray=();
1.800     albertel 5475:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5476:       next if ($key =~ /^error: 2 /);
1.800     albertel 5477:       push(@keyarray,&unescape($key));
1.407     www      5478:    }
                   5479:    return @keyarray;
1.318     matthew  5480: }
                   5481: 
1.319     matthew  5482: # --------------------------------------------------------------- currentdump
                   5483: sub currentdump {
1.328     matthew  5484:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5485:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5486:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5487:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5488:    my $uhome = &homeserver($sname,$sdom);
                   5489:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  5490:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5491:    #
1.318     matthew  5492:    my %returnhash=();
1.319     matthew  5493:    #
                   5494:    if ($rep eq "unknown_cmd") { 
                   5495:        # an old lond will not know currentdump
                   5496:        # Do a dump and make it look like a currentdump
1.822     albertel 5497:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5498:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5499:        my %hash = @tmp;
                   5500:        @tmp=();
1.424     matthew  5501:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5502:    } else {
                   5503:        my @pairs=split(/\&/,$rep);
1.800     albertel 5504:        foreach my $pair (@pairs) {
                   5505:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5506:            my ($symb,$param) = split(/:/,$key);
                   5507:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5508:                                                         &thaw_unescape($value);
1.319     matthew  5509:        }
1.191     harris41 5510:    }
1.12      www      5511:    return %returnhash;
1.424     matthew  5512: }
                   5513: 
                   5514: sub convert_dump_to_currentdump{
                   5515:     my %hash = %{shift()};
                   5516:     my %returnhash;
                   5517:     # Code ripped from lond, essentially.  The only difference
                   5518:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5519:     # we might run in to problems with parameter names =~ /^v\./
                   5520:     while (my ($key,$value) = each(%hash)) {
                   5521:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5522: 	$symb  = &unescape($symb);
                   5523: 	$param = &unescape($param);
1.424     matthew  5524:         next if ($v eq 'version' || $symb eq 'keys');
                   5525:         next if (exists($returnhash{$symb}) &&
                   5526:                  exists($returnhash{$symb}->{$param}) &&
                   5527:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5528:         $returnhash{$symb}->{$param}=$value;
                   5529:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5530:     }
                   5531:     #
                   5532:     # Remove all of the keys in the hashes which keep track of
                   5533:     # the version of the parameter.
                   5534:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5535:         # use a foreach because we are going to delete from the hash.
                   5536:         foreach my $key (keys(%$param_hash)) {
                   5537:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5538:         }
                   5539:     }
                   5540:     return \%returnhash;
1.12      www      5541: }
                   5542: 
1.627     albertel 5543: # ------------------------------------------------------ critical inc interface
                   5544: 
                   5545: sub cinc {
                   5546:     return &inc(@_,'critical');
                   5547: }
                   5548: 
1.449     matthew  5549: # --------------------------------------------------------------- inc interface
                   5550: 
                   5551: sub inc {
1.627     albertel 5552:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5553:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5554:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5555:     my $uhome=&homeserver($uname,$udomain);
                   5556:     my $items='';
                   5557:     if (! ref($store)) {
                   5558:         # got a single value, so use that instead
                   5559:         $items = &escape($store).'=&';
                   5560:     } elsif (ref($store) eq 'SCALAR') {
                   5561:         $items = &escape($$store).'=&';        
                   5562:     } elsif (ref($store) eq 'ARRAY') {
                   5563:         $items = join('=&',map {&escape($_);} @{$store});
                   5564:     } elsif (ref($store) eq 'HASH') {
                   5565:         while (my($key,$value) = each(%{$store})) {
                   5566:             $items.= &escape($key).'='.&escape($value).'&';
                   5567:         }
                   5568:     }
                   5569:     $items=~s/\&$//;
1.627     albertel 5570:     if ($critical) {
                   5571: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5572:     } else {
                   5573: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5574:     }
1.449     matthew  5575: }
                   5576: 
1.12      www      5577: # --------------------------------------------------------------- put interface
                   5578: 
                   5579: sub put {
1.134     albertel 5580:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5581:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5582:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5583:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5584:    my $items='';
1.800     albertel 5585:    foreach my $item (keys(%$storehash)) {
                   5586:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5587:    }
1.12      www      5588:    $items=~s/\&$//;
1.134     albertel 5589:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5590: }
                   5591: 
1.631     albertel 5592: # ------------------------------------------------------------ newput interface
                   5593: 
                   5594: sub newput {
                   5595:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5596:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5597:    if (!$uname) { $uname=$env{'user.name'}; }
                   5598:    my $uhome=&homeserver($uname,$udomain);
                   5599:    my $items='';
                   5600:    foreach my $key (keys(%$storehash)) {
                   5601:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5602:    }
                   5603:    $items=~s/\&$//;
                   5604:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5605: }
                   5606: 
                   5607: # ---------------------------------------------------------  putstore interface
                   5608: 
1.524     raeburn  5609: sub putstore {
1.715     albertel 5610:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 5611:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5612:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5613:    my $uhome=&homeserver($uname,$udomain);
                   5614:    my $items='';
1.715     albertel 5615:    foreach my $key (keys(%$storehash)) {
                   5616:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5617:    }
1.715     albertel 5618:    $items=~s/\&$//;
1.716     albertel 5619:    my $esc_symb=&escape($symb);
                   5620:    my $esc_v=&escape($version);
1.715     albertel 5621:    my $reply =
1.716     albertel 5622:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5623: 	      $uhome);
                   5624:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5625:        # gfall back to way things use to be done
1.715     albertel 5626:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5627: 			    $uname);
1.524     raeburn  5628:    }
1.715     albertel 5629:    return $reply;
                   5630: }
                   5631: 
                   5632: sub old_putstore {
1.716     albertel 5633:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5634:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5635:     if (!$uname) { $uname=$env{'user.name'}; }
                   5636:     my $uhome=&homeserver($uname,$udomain);
                   5637:     my %newstorehash;
1.800     albertel 5638:     foreach my $item (keys(%$storehash)) {
                   5639: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5640: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5641:     }
                   5642:     my $items='';
                   5643:     my %allitems = ();
1.800     albertel 5644:     foreach my $item (keys(%newstorehash)) {
                   5645: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5646: 	    my $key = $1.':keys:'.$2;
                   5647: 	    $allitems{$key} .= $3.':';
                   5648: 	}
1.800     albertel 5649: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5650:     }
1.800     albertel 5651:     foreach my $item (keys(%allitems)) {
                   5652: 	$allitems{$item} =~ s/\:$//;
                   5653: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5654:     }
                   5655:     $items=~s/\&$//;
                   5656:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5657: }
                   5658: 
1.47      www      5659: # ------------------------------------------------------ critical put interface
                   5660: 
                   5661: sub cput {
1.134     albertel 5662:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5663:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5664:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5665:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5666:    my $items='';
1.800     albertel 5667:    foreach my $item (keys(%$storehash)) {
                   5668:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5669:    }
1.47      www      5670:    $items=~s/\&$//;
1.134     albertel 5671:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5672: }
                   5673: 
                   5674: # -------------------------------------------------------------- eget interface
                   5675: 
                   5676: sub eget {
1.133     albertel 5677:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5678:    my $items='';
1.800     albertel 5679:    foreach my $item (@$storearr) {
                   5680:        $items.=&escape($item).'&';
1.191     harris41 5681:    }
1.12      www      5682:    $items=~s/\&$//;
1.620     albertel 5683:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5684:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5685:    my $uhome=&homeserver($uname,$udomain);
                   5686:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5687:    my @pairs=split(/\&/,$rep);
                   5688:    my %returnhash=();
1.42      www      5689:    my $i=0;
1.800     albertel 5690:    foreach my $item (@$storearr) {
                   5691:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5692:       $i++;
1.191     harris41 5693:    }
1.12      www      5694:    return %returnhash;
                   5695: }
                   5696: 
1.667     albertel 5697: # ------------------------------------------------------------ tmpput interface
                   5698: sub tmpput {
1.802     raeburn  5699:     my ($storehash,$server,$context)=@_;
1.667     albertel 5700:     my $items='';
1.800     albertel 5701:     foreach my $item (keys(%$storehash)) {
                   5702: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5703:     }
                   5704:     $items=~s/\&$//;
1.802     raeburn  5705:     if (defined($context)) {
                   5706:         $items .= ':'.&escape($context);
                   5707:     }
1.667     albertel 5708:     return &reply("tmpput:$items",$server);
                   5709: }
                   5710: 
                   5711: # ------------------------------------------------------------ tmpget interface
                   5712: sub tmpget {
1.688     albertel 5713:     my ($token,$server)=@_;
                   5714:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5715:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5716:     my %returnhash;
                   5717:     foreach my $item (split(/\&/,$rep)) {
                   5718: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5719:         next if ($key =~ /^error: 2 /);
1.667     albertel 5720: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5721:     }
                   5722:     return %returnhash;
                   5723: }
                   5724: 
1.1113    raeburn  5725: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 5726: sub tmpdel {
                   5727:     my ($token,$server)=@_;
                   5728:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5729:     return &reply("tmpdel:$token",$server);
                   5730: }
                   5731: 
1.1172.2.13  raeburn  5732: # ------------------------------------------------------------ get_timebased_id
                   5733: 
                   5734: sub get_timebased_id {
                   5735:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   5736:         $maxtries) = @_;
                   5737:     my ($newid,$error,$dellock);
                   5738:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   5739:         return ('','ok','invalid call to get suffix');
                   5740:     }
                   5741: 
                   5742: # set defaults for any optional args for which values were not supplied
                   5743:     if ($who eq '') {
                   5744:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   5745:     }
                   5746:     if (!$locktries) {
                   5747:         $locktries = 3;
                   5748:     }
                   5749:     if (!$maxtries) {
                   5750:         $maxtries = 10;
                   5751:     }
                   5752: 
                   5753:     if (($cdom eq '') || ($cnum eq '')) {
                   5754:         if ($env{'request.course.id'}) {
                   5755:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5756:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5757:         }
                   5758:         if (($cdom eq '') || ($cnum eq '')) {
                   5759:             return ('','ok','call to get suffix not in course context');
                   5760:         }
                   5761:     }
                   5762: 
                   5763: # construct locking item
                   5764:     my $lockhash = {
                   5765:                       $prefix."\0".'locked_'.$keyid => $who,
                   5766:                    };
                   5767:     my $tries = 0;
                   5768: 
                   5769: # attempt to get lock on nohist_$namespace file
                   5770:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5771:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   5772:         $tries ++;
                   5773:         sleep 1;
                   5774:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5775:     }
                   5776: 
                   5777: # attempt to get unique identifier, based on current timestamp
                   5778:     if ($gotlock eq 'ok') {
                   5779:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   5780:         my $id = time;
                   5781:         $newid = $id;
                   5782:         my $idtries = 0;
                   5783:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   5784:             if ($idtype eq 'concat') {
                   5785:                 $newid = $id.$idtries;
                   5786:             } else {
                   5787:                 $newid ++;
                   5788:             }
                   5789:             $idtries ++;
                   5790:         }
                   5791:         if (!exists($inuse{$prefix."\0".$newid})) {
                   5792:             my %new_item =  (
                   5793:                               $prefix."\0".$newid => $who,
                   5794:                             );
                   5795:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   5796:                                                  $cdom,$cnum);
                   5797:             if ($putresult ne 'ok') {
                   5798:                 undef($newid);
                   5799:                 $error = 'error saving new item: '.$putresult;
                   5800:             }
                   5801:         } else {
                   5802:              $error = ('error: no unique suffix available for the new item ');
                   5803:         }
                   5804: #  remove lock
                   5805:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   5806:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   5807:     } else {
                   5808:         $error = "error: could not obtain lockfile\n";
                   5809:         $dellock = 'ok';
                   5810:     }
                   5811:     return ($newid,$dellock,$error);
                   5812: }
                   5813: 
1.765     albertel 5814: # -------------------------------------------------- portfolio access checking
                   5815: 
                   5816: sub portfolio_access {
1.766     albertel 5817:     my ($requrl) = @_;
1.765     albertel 5818:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   5819:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  5820:     if ($result) {
                   5821:         my %setters;
                   5822:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5823:             my ($startblock,$endblock) =
                   5824:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   5825:             if ($startblock && $endblock) {
                   5826:                 return 'B';
                   5827:             }
                   5828:         } else {
                   5829:             my ($startblock,$endblock) =
                   5830:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   5831:             if ($startblock && $endblock) {
                   5832:                 return 'B';
                   5833:             }
                   5834:         }
                   5835:     }
1.765     albertel 5836:     if ($result eq 'ok') {
1.766     albertel 5837:        return 'F';
1.765     albertel 5838:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 5839:        return 'A';
1.765     albertel 5840:     }
1.766     albertel 5841:     return '';
1.765     albertel 5842: }
                   5843: 
                   5844: sub get_portfolio_access {
1.767     albertel 5845:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   5846: 
                   5847:     if (!ref($access_hash)) {
                   5848: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   5849: 	my %access_controls = &get_access_controls($current_perms,$group,
                   5850: 						   $file_name);
                   5851: 	$access_hash = $access_controls{$file_name};
                   5852:     }
                   5853: 
1.765     albertel 5854:     my ($public,$guest,@domains,@users,@courses,@groups);
                   5855:     my $now = time;
                   5856:     if (ref($access_hash) eq 'HASH') {
                   5857:         foreach my $key (keys(%{$access_hash})) {
                   5858:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5859:             if ($start > $now) {
                   5860:                 next;
                   5861:             }
                   5862:             if ($end && $end<$now) {
                   5863:                 next;
                   5864:             }
                   5865:             if ($scope eq 'public') {
                   5866:                 $public = $key;
                   5867:                 last;
                   5868:             } elsif ($scope eq 'guest') {
                   5869:                 $guest = $key;
                   5870:             } elsif ($scope eq 'domains') {
                   5871:                 push(@domains,$key);
                   5872:             } elsif ($scope eq 'users') {
                   5873:                 push(@users,$key);
                   5874:             } elsif ($scope eq 'course') {
                   5875:                 push(@courses,$key);
                   5876:             } elsif ($scope eq 'group') {
                   5877:                 push(@groups,$key);
                   5878:             }
                   5879:         }
                   5880:         if ($public) {
                   5881:             return 'ok';
                   5882:         }
                   5883:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5884:             if ($guest) {
                   5885:                 return $guest;
                   5886:             }
                   5887:         } else {
                   5888:             if (@domains > 0) {
                   5889:                 foreach my $domkey (@domains) {
                   5890:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   5891:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   5892:                             return 'ok';
                   5893:                         }
                   5894:                     }
                   5895:                 }
                   5896:             }
                   5897:             if (@users > 0) {
                   5898:                 foreach my $userkey (@users) {
1.865     raeburn  5899:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   5900:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   5901:                             if (ref($item) eq 'HASH') {
                   5902:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   5903:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   5904:                                     return 'ok';
                   5905:                                 }
                   5906:                             }
                   5907:                         }
                   5908:                     } 
1.765     albertel 5909:                 }
                   5910:             }
                   5911:             my %roleshash;
                   5912:             my @courses_and_groups = @courses;
                   5913:             push(@courses_and_groups,@groups); 
                   5914:             if (@courses_and_groups > 0) {
                   5915:                 my (%allgroups,%allroles); 
                   5916:                 my ($start,$end,$role,$sec,$group);
                   5917:                 foreach my $envkey (%env) {
1.1060    raeburn  5918:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5919:                         my $cid = $2.'_'.$3; 
                   5920:                         if ($1 eq 'gr') {
                   5921:                             $group = $4;
                   5922:                             $allgroups{$cid}{$group} = $env{$envkey};
                   5923:                         } else {
                   5924:                             if ($4 eq '') {
                   5925:                                 $sec = 'none';
                   5926:                             } else {
                   5927:                                 $sec = $4;
                   5928:                             }
                   5929:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5930:                         }
1.811     albertel 5931:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5932:                         my $cid = $2.'_'.$3;
                   5933:                         if ($4 eq '') {
                   5934:                             $sec = 'none';
                   5935:                         } else {
                   5936:                             $sec = $4;
                   5937:                         }
                   5938:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5939:                     }
                   5940:                 }
                   5941:                 if (keys(%allroles) == 0) {
                   5942:                     return;
                   5943:                 }
                   5944:                 foreach my $key (@courses_and_groups) {
                   5945:                     my %content = %{$$access_hash{$key}};
                   5946:                     my $cnum = $content{'number'};
                   5947:                     my $cdom = $content{'domain'};
                   5948:                     my $cid = $cdom.'_'.$cnum;
                   5949:                     if (!exists($allroles{$cid})) {
                   5950:                         next;
                   5951:                     }    
                   5952:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   5953:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   5954:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   5955:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   5956:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   5957:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   5958:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   5959:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   5960:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   5961:                                         if (grep/^all$/,@sections) {
                   5962:                                             return 'ok';
                   5963:                                         } else {
                   5964:                                             if (grep/^$sec$/,@sections) {
                   5965:                                                 return 'ok';
                   5966:                                             }
                   5967:                                         }
                   5968:                                     }
                   5969:                                 }
                   5970:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   5971:                                     if (grep/^none$/,@groups) {
                   5972:                                         return 'ok';
                   5973:                                     }
                   5974:                                 } else {
                   5975:                                     if (grep/^all$/,@groups) {
                   5976:                                         return 'ok';
                   5977:                                     } 
                   5978:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   5979:                                         if (grep/^$group$/,@groups) {
                   5980:                                             return 'ok';
                   5981:                                         }
                   5982:                                     }
                   5983:                                 } 
                   5984:                             }
                   5985:                         }
                   5986:                     }
                   5987:                 }
                   5988:             }
                   5989:             if ($guest) {
                   5990:                 return $guest;
                   5991:             }
                   5992:         }
                   5993:     }
                   5994:     return;
                   5995: }
                   5996: 
                   5997: sub course_group_datechecker {
                   5998:     my ($dates,$now,$status) = @_;
                   5999:     my ($start,$end) = split(/\./,$dates);
                   6000:     if (!$start && !$end) {
                   6001:         return 'ok';
                   6002:     }
                   6003:     if (grep/^active$/,@{$status}) {
                   6004:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6005:             return 'ok';
                   6006:         }
                   6007:     }
                   6008:     if (grep/^previous$/,@{$status}) {
                   6009:         if ($end > $now ) {
                   6010:             return 'ok';
                   6011:         }
                   6012:     }
                   6013:     if (grep/^future$/,@{$status}) {
                   6014:         if ($start > $now) {
                   6015:             return 'ok';
                   6016:         }
                   6017:     }
                   6018:     return; 
                   6019: }
                   6020: 
                   6021: sub parse_portfolio_url {
                   6022:     my ($url) = @_;
                   6023: 
                   6024:     my ($type,$udom,$unum,$group,$file_name);
                   6025:     
1.823     albertel 6026:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6027: 	$type = 1;
                   6028:         $udom = $1;
                   6029:         $unum = $2;
                   6030:         $file_name = $3;
1.823     albertel 6031:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6032: 	$type = 2;
                   6033:         $udom = $1;
                   6034:         $unum = $2;
                   6035:         $group = $3;
                   6036:         $file_name = $3.'/'.$4;
                   6037:     }
                   6038:     if (wantarray) {
                   6039: 	return ($type,$udom,$unum,$file_name,$group);
                   6040:     }
                   6041:     return $type;
                   6042: }
                   6043: 
                   6044: sub is_portfolio_url {
                   6045:     my ($url) = @_;
                   6046:     return scalar(&parse_portfolio_url($url));
                   6047: }
                   6048: 
1.798     raeburn  6049: sub is_portfolio_file {
                   6050:     my ($file) = @_;
1.820     raeburn  6051:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6052:         return 1;
                   6053:     }
                   6054:     return;
                   6055: }
                   6056: 
1.976     raeburn  6057: sub usertools_access {
1.1084    raeburn  6058:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6059:     my ($access,%tools);
                   6060:     if ($context eq '') {
                   6061:         $context = 'tools';
                   6062:     }
                   6063:     if ($context eq 'requestcourses') {
                   6064:         %tools = (
                   6065:                       official   => 1,
                   6066:                       unofficial => 1,
1.1006    raeburn  6067:                       community  => 1,
1.985     raeburn  6068:                  );
1.1172.2.9  raeburn  6069:     } elsif ($context eq 'requestauthor') {
                   6070:         %tools = (
                   6071:                       requestauthor => 1,
                   6072:                  );
1.985     raeburn  6073:     } else {
                   6074:         %tools = (
                   6075:                       aboutme   => 1,
                   6076:                       blog      => 1,
1.1172.2.6  raeburn  6077:                       webdav    => 1,
1.985     raeburn  6078:                       portfolio => 1,
                   6079:                  );
                   6080:     }
1.976     raeburn  6081:     return if (!defined($tools{$tool}));
                   6082: 
                   6083:     if ((!defined($udom)) || (!defined($uname))) {
                   6084:         $udom = $env{'user.domain'};
                   6085:         $uname = $env{'user.name'};
                   6086:     }
                   6087: 
1.978     raeburn  6088:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6089:         if ($action ne 'reload') {
1.985     raeburn  6090:             if ($context eq 'requestcourses') {
                   6091:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  6092:             } elsif ($context eq 'requestauthor') {
                   6093:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6094:             } else {
                   6095:                 return $env{'environment.availabletools.'.$tool};
                   6096:             }
                   6097:         }
1.976     raeburn  6098:     }
                   6099: 
1.1172.2.9  raeburn  6100:     my ($toolstatus,$inststatus,$envkey);
                   6101:     if ($context eq 'requestauthor') {
                   6102:         $envkey = $context;
                   6103:     } else {
                   6104:         $envkey = $context.'.'.$tool;
                   6105:     }
1.976     raeburn  6106: 
1.985     raeburn  6107:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6108:          ($action ne 'reload')) {
1.1172.2.9  raeburn  6109:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6110:         $inststatus = $env{'environment.inststatus'};
                   6111:     } else {
1.1084    raeburn  6112:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  6113:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6114:             $inststatus = $userenvref->{'inststatus'};
                   6115:         } else {
1.1172.2.9  raeburn  6116:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6117:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6118:             $inststatus = $userenv{'inststatus'};
                   6119:         }
1.976     raeburn  6120:     }
                   6121: 
                   6122:     if ($toolstatus ne '') {
                   6123:         if ($toolstatus) {
                   6124:             $access = 1;
                   6125:         } else {
                   6126:             $access = 0;
                   6127:         }
                   6128:         return $access;
                   6129:     }
                   6130: 
1.1084    raeburn  6131:     my ($is_adv,%domdef);
                   6132:     if (ref($is_advref) eq 'HASH') {
                   6133:         $is_adv = $is_advref->{'is_adv'};
                   6134:     } else {
                   6135:         $is_adv = &is_advanced_user($udom,$uname);
                   6136:     }
                   6137:     if (ref($domdefref) eq 'HASH') {
                   6138:         %domdef = %{$domdefref};
                   6139:     } else {
                   6140:         %domdef = &get_domain_defaults($udom);
                   6141:     }
1.976     raeburn  6142:     if (ref($domdef{$tool}) eq 'HASH') {
                   6143:         if ($is_adv) {
                   6144:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6145:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6146:                     $access = 1;
                   6147:                 } else {
                   6148:                     $access = 0;
                   6149:                 }
                   6150:                 return $access;
                   6151:             }
                   6152:         }
                   6153:         if ($inststatus ne '') {
                   6154:             my ($hasaccess,$hasnoaccess);
                   6155:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6156:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6157:                     if ($domdef{$tool}{$affiliation}) {
                   6158:                         $hasaccess = 1;
                   6159:                     } else {
                   6160:                         $hasnoaccess = 1;
                   6161:                     }
                   6162:                 }
                   6163:             }
                   6164:             if ($hasaccess || $hasnoaccess) {
                   6165:                 if ($hasaccess) {
                   6166:                     $access = 1;
                   6167:                 } elsif ($hasnoaccess) {
                   6168:                     $access = 0; 
                   6169:                 }
                   6170:                 return $access;
                   6171:             }
                   6172:         } else {
                   6173:             if ($domdef{$tool}{'default'} ne '') {
                   6174:                 if ($domdef{$tool}{'default'}) {
                   6175:                     $access = 1;
                   6176:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6177:                     $access = 0;
                   6178:                 }
                   6179:                 return $access;
                   6180:             }
                   6181:         }
                   6182:     } else {
1.1172.2.6  raeburn  6183:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6184:             $access = 1;
                   6185:         } else {
                   6186:             $access = 0;
                   6187:         }
1.976     raeburn  6188:         return $access;
                   6189:     }
                   6190: }
                   6191: 
1.1050    raeburn  6192: sub is_course_owner {
                   6193:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6194:     if (($udom eq '') || ($uname eq '')) {
                   6195:         $udom = $env{'user.domain'};
                   6196:         $uname = $env{'user.name'};
                   6197:     }
                   6198:     unless (($udom eq '') || ($uname eq '')) {
                   6199:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6200:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6201:                 return 1;
                   6202:             } else {
                   6203:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6204:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6205:                     return 1;
                   6206:                 }
                   6207:             }
                   6208:         }
                   6209:     }
                   6210:     return;
                   6211: }
                   6212: 
1.976     raeburn  6213: sub is_advanced_user {
                   6214:     my ($udom,$uname) = @_;
1.1085    raeburn  6215:     if ($udom ne '' && $uname ne '') {
                   6216:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6217:             if (wantarray) {
                   6218:                 return ($env{'user.adv'},$env{'user.author'});
                   6219:             } else {
                   6220:                 return $env{'user.adv'};
                   6221:             }
1.1085    raeburn  6222:         }
                   6223:     }
1.976     raeburn  6224:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6225:     my %allroles;
1.1128    raeburn  6226:     my ($is_adv,$is_author);
1.976     raeburn  6227:     foreach my $role (keys(%roleshash)) {
                   6228:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6229:         my $area = '/'.$tdomain.'/'.$trest;
                   6230:         if ($sec ne '') {
                   6231:             $area .= '/'.$sec;
                   6232:         }
                   6233:         if (($area ne '') && ($trole ne '')) {
                   6234:             my $spec=$trole.'.'.$area;
                   6235:             if ($trole =~ /^cr\//) {
                   6236:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6237:             } elsif ($trole ne 'gr') {
                   6238:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6239:             }
1.1128    raeburn  6240:             if ($trole eq 'au') {
                   6241:                 $is_author = 1;
                   6242:             }
1.976     raeburn  6243:         }
                   6244:     }
                   6245:     foreach my $role (keys(%allroles)) {
                   6246:         last if ($is_adv);
                   6247:         foreach my $item (split(/:/,$allroles{$role})) {
                   6248:             if ($item ne '') {
                   6249:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6250:                 if ($privilege eq 'adv') {
                   6251:                     $is_adv = 1;
                   6252:                     last;
                   6253:                 }
                   6254:             }
                   6255:         }
                   6256:     }
1.1128    raeburn  6257:     if (wantarray) {
                   6258:         return ($is_adv,$is_author);
                   6259:     }
1.976     raeburn  6260:     return $is_adv;
                   6261: }
1.798     raeburn  6262: 
1.1035    raeburn  6263: sub check_can_request {
1.1036    raeburn  6264:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6265:     my $canreq = 0;
                   6266:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6267:     my @options = ('approval','validate','autolimit');
                   6268:     my $optregex = join('|',@options);
                   6269:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6270:         foreach my $type (@{$types}) {
                   6271:             if (&usertools_access($env{'user.name'},
                   6272:                                   $env{'user.domain'},
                   6273:                                   $type,undef,'requestcourses')) {
                   6274:                 $canreq ++;
1.1036    raeburn  6275:                 if (ref($request_domains) eq 'HASH') {
                   6276:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6277:                 }
1.1035    raeburn  6278:                 if ($dom eq $env{'user.domain'}) {
                   6279:                     $can_request->{$type} = 1;
                   6280:                 }
                   6281:             }
                   6282:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6283:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6284:                 if (@curr > 0) {
1.1036    raeburn  6285:                     foreach my $item (@curr) {
                   6286:                         if (ref($request_domains) eq 'HASH') {
                   6287:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6288:                             if ($otherdom ne '') {
                   6289:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6290:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6291:                                         push(@{$request_domains->{$type}},$otherdom);
                   6292:                                     }
                   6293:                                 } else {
                   6294:                                     push(@{$request_domains->{$type}},$otherdom);
                   6295:                                 }
                   6296:                             }
                   6297:                         }
                   6298:                     }
                   6299:                     unless($dom eq $env{'user.domain'}) {
                   6300:                         $canreq ++;
1.1035    raeburn  6301:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6302:                             $can_request->{$type} = 1;
                   6303:                         }
                   6304:                     }
                   6305:                 }
                   6306:             }
                   6307:         }
                   6308:     }
                   6309:     return $canreq;
                   6310: }
                   6311: 
1.341     www      6312: # ---------------------------------------------- Custom access rule evaluation
                   6313: 
                   6314: sub customaccess {
                   6315:     my ($priv,$uri)=@_;
1.807     albertel 6316:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6317:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6318:     $udom = &LONCAPA::clean_domain($udom);
                   6319:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6320:     my $access=0;
1.800     albertel 6321:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6322: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6323: 	if ($type eq 'user') {
                   6324: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6325: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6326: 		if ($tdom) {
                   6327: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6328: 		}
1.896     albertel 6329: 		if ($tuname) {
                   6330: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6331: 		}
                   6332: 		$access=($effect eq 'allow');
                   6333: 		last;
                   6334: 	    }
                   6335: 	} else {
                   6336: 	    if ($role) {
                   6337: 		if ($role ne $urole) { next; }
                   6338: 	    }
                   6339: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6340: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6341: 		if ($tdom) {
                   6342: 		    if ($tdom ne $udom) { next; }
                   6343: 		}
                   6344: 		if ($tcrs) {
                   6345: 		    if ($tcrs ne $ucrs) { next; }
                   6346: 		}
                   6347: 		if ($tsec) {
                   6348: 		    if ($tsec ne $usec) { next; }
                   6349: 		}
                   6350: 		$access=($effect eq 'allow');
                   6351: 		last;
                   6352: 	    }
                   6353: 	    if ($realm eq '' && $role eq '') {
                   6354: 		$access=($effect eq 'allow');
                   6355: 	    }
1.402     bowersj2 6356: 	}
1.341     www      6357:     }
                   6358:     return $access;
                   6359: }
                   6360: 
1.103     harris41 6361: # ------------------------------------------------- Check for a user privilege
1.12      www      6362: 
                   6363: sub allowed {
1.810     raeburn  6364:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 6365:     my $ver_orguri=$uri;
1.439     www      6366:     $uri=&deversion($uri);
1.152     www      6367:     my $orguri=$uri;
1.52      www      6368:     $uri=&declutter($uri);
1.809     raeburn  6369: 
1.810     raeburn  6370:     if ($priv eq 'evb') {
                   6371: # Evade communication block restrictions for specified role in a course
                   6372:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6373:             return $1;
                   6374:         } else {
                   6375:             return;
                   6376:         }
                   6377:     }
                   6378: 
1.620     albertel 6379:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6380: # Free bre access to adm and meta resources
1.775     albertel 6381:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6382: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6383: 	&& ($priv eq 'bre')) {
1.14      www      6384: 	return 'F';
1.159     www      6385:     }
                   6386: 
1.545     banghart 6387: # Free bre access to user's own portfolio contents
1.714     raeburn  6388:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6389:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6390: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6391:         my %setters;
                   6392:         my ($startblock,$endblock) = 
                   6393:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6394:         if ($startblock && $endblock) {
                   6395:             return 'B';
                   6396:         } else {
                   6397:             return 'F';
                   6398:         }
1.545     banghart 6399:     }
                   6400: 
1.762     raeburn  6401: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6402:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6403:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6404:         if (exists($env{'request.course.id'})) {
                   6405:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6406:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6407:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6408:                 my $courseprivid=$env{'request.course.id'};
                   6409:                 $courseprivid=~s/\_/\//;
                   6410:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6411:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6412:                     return $1; 
1.762     raeburn  6413:                 } else {
                   6414:                     if ($env{'request.course.sec'}) {
                   6415:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6416:                     }
                   6417:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6418:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6419:                         return $2;
                   6420:                     }
1.714     raeburn  6421:                 }
                   6422:             }
                   6423:         }
                   6424:     }
                   6425: 
1.159     www      6426: # Free bre to public access
                   6427: 
                   6428:     if ($priv eq 'bre') {
1.238     www      6429:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6430: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6431:            return 'F'; 
                   6432:         }
1.238     www      6433:         if ($copyright eq 'priv') {
                   6434:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6435: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6436: 		return '';
                   6437:             }
                   6438:         }
                   6439:         if ($copyright eq 'domain') {
                   6440:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6441: 	    unless (($env{'user.domain'} eq $1) ||
                   6442:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6443: 		return '';
                   6444:             }
1.262     matthew  6445:         }
1.620     albertel 6446:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6447:             # Library role, so allow browsing of resources in this domain.
                   6448:             return 'F';
1.238     www      6449:         }
1.341     www      6450:         if ($copyright eq 'custom') {
                   6451: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6452:         }
1.14      www      6453:     }
1.264     matthew  6454:     # Domain coordinator is trying to create a course
1.620     albertel 6455:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6456:         # uri is the requested domain in this case.
                   6457:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6458:         # a role of dc for the domain in question.
1.620     albertel 6459:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6460:     }
1.29      www      6461: 
1.52      www      6462:     my $thisallowed='';
                   6463:     my $statecond=0;
                   6464:     my $courseprivid='';
                   6465: 
1.1039    raeburn  6466:     my $ownaccess;
1.1043    raeburn  6467:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6468:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6469:         if ($uri eq '') {
                   6470:             $ownaccess = 1;
                   6471:         } else {
                   6472:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6473:                 my $udom = $env{'user.domain'};
                   6474:                 my $uname = $env{'user.name'};
                   6475:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6476:                     $ownaccess = 1;
1.1040    raeburn  6477:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6478:                     unless ($uri =~ m{\.\./}) {
                   6479:                         $ownaccess = 1;
                   6480:                     }
                   6481:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6482:                     my $now = time;
                   6483:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6484:                         my $adom = $1;
                   6485:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6486:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6487:                                 my ($start,$end) = split('.',$env{$key});
                   6488:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6489:                                     $ownaccess = 1;
                   6490:                                     last;
                   6491:                                 }
                   6492:                             }
                   6493:                         }
                   6494:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6495:                         my $adom = $1;
                   6496:                         my $aname = $2;
1.1042    raeburn  6497:                         foreach my $role ('ca','aa') { 
                   6498:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6499:                                 my ($start,$end) =
                   6500:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6501:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6502:                                     $ownaccess = 1;
                   6503:                                     last;
                   6504:                                 }
1.1039    raeburn  6505:                             }
                   6506:                         }
                   6507:                     }
                   6508:                 }
                   6509:             }
                   6510:         }
                   6511:     }
                   6512: 
1.52      www      6513: # Course
                   6514: 
1.620     albertel 6515:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6516:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6517:             $thisallowed.=$1;
                   6518:         }
1.52      www      6519:     }
1.29      www      6520: 
1.52      www      6521: # Domain
                   6522: 
1.620     albertel 6523:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6524:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6525:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6526:             $thisallowed.=$1;
                   6527:         }
1.12      www      6528:     }
1.52      www      6529: 
1.1141    raeburn  6530: # User who is not author or co-author might still be able to edit
                   6531: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6532:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6533:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6534:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6535:             $thisallowed.=$1;
                   6536:         }
                   6537:     }
                   6538: 
1.52      www      6539: # Course: uri itself is a course
1.66      www      6540:     my $courseuri=$uri;
                   6541:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6542:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6543: 
1.620     albertel 6544:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6545:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6546:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6547:             $thisallowed.=$1;
                   6548:         }
1.12      www      6549:     }
1.29      www      6550: 
1.665     albertel 6551: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6552: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6553:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6554: 	$thisallowed='';
1.671     raeburn  6555:         my ($match)=&is_on_map($uri);
                   6556:         if ($match) {
                   6557:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6558:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6559:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6560:                 if (@blockers > 0) {
                   6561:                     $thisallowed = 'B';
                   6562:                 } else {
                   6563:                     $thisallowed.=$1;
                   6564:                 }
1.671     raeburn  6565:             }
                   6566:         } else {
1.705     albertel 6567:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6568:             if ($refuri) {
                   6569:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6570:                     $thisallowed='F';
1.671     raeburn  6571:                 } else {
                   6572:                     $refuri=&declutter($refuri);
                   6573:                     my ($match) = &is_on_map($refuri);
                   6574:                     if ($match) {
1.1162    raeburn  6575:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6576:                         if (@blockers > 0) {
                   6577:                             $thisallowed = 'B';
                   6578:                         } else {
                   6579:                             $thisallowed='F';
                   6580:                         }
1.671     raeburn  6581:                     }
1.669     raeburn  6582:                 }
1.671     raeburn  6583:             }
                   6584:         }
1.314     www      6585:     }
1.492     albertel 6586: 
1.766     albertel 6587:     if ($priv eq 'bre'
                   6588: 	&& $thisallowed ne 'F' 
                   6589: 	&& $thisallowed ne '2'
                   6590: 	&& &is_portfolio_url($uri)) {
                   6591: 	$thisallowed = &portfolio_access($uri);
                   6592:     }
                   6593:     
1.52      www      6594: # Full access at system, domain or course-wide level? Exit.
1.29      www      6595:     if ($thisallowed=~/F/) {
                   6596: 	return 'F';
                   6597:     }
                   6598: 
1.52      www      6599: # If this is generating or modifying users, exit with special codes
1.29      www      6600: 
1.643     www      6601:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6602: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6603: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6604: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6605: 	    unless ($auname) { return $thisallowed; }
                   6606: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6607: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6608: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6609: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6610: 	}
1.52      www      6611: 	return $thisallowed;
                   6612:     }
                   6613: #
1.103     harris41 6614: # Gathered so far: system, domain and course wide privileges
1.52      www      6615: #
                   6616: # Course: See if uri or referer is an individual resource that is part of 
                   6617: # the course
                   6618: 
1.620     albertel 6619:     if ($env{'request.course.id'}) {
1.232     www      6620: 
1.620     albertel 6621:        $courseprivid=$env{'request.course.id'};
                   6622:        if ($env{'request.course.sec'}) {
                   6623:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6624:        }
                   6625:        $courseprivid=~s/\_/\//;
                   6626:        my $checkreferer=1;
1.232     www      6627:        my ($match,$cond)=&is_on_map($uri);
                   6628:        if ($match) {
                   6629:            $statecond=$cond;
1.620     albertel 6630:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6631:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6632:                my $value = $1;
                   6633:                if ($priv eq 'bre') {
                   6634:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6635:                    if (@blockers > 0) {
                   6636:                        $thisallowed = 'B';
                   6637:                    } else {
                   6638:                        $thisallowed.=$value;
                   6639:                    }
                   6640:                } else {
                   6641:                    $thisallowed.=$value;
                   6642:                }
1.52      www      6643:                $checkreferer=0;
                   6644:            }
1.29      www      6645:        }
1.83      www      6646:        
1.148     www      6647:        if ($checkreferer) {
1.620     albertel 6648: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6649:             unless ($refuri) {
1.800     albertel 6650:                 foreach my $key (keys(%env)) {
                   6651: 		    if ($key=~/^httpref\..*\*/) {
                   6652: 			my $pattern=$key;
1.156     www      6653:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6654:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6655:                         $pattern=~s/\//\\\//g;
1.152     www      6656:                         if ($orguri=~/$pattern/) {
1.800     albertel 6657: 			    $refuri=$env{$key};
1.148     www      6658:                         }
                   6659:                     }
1.191     harris41 6660:                 }
1.148     www      6661:             }
1.232     www      6662: 
1.148     www      6663:          if ($refuri) { 
1.152     www      6664: 	  $refuri=&declutter($refuri);
1.232     www      6665:           my ($match,$cond)=&is_on_map($refuri);
                   6666:             if ($match) {
                   6667:               my $refstatecond=$cond;
1.620     albertel 6668:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6669:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6670:                   my $value = $1;
                   6671:                   if ($priv eq 'bre') {
                   6672:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6673:                       if (@blockers > 0) {
                   6674:                           $thisallowed = 'B';
                   6675:                       } else {
                   6676:                           $thisallowed.=$value;
                   6677:                       }
                   6678:                   } else {
                   6679:                       $thisallowed.=$value;
                   6680:                   }
1.53      www      6681:                   $uri=$refuri;
                   6682:                   $statecond=$refstatecond;
1.52      www      6683:               }
                   6684:           }
1.148     www      6685:         }
1.29      www      6686:        }
1.52      www      6687:    }
1.29      www      6688: 
1.52      www      6689: #
1.103     harris41 6690: # Gathered now: all privileges that could apply, and condition number
1.52      www      6691: # 
                   6692: #
                   6693: # Full or no access?
                   6694: #
1.29      www      6695: 
1.52      www      6696:     if ($thisallowed=~/F/) {
                   6697: 	return 'F';
                   6698:     }
1.29      www      6699: 
1.52      www      6700:     unless ($thisallowed) {
                   6701:         return '';
                   6702:     }
1.29      www      6703: 
1.52      www      6704: # Restrictions exist, deal with them
                   6705: #
                   6706: #   C:according to course preferences
                   6707: #   R:according to resource settings
                   6708: #   L:unless locked
                   6709: #   X:according to user session state
                   6710: #
                   6711: 
                   6712: # Possibly locked functionality, check all courses
1.54      www      6713: # Locks might take effect only after 10 minutes cache expiration for other
                   6714: # courses, and 2 minutes for current course
1.52      www      6715: 
                   6716:     my $envkey;
                   6717:     if ($thisallowed=~/L/) {
1.1000    raeburn  6718:         foreach $envkey (keys(%env)) {
1.54      www      6719:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6720:                my $courseid=$2;
                   6721:                my $roleid=$1.'.'.$2;
1.92      www      6722:                $courseid=~s/^\///;
1.54      www      6723:                my $expiretime=600;
1.620     albertel 6724:                if ($env{'request.role'} eq $roleid) {
1.54      www      6725: 		  $expiretime=120;
                   6726:                }
                   6727: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   6728:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 6729:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 6730: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      6731:                }
1.620     albertel 6732:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6733:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   6734: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   6735:                        &log($env{'user.domain'},$env{'user.name'},
                   6736:                             $env{'user.home'},
1.57      www      6737:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      6738:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6739:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6740: 		       return '';
                   6741:                    }
                   6742:                }
1.620     albertel 6743:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6744:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   6745: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   6746:                        &log($env{'user.domain'},$env{'user.name'},
                   6747:                             $env{'user.home'},
1.57      www      6748:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      6749:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6750:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6751: 		       return '';
                   6752:                    }
                   6753:                }
                   6754: 	   }
1.29      www      6755:        }
1.52      www      6756:     }
                   6757:    
                   6758: #
                   6759: # Rest of the restrictions depend on selected course
                   6760: #
                   6761: 
1.620     albertel 6762:     unless ($env{'request.course.id'}) {
1.766     albertel 6763: 	if ($thisallowed eq 'A') {
                   6764: 	    return 'A';
1.814     raeburn  6765:         } elsif ($thisallowed eq 'B') {
                   6766:             return 'B';
1.766     albertel 6767: 	} else {
                   6768: 	    return '1';
                   6769: 	}
1.52      www      6770:     }
1.29      www      6771: 
1.52      www      6772: #
                   6773: # Now user is definitely in a course
                   6774: #
1.53      www      6775: 
                   6776: 
                   6777: # Course preferences
                   6778: 
                   6779:    if ($thisallowed=~/C/) {
1.620     albertel 6780:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   6781:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   6782:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 6783: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  6784: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6785: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6786: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   6787: 			$env{'request.course.id'});
                   6788: 	   }
1.237     www      6789:            return '';
                   6790:        }
                   6791: 
1.620     albertel 6792:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 6793: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  6794: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6795: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   6796: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   6797: 			$env{'request.course.id'});
                   6798: 	   }
1.54      www      6799:            return '';
                   6800:        }
1.53      www      6801:    }
                   6802: 
                   6803: # Resource preferences
                   6804: 
                   6805:    if ($thisallowed=~/R/) {
1.620     albertel 6806:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 6807:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  6808: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6809: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6810: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   6811: 	   }
                   6812: 	   return '';
1.54      www      6813:        }
1.53      www      6814:    }
1.30      www      6815: 
1.246     www      6816: # Restricted by state or randomout?
1.30      www      6817: 
1.52      www      6818:    if ($thisallowed=~/X/) {
1.620     albertel 6819:       if ($env{'acc.randomout'}) {
1.579     albertel 6820: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 6821:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      6822:             return ''; 
                   6823:          }
1.247     www      6824:       }
                   6825:       if (&condval($statecond)) {
1.52      www      6826: 	 return '2';
                   6827:       } else {
                   6828:          return '';
                   6829:       }
                   6830:    }
1.30      www      6831: 
1.766     albertel 6832:     if ($thisallowed eq 'A') {
                   6833: 	return 'A';
1.814     raeburn  6834:     } elsif ($thisallowed eq 'B') {
                   6835:         return 'B';
1.766     albertel 6836:     }
1.52      www      6837:    return 'F';
1.232     www      6838: }
1.1162    raeburn  6839: 
1.1172.2.13  raeburn  6840: # ------------------------------------------- Check construction space access
                   6841: 
                   6842: sub constructaccess {
                   6843:     my ($url,$setpriv)=@_;
                   6844: 
                   6845: # We do not allow editing of previous versions of files
                   6846:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   6847: 
                   6848: # Get username and domain from URL
                   6849:     my ($ownername,$ownerdomain,$ownerhome);
                   6850: 
                   6851:     ($ownerdomain,$ownername) =
                   6852:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
                   6853: 
                   6854: # The URL does not really point to any authorspace, forget it
                   6855:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   6856: 
                   6857: # Now we need to see if the user has access to the authorspace of
                   6858: # $ownername at $ownerdomain
                   6859: 
                   6860:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   6861: # Real author for this?
                   6862:        $ownerhome = $env{'user.home'};
                   6863:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   6864:           return ($ownername,$ownerdomain,$ownerhome);
                   6865:        }
                   6866:     } else {
                   6867: # Co-author for this?
                   6868:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   6869:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   6870:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   6871:             return ($ownername,$ownerdomain,$ownerhome);
                   6872:         }
                   6873:     }
                   6874: 
                   6875: # We don't have any access right now. If we are not possibly going to do anything about this,
                   6876: # we might as well leave
                   6877:    unless ($setpriv) { return ''; }
                   6878: 
                   6879: # Backdoor access?
                   6880:     my $allowed=&allowed('eco',$ownerdomain);
                   6881: # Nope
                   6882:     unless ($allowed) { return ''; }
                   6883: # Looks like we may have access, but could be locked by the owner of the construction space
                   6884:     if ($allowed eq 'U') {
                   6885:         my %blocked=&get('environment',['domcoord.author'],
                   6886:                          $ownerdomain,$ownername);
                   6887: # Is blocked by owner
                   6888:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   6889:     }
                   6890:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   6891: # Grant temporary access
                   6892:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  6893:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  6894:         if (!$update) { $update = $then; }
                   6895:         my $refresh=$env{'user.refresh.time'};
                   6896:         if (!$refresh) { $refresh = $update; }
                   6897:         my $now = time;
                   6898:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   6899:                            $now,'ca','constructaccess');
                   6900:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   6901:         return($ownername,$ownerdomain,$ownerhome);
                   6902:     }
                   6903: # No business here
                   6904:     return '';
                   6905: }
                   6906: 
1.1162    raeburn  6907: sub get_comm_blocks {
                   6908:     my ($cdom,$cnum) = @_;
                   6909:     if ($cdom eq '' || $cnum eq '') {
                   6910:         return unless ($env{'request.course.id'});
                   6911:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6912:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6913:     }
                   6914:     my %commblocks;
                   6915:     my $hashid=$cdom.'_'.$cnum;
                   6916:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   6917:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   6918:         %commblocks = %{$blocksref};
                   6919:     } else {
                   6920:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   6921:         my $cachetime = 600;
                   6922:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   6923:     }
                   6924:     return %commblocks;
                   6925: }
                   6926: 
                   6927: sub has_comm_blocking {
                   6928:     my ($priv,$symb,$uri,$blocks) = @_;
                   6929:     return unless ($env{'request.course.id'});
                   6930:     return unless ($priv eq 'bre');
                   6931:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   6932:     my %commblocks;
                   6933:     if (ref($blocks) eq 'HASH') {
                   6934:         %commblocks = %{$blocks};
                   6935:     } else {
                   6936:         %commblocks = &get_comm_blocks();
                   6937:     }
                   6938:     return unless (keys(%commblocks) > 0);
                   6939:     if (!$symb) { $symb=&symbread($uri,1); }
                   6940:     my ($map,$resid,undef)=&decode_symb($symb);
                   6941:     my %tocheck = (
                   6942:                     maps      => $map,
                   6943:                     resources => $symb,
                   6944:                   );
                   6945:     my @blockers;
                   6946:     my $now = time;
1.1163    raeburn  6947:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1162    raeburn  6948:     foreach my $block (keys(%commblocks)) {
                   6949:         if ($block =~ /^(\d+)____(\d+)$/) {
                   6950:             my ($start,$end) = ($1,$2);
                   6951:             if ($start <= $now && $end >= $now) {
                   6952:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6953:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   6954:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   6955:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
                   6956:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   6957:                                     push(@blockers,$block);
                   6958:                                 }
                   6959:                             }
                   6960:                         }
                   6961:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   6962:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
                   6963:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
                   6964:                                     push(@blockers,$block);
                   6965:                                 }
                   6966:                             }
                   6967:                         }
                   6968:                     }
                   6969:                 }
                   6970:             }
                   6971:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   6972:             my $item = $1;
1.1163    raeburn  6973:             my @to_test;
1.1162    raeburn  6974:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6975:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   6976:                     my $check_interval;
                   6977:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
                   6978:                         my @interval;
                   6979:                         my $type = 'map';
                   6980:                         if ($item eq 'course') {
                   6981:                             $type = 'course';
                   6982:                             @interval=&EXT("resource.0.interval");
                   6983:                         } else {
                   6984:                             if ($item =~ /___\d+___/) {
                   6985:                                 $type = 'resource';
                   6986:                                 @interval=&EXT("resource.0.interval",$item);
1.1163    raeburn  6987:                                 if (ref($navmap)) {                        
                   6988:                                     my $res = $navmap->getBySymb($item); 
                   6989:                                     push(@to_test,$res);
                   6990:                                 }
1.1162    raeburn  6991:                             } else {
                   6992:                                 my $mapsymb = &symbread($item,1);
                   6993:                                 if ($mapsymb) {
                   6994:                                     if (ref($navmap)) {
                   6995:                                         my $mapres = $navmap->getBySymb($mapsymb);
1.1163    raeburn  6996:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
                   6997:                                         foreach my $res (@to_test) {
1.1162    raeburn  6998:                                             my $symb = $res->symb();
                   6999:                                             next if ($symb eq $mapsymb);
                   7000:                                             if ($symb ne '') {
                   7001:                                                 @interval=&EXT("resource.0.interval",$symb);
                   7002:                                                 last;
                   7003:                                             }
                   7004:                                         }
                   7005:                                     }
                   7006:                                 }
                   7007:                             }
                   7008:                         }
                   7009:                         if ($interval[0] =~ /\d+/) {
                   7010:                             my $first_access;
                   7011:                             if ($type eq 'resource') {
                   7012:                                 $first_access=&get_first_access($interval[1],$item);
                   7013:                             } elsif ($type eq 'map') {
                   7014:                                 $first_access=&get_first_access($interval[1],undef,$item);
                   7015:                             } else {
                   7016:                                 $first_access=&get_first_access($interval[1]);
                   7017:                             }
                   7018:                             if ($first_access) {
                   7019:                                 my $timesup = $first_access+$interval[0];
                   7020:                                 if ($timesup > $now) {
1.1163    raeburn  7021:                                     foreach my $res (@to_test) {
                   7022:                                         if ($res->is_problem()) {
                   7023:                                             if ($res->completable()) {
                   7024:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7025:                                                     push(@blockers,$block);
                   7026:                                                 }
                   7027:                                                 last;
                   7028:                                             }
                   7029:                                         }
1.1162    raeburn  7030:                                     }
                   7031:                                 }
                   7032:                             }
                   7033:                         }
                   7034:                     }
                   7035:                 }
                   7036:             }
                   7037:         }
                   7038:     }
                   7039:     return @blockers;
                   7040: }
                   7041: 
                   7042: sub check_docs_block {
                   7043:     my ($docsblock,$tocheck) =@_;
                   7044:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
                   7045:         return;
                   7046:     }
                   7047:     if (ref($docsblock->{'maps'}) eq 'HASH') {
                   7048:         if ($tocheck->{'maps'}) {
                   7049:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
                   7050:                 return 1;
                   7051:             }
                   7052:         }
                   7053:     }
                   7054:     if (ref($docsblock->{'resources'}) eq 'HASH') {
                   7055:         if ($tocheck->{'resources'}) {
                   7056:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
                   7057:                 return 1;
                   7058:             }
                   7059:         }
                   7060:     }
                   7061:     return;
                   7062: }
                   7063: 
1.1133    foxr     7064: #
                   7065: #   Removes the versino from a URI and
                   7066: #   splits it in to its filename and path to the filename.
                   7067: #   Seems like File::Basename could have done this more clearly.
                   7068: #   Parameters:
                   7069: #      $uri   - input URI
                   7070: #   Returns:
                   7071: #     Two element list consisting of 
                   7072: #     $pathname  - the URI up to and excluding the trailing /
                   7073: #     $filename  - The part of the URI following the last /
                   7074: #  NOTE:
                   7075: #    Another realization of this is simply:
                   7076: #    use File::Basename;
                   7077: #    ...
                   7078: #    $uri = shift;
                   7079: #    $filename = basename($uri);
                   7080: #    $path     = dirname($uri);
                   7081: #    return ($filename, $path);
                   7082: #
                   7083: #     The implementation below is probably faster however.
                   7084: #
1.710     albertel 7085: sub split_uri_for_cond {
                   7086:     my $uri=&deversion(&declutter(shift));
                   7087:     my @uriparts=split(/\//,$uri);
                   7088:     my $filename=pop(@uriparts);
                   7089:     my $pathname=join('/',@uriparts);
                   7090:     return ($pathname,$filename);
                   7091: }
1.232     www      7092: # --------------------------------------------------- Is a resource on the map?
                   7093: 
                   7094: sub is_on_map {
1.710     albertel 7095:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7096:     #Trying to find the conditional for the file
1.620     albertel 7097:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7098: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7099:     if ($match) {
1.289     bowersj2 7100: 	return (1,$1);
                   7101:     } else {
1.434     www      7102: 	return (0,0);
1.289     bowersj2 7103:     }
1.12      www      7104: }
                   7105: 
1.427     www      7106: # --------------------------------------------------------- Get symb from alias
                   7107: 
                   7108: sub get_symb_from_alias {
                   7109:     my $symb=shift;
                   7110:     my ($map,$resid,$url)=&decode_symb($symb);
                   7111: # Already is a symb
                   7112:     if ($url) { return $symb; }
                   7113: # Must be an alias
                   7114:     my $aliassymb='';
                   7115:     my %bighash;
1.620     albertel 7116:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7117:                             &GDBM_READER(),0640)) {
                   7118:         my $rid=$bighash{'mapalias_'.$symb};
                   7119: 	if ($rid) {
                   7120: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7121: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7122: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7123: 	}
                   7124:         untie %bighash;
                   7125:     }
                   7126:     return $aliassymb;
                   7127: }
                   7128: 
1.12      www      7129: # ----------------------------------------------------------------- Define Role
                   7130: 
                   7131: sub definerole {
                   7132:   if (allowed('mcr','/')) {
                   7133:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7134:     foreach my $role (split(':',$sysrole)) {
                   7135: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7136:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7137:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7138: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7139:                return "refused:s:$crole&$cqual"; 
                   7140:             }
                   7141:         }
1.191     harris41 7142:     }
1.800     albertel 7143:     foreach my $role (split(':',$domrole)) {
                   7144: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7145:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7146:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7147: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7148:                return "refused:d:$crole&$cqual"; 
                   7149:             }
                   7150:         }
1.191     harris41 7151:     }
1.800     albertel 7152:     foreach my $role (split(':',$courole)) {
                   7153: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7154:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7155:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7156: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7157:                return "refused:c:$crole&$cqual"; 
                   7158:             }
                   7159:         }
1.191     harris41 7160:     }
1.620     albertel 7161:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7162:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7163: 	        "rolesdef_$rolename=".
                   7164:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7165:     return reply($command,$env{'user.home'});
1.12      www      7166:   } else {
                   7167:     return 'refused';
                   7168:   }
1.105     harris41 7169: }
                   7170: 
                   7171: # ---------------- Make a metadata query against the network of library servers
                   7172: 
                   7173: sub metadata_query {
1.244     matthew  7174:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 7175:     my %rhash;
1.845     albertel 7176:     my %libserv = &all_library();
1.244     matthew  7177:     my @server_list = (defined($server_array) ? @$server_array
                   7178:                                               : keys(%libserv) );
                   7179:     for my $server (@server_list) {
1.118     harris41 7180: 	unless ($custom or $customshow) {
                   7181: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   7182: 	    $rhash{$server}=$reply;
                   7183: 	}
                   7184: 	else {
                   7185: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   7186: 			     &escape($custom).':'.&escape($customshow),
                   7187: 			     $server);
                   7188: 	    $rhash{$server}=$reply;
                   7189: 	}
1.112     harris41 7190:     }
1.118     harris41 7191:     return \%rhash;
1.240     www      7192: }
                   7193: 
                   7194: # ----------------------------------------- Send log queries and wait for reply
                   7195: 
                   7196: sub log_query {
                   7197:     my ($uname,$udom,$query,%filters)=@_;
                   7198:     my $uhome=&homeserver($uname,$udom);
                   7199:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7200:     my $uhost=&hostname($uhome);
1.800     albertel 7201:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7202:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7203:                        $uhome);
1.479     albertel 7204:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7205:     return get_query_reply($queryid);
                   7206: }
                   7207: 
1.818     raeburn  7208: # -------------------------- Update MySQL table for portfolio file
                   7209: 
                   7210: sub update_portfolio_table {
1.821     raeburn  7211:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7212:     if ($group ne '') {
                   7213:         $file_name =~s /^\Q$group\E//;
                   7214:     }
1.818     raeburn  7215:     my $homeserver = &homeserver($uname,$udom);
                   7216:     my $queryid=
1.821     raeburn  7217:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7218:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7219:     my $reply = &get_query_reply($queryid);
                   7220:     return $reply;
                   7221: }
                   7222: 
1.899     raeburn  7223: # -------------------------- Update MySQL allusers table
                   7224: 
                   7225: sub update_allusers_table {
                   7226:     my ($uname,$udom,$names) = @_;
                   7227:     my $homeserver = &homeserver($uname,$udom);
                   7228:     my $queryid=
                   7229:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7230:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7231:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7232:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7233:                'generation='.&escape($names->{'generation'}).'%%'.
                   7234:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7235:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7236:     return;
1.899     raeburn  7237: }
                   7238: 
1.508     raeburn  7239: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7240: 
                   7241: sub fetch_enrollment_query {
1.511     raeburn  7242:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  7243:     my $homeserver;
1.547     raeburn  7244:     my $maxtries = 1;
1.508     raeburn  7245:     if ($context eq 'automated') {
                   7246:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  7247:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7248:     } else {
                   7249:         $homeserver = &homeserver($cnum,$dom);
                   7250:     }
1.838     albertel 7251:     my $host=&hostname($homeserver);
1.506     raeburn  7252:     my $cmd = '';
1.1000    raeburn  7253:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7254:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7255:     }
                   7256:     $cmd =~ s/%%$//;
                   7257:     $cmd = &escape($cmd);
                   7258:     my $query = 'fetchenrollment';
1.620     albertel 7259:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7260:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7261:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7262:         return 'error: '.$queryid;
                   7263:     }
1.506     raeburn  7264:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7265:     my $tries = 1;
                   7266:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7267:         $reply = &get_query_reply($queryid);
                   7268:         $tries ++;
                   7269:     }
1.526     raeburn  7270:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7271:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7272:     } else {
1.901     albertel 7273:         my @responses = split(/:/,$reply);
1.515     raeburn  7274:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7275:             foreach my $line (@responses) {
                   7276:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7277:                 $$replyref{$key} = $value;
                   7278:             }
                   7279:         } else {
1.1117    foxr     7280:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7281:             foreach my $line (@responses) {
                   7282:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7283:                 $$replyref{$key} = $value;
                   7284:                 if ($value > 0) {
1.800     albertel 7285:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7286:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7287:                         my $destname = $pathname.'/'.$filename;
                   7288:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7289:                         if ($xml_classlist =~ /^error/) {
                   7290:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7291:                         } else {
1.506     raeburn  7292:                             if ( open(FILE,">$destname") ) {
                   7293:                                 print FILE &unescape($xml_classlist);
                   7294:                                 close(FILE);
1.526     raeburn  7295:                             } else {
                   7296:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7297:                             }
                   7298:                         }
                   7299:                     }
                   7300:                 }
                   7301:             }
                   7302:         }
                   7303:         return 'ok';
                   7304:     }
                   7305:     return 'error';
                   7306: }
                   7307: 
1.242     www      7308: sub get_query_reply {
                   7309:     my $queryid=shift;
1.1117    foxr     7310:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7311:     my $reply='';
                   7312:     for (1..100) {
                   7313: 	sleep 2;
                   7314:         if (-e $replyfile.'.end') {
1.448     albertel 7315: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7316: 		$reply = join('',<$fh>);
                   7317: 		close($fh);
1.240     www      7318: 	   } else { return 'error: reply_file_error'; }
1.242     www      7319:            return &unescape($reply);
                   7320: 	}
1.240     www      7321:     }
1.242     www      7322:     return 'timeout:'.$queryid;
1.240     www      7323: }
                   7324: 
                   7325: sub courselog_query {
1.241     www      7326: #
                   7327: # possible filters:
                   7328: # url: url or symb
                   7329: # username
                   7330: # domain
                   7331: # action: view, submit, grade
                   7332: # start: timestamp
                   7333: # end: timestamp
                   7334: #
1.240     www      7335:     my (%filters)=@_;
1.620     albertel 7336:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7337:     if ($filters{'url'}) {
                   7338: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7339:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7340:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7341:     }
1.620     albertel 7342:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7343:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7344:     return &log_query($cname,$cdom,'courselog',%filters);
                   7345: }
                   7346: 
                   7347: sub userlog_query {
1.858     raeburn  7348: #
                   7349: # possible filters:
                   7350: # action: log check role
                   7351: # start: timestamp
                   7352: # end: timestamp
                   7353: #
1.240     www      7354:     my ($uname,$udom,%filters)=@_;
                   7355:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7356: }
                   7357: 
1.506     raeburn  7358: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7359: 
                   7360: sub auto_run {
1.508     raeburn  7361:     my ($cnum,$cdom) = @_;
1.876     raeburn  7362:     my $response = 0;
                   7363:     my $settings;
                   7364:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7365:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7366:         $settings = $domconfig{'autoenroll'};
                   7367:         if ($settings->{'run'} eq '1') {
                   7368:             $response = 1;
                   7369:         }
                   7370:     } else {
1.934     raeburn  7371:         my $homeserver;
                   7372:         if (&is_course($cdom,$cnum)) {
                   7373:             $homeserver = &homeserver($cnum,$cdom);
                   7374:         } else {
                   7375:             $homeserver = &domain($cdom,'primary');
                   7376:         }
                   7377:         if ($homeserver ne 'no_host') {
                   7378:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7379:         }
1.876     raeburn  7380:     }
1.506     raeburn  7381:     return $response;
                   7382: }
1.776     albertel 7383: 
1.506     raeburn  7384: sub auto_get_sections {
1.508     raeburn  7385:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7386:     my $homeserver;
                   7387:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7388:         $homeserver = &homeserver($cnum,$cdom);
                   7389:     }
                   7390:     if (!defined($homeserver)) { 
                   7391:         if ($cdom =~ /^$match_domain$/) {
                   7392:             $homeserver = &domain($cdom,'primary');
                   7393:         }
                   7394:     }
                   7395:     my @secs;
                   7396:     if (defined($homeserver)) {
                   7397:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7398:         unless ($response eq 'refused') {
                   7399:             @secs = split(/:/,$response);
                   7400:         }
1.506     raeburn  7401:     }
                   7402:     return @secs;
                   7403: }
1.776     albertel 7404: 
1.506     raeburn  7405: sub auto_new_course {
1.1099    raeburn  7406:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7407:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7408:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7409:     return $response;
                   7410: }
1.776     albertel 7411: 
1.506     raeburn  7412: sub auto_validate_courseID {
1.508     raeburn  7413:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7414:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7415:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7416:     return $response;
                   7417: }
1.776     albertel 7418: 
1.1007    raeburn  7419: sub auto_validate_instcode {
1.1020    raeburn  7420:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7421:     my ($homeserver,$response);
                   7422:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7423:         $homeserver = &homeserver($cnum,$cdom);
                   7424:     }
                   7425:     if (!defined($homeserver)) {
                   7426:         if ($cdom =~ /^$match_domain$/) {
                   7427:             $homeserver = &domain($cdom,'primary');
                   7428:         }
                   7429:     }
1.1065    raeburn  7430:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7431:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  7432:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   7433:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  7434: }
                   7435: 
1.506     raeburn  7436: sub auto_create_password {
1.873     raeburn  7437:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7438:     my ($homeserver,$response);
1.506     raeburn  7439:     my $create_passwd = 0;
                   7440:     my $authchk = '';
1.873     raeburn  7441:     if ($udom =~ /^$match_domain$/) {
                   7442:         $homeserver = &domain($udom,'primary');
                   7443:     }
                   7444:     if ($homeserver eq '') {
                   7445:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7446:             $homeserver = &homeserver($cnum,$cdom);
                   7447:         }
                   7448:     }
                   7449:     if ($homeserver eq '') {
                   7450:         $authchk = 'nodomain';
1.506     raeburn  7451:     } else {
1.873     raeburn  7452:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   7453:         if ($response eq 'refused') {
                   7454:             $authchk = 'refused';
                   7455:         } else {
1.901     albertel 7456:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  7457:         }
1.506     raeburn  7458:     }
                   7459:     return ($authparam,$create_passwd,$authchk);
                   7460: }
                   7461: 
1.706     raeburn  7462: sub auto_photo_permission {
                   7463:     my ($cnum,$cdom,$students) = @_;
                   7464:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 7465:     my ($outcome,$perm_reqd,$conditions) = 
                   7466: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 7467:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7468: 	return (undef,undef);
                   7469:     }
1.706     raeburn  7470:     return ($outcome,$perm_reqd,$conditions);
                   7471: }
                   7472: 
                   7473: sub auto_checkphotos {
                   7474:     my ($uname,$udom,$pid) = @_;
                   7475:     my $homeserver = &homeserver($uname,$udom);
                   7476:     my ($result,$resulttype);
                   7477:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 7478: 				   &escape($uname).':'.&escape($pid),
                   7479: 				   $homeserver));
1.709     albertel 7480:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7481: 	return (undef,undef);
                   7482:     }
1.706     raeburn  7483:     if ($outcome) {
                   7484:         ($result,$resulttype) = split(/:/,$outcome);
                   7485:     } 
                   7486:     return ($result,$resulttype);
                   7487: }
                   7488: 
                   7489: sub auto_photochoice {
                   7490:     my ($cnum,$cdom) = @_;
                   7491:     my $homeserver = &homeserver($cnum,$cdom);
                   7492:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 7493: 						       &escape($cdom),
                   7494: 						       $homeserver)));
1.709     albertel 7495:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7496: 	return (undef,undef);
                   7497:     }
1.706     raeburn  7498:     return ($update,$comment);
                   7499: }
                   7500: 
                   7501: sub auto_photoupdate {
                   7502:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   7503:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 7504:     my $host=&hostname($homeserver);
1.706     raeburn  7505:     my $cmd = '';
                   7506:     my $maxtries = 1;
1.800     albertel 7507:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   7508:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  7509:     }
                   7510:     $cmd =~ s/%%$//;
                   7511:     $cmd = &escape($cmd);
                   7512:     my $query = 'institutionalphotos';
                   7513:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7514:     unless ($queryid=~/^\Q$host\E\_/) {
                   7515:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7516:         return 'error: '.$queryid;
                   7517:     }
                   7518:     my $reply = &get_query_reply($queryid);
                   7519:     my $tries = 1;
                   7520:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7521:         $reply = &get_query_reply($queryid);
                   7522:         $tries ++;
                   7523:     }
                   7524:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7525:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7526:     } else {
                   7527:         my @responses = split(/:/,$reply);
                   7528:         my $outcome = shift(@responses); 
                   7529:         foreach my $item (@responses) {
                   7530:             my ($key,$value) = split(/=/,$item);
                   7531:             $$photo{$key} = $value;
                   7532:         }
                   7533:         return $outcome;
                   7534:     }
                   7535:     return 'error';
                   7536: }
                   7537: 
1.521     raeburn  7538: sub auto_instcode_format {
1.793     albertel 7539:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7540: 	$cat_order) = @_;
1.521     raeburn  7541:     my $courses = '';
1.772     raeburn  7542:     my @homeservers;
1.521     raeburn  7543:     if ($caller eq 'global') {
1.841     albertel 7544: 	my %servers = &get_servers($codedom,'library');
                   7545: 	foreach my $tryserver (keys(%servers)) {
                   7546: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7547: 		push(@homeservers,$tryserver);
                   7548: 	    }
1.584     raeburn  7549:         }
1.1022    raeburn  7550:     } elsif ($caller eq 'requests') {
                   7551:         if ($codedom =~ /^$match_domain$/) {
                   7552:             my $chome = &domain($codedom,'primary');
                   7553:             unless ($chome eq 'no_host') {
                   7554:                 push(@homeservers,$chome);
                   7555:             }
                   7556:         }
1.521     raeburn  7557:     } else {
1.772     raeburn  7558:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7559:     }
1.793     albertel 7560:     foreach my $code (keys(%{$instcodes})) {
                   7561:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7562:     }
                   7563:     chop($courses);
1.772     raeburn  7564:     my $ok_response = 0;
                   7565:     my $response;
                   7566:     while (@homeservers > 0 && $ok_response == 0) {
                   7567:         my $server = shift(@homeservers); 
                   7568:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7569:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7570:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7571: 		split(/:/,$response);
1.772     raeburn  7572:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7573:             push(@{$codetitles},&str2array($codetitles_str));
                   7574:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   7575:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   7576:             $ok_response = 1;
                   7577:         }
                   7578:     }
                   7579:     if ($ok_response) {
1.521     raeburn  7580:         return 'ok';
1.772     raeburn  7581:     } else {
                   7582:         return $response;
1.521     raeburn  7583:     }
                   7584: }
                   7585: 
1.792     raeburn  7586: sub auto_instcode_defaults {
                   7587:     my ($domain,$returnhash,$code_order) = @_;
                   7588:     my @homeservers;
1.841     albertel 7589: 
                   7590:     my %servers = &get_servers($domain,'library');
                   7591:     foreach my $tryserver (keys(%servers)) {
                   7592: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7593: 	    push(@homeservers,$tryserver);
                   7594: 	}
1.792     raeburn  7595:     }
1.841     albertel 7596: 
1.792     raeburn  7597:     my $response;
1.841     albertel 7598:     foreach my $server (@homeservers) {
1.792     raeburn  7599:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 7600:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   7601: 	
                   7602: 	foreach my $pair (split(/\&/,$response)) {
                   7603: 	    my ($name,$value)=split(/\=/,$pair);
                   7604: 	    if ($name eq 'code_order') {
                   7605: 		@{$code_order} = split(/\&/,&unescape($value));
                   7606: 	    } else {
                   7607: 		$returnhash->{&unescape($name)}=&unescape($value);
                   7608: 	    }
                   7609: 	}
                   7610: 	return 'ok';
1.792     raeburn  7611:     }
1.841     albertel 7612: 
                   7613:     return $response;
1.1003    raeburn  7614: }
                   7615: 
                   7616: sub auto_possible_instcodes {
1.1007    raeburn  7617:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   7618:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   7619:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   7620:         return;
                   7621:     }
1.1003    raeburn  7622:     my (@homeservers,$uhome);
                   7623:     if (defined(&domain($domain,'primary'))) {
                   7624:         $uhome=&domain($domain,'primary');
                   7625:         push(@homeservers,&domain($domain,'primary'));
                   7626:     } else {
                   7627:         my %servers = &get_servers($domain,'library');
                   7628:         foreach my $tryserver (keys(%servers)) {
                   7629:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7630:                 push(@homeservers,$tryserver);
                   7631:             }
                   7632:         }
                   7633:     }
                   7634:     my $response;
                   7635:     foreach my $server (@homeservers) {
                   7636:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   7637:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  7638:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   7639:             split(':',$response);
                   7640:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   7641:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  7642:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  7643:             my ($name,$value)=split('=',$item);
                   7644:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7645:         }
                   7646:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  7647:             my ($name,$value)=split('=',$item);
                   7648:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7649:         }
                   7650:         return 'ok';
                   7651:     }
                   7652:     return $response;
                   7653: }
1.792     raeburn  7654: 
1.1010    raeburn  7655: sub auto_courserequest_checks {
                   7656:     my ($dom) = @_;
1.1020    raeburn  7657:     my ($homeserver,%validations);
                   7658:     if ($dom =~ /^$match_domain$/) {
                   7659:         $homeserver = &domain($dom,'primary');
                   7660:     }
                   7661:     unless ($homeserver eq 'no_host') {
                   7662:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   7663:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7664:             my @items = split(/&/,$response);
                   7665:             foreach my $item (@items) {
                   7666:                 my ($key,$value) = split('=',$item);
                   7667:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   7668:             }
                   7669:         }
                   7670:     }
1.1010    raeburn  7671:     return %validations; 
                   7672: }
                   7673: 
1.1020    raeburn  7674: sub auto_courserequest_validation {
                   7675:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   7676:     my ($homeserver,$response);
                   7677:     if ($dom =~ /^$match_domain$/) {
                   7678:         $homeserver = &domain($dom,'primary');
                   7679:     }
                   7680:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  7681:           
1.1020    raeburn  7682:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  7683:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  7684:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   7685:                                     $homeserver));
                   7686:     }
                   7687:     return $response;
                   7688: }
                   7689: 
1.777     albertel 7690: sub auto_validate_class_sec {
1.918     raeburn  7691:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  7692:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  7693:     my $ownerlist;
                   7694:     if (ref($owners) eq 'ARRAY') {
                   7695:         $ownerlist = join(',',@{$owners});
                   7696:     } else {
                   7697:         $ownerlist = $owners;
                   7698:     }
1.773     raeburn  7699:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  7700:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  7701:     return $response;
                   7702: }
                   7703: 
1.679     raeburn  7704: # ------------------------------------------------------- Course Group routines
                   7705: 
                   7706: sub get_coursegroups {
1.809     raeburn  7707:     my ($cdom,$cnum,$group,$namespace) = @_;
                   7708:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  7709: }
                   7710: 
1.679     raeburn  7711: sub modify_coursegroup {
                   7712:     my ($cdom,$cnum,$groupsettings) = @_;
                   7713:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   7714: }
                   7715: 
1.809     raeburn  7716: sub toggle_coursegroup_status {
                   7717:     my ($cdom,$cnum,$group,$action) = @_;
                   7718:     my ($from_namespace,$to_namespace);
                   7719:     if ($action eq 'delete') {
                   7720:         $from_namespace = 'coursegroups';
                   7721:         $to_namespace = 'deleted_groups';
                   7722:     } else {
                   7723:         $from_namespace = 'deleted_groups';
                   7724:         $to_namespace = 'coursegroups';
                   7725:     }
                   7726:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  7727:     if (my $tmp = &error(%curr_group)) {
                   7728:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   7729:         return ('read error',$tmp);
                   7730:     } else {
                   7731:         my %savedsettings = %curr_group; 
1.809     raeburn  7732:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  7733:         my $deloutcome;
                   7734:         if ($result eq 'ok') {
1.809     raeburn  7735:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  7736:         } else {
                   7737:             return ('write error',$result);
                   7738:         }
                   7739:         if ($deloutcome eq 'ok') {
                   7740:             return 'ok';
                   7741:         } else {
                   7742:             return ('delete error',$deloutcome);
                   7743:         }
                   7744:     }
                   7745: }
                   7746: 
1.679     raeburn  7747: sub modify_group_roles {
1.957     raeburn  7748:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  7749:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   7750:     my $role = 'gr/'.&escape($userprivs);
                   7751:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  7752:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  7753:     if ($result eq 'ok') {
                   7754:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   7755:     }
1.679     raeburn  7756:     return $result;
                   7757: }
                   7758: 
                   7759: sub modify_coursegroup_membership {
                   7760:     my ($cdom,$cnum,$membership) = @_;
                   7761:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   7762:     return $result;
                   7763: }
                   7764: 
1.682     raeburn  7765: sub get_active_groups {
                   7766:     my ($udom,$uname,$cdom,$cnum) = @_;
                   7767:     my $now = time;
                   7768:     my %groups = ();
                   7769:     foreach my $key (keys(%env)) {
1.811     albertel 7770:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  7771:             my ($start,$end) = split(/\./,$env{$key});
                   7772:             if (($end!=0) && ($end<$now)) { next; }
                   7773:             if (($start!=0) && ($start>$now)) { next; }
                   7774:             if ($1 eq $cdom && $2 eq $cnum) {
                   7775:                 $groups{$3} = $env{$key} ;
                   7776:             }
                   7777:         }
                   7778:     }
                   7779:     return %groups;
                   7780: }
                   7781: 
1.683     raeburn  7782: sub get_group_membership {
                   7783:     my ($cdom,$cnum,$group) = @_;
                   7784:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   7785: }
                   7786: 
                   7787: sub get_users_groups {
                   7788:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  7789:     my @usersgroups;
1.683     raeburn  7790:     my $cachetime=1800;
                   7791: 
                   7792:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  7793:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   7794:     if (defined($cached)) {
1.734     albertel 7795:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  7796:     } else {  
                   7797:         $grouplist = '';
1.816     raeburn  7798:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  7799:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  7800:         my $access_end = $env{'course.'.$courseid.
                   7801:                               '.default_enrollment_end_date'};
                   7802:         my $now = time;
                   7803:         foreach my $key (keys(%roleshash)) {
                   7804:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   7805:                 my $group = $1;
                   7806:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   7807:                     my $start = $2;
                   7808:                     my $end = $1;
                   7809:                     if ($start == -1) { next; } # deleted from group
                   7810:                     if (($start!=0) && ($start>$now)) { next; }
                   7811:                     if (($end!=0) && ($end<$now)) {
                   7812:                         if ($access_end && $access_end < $now) {
                   7813:                             if ($access_end - $end < 86400) {
                   7814:                                 push(@usersgroups,$group);
1.733     raeburn  7815:                             }
                   7816:                         }
1.817     raeburn  7817:                         next;
1.733     raeburn  7818:                     }
1.817     raeburn  7819:                     push(@usersgroups,$group);
1.683     raeburn  7820:                 }
                   7821:             }
                   7822:         }
1.817     raeburn  7823:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   7824:         $grouplist = join(':',@usersgroups);
                   7825:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  7826:     }
1.733     raeburn  7827:     return @usersgroups;
1.683     raeburn  7828: }
                   7829: 
                   7830: sub devalidate_getgroups_cache {
                   7831:     my ($udom,$uname,$cdom,$cnum)=@_;
                   7832:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 7833: 
1.683     raeburn  7834:     my $hashid="$udom:$uname:$courseid";
                   7835:     &devalidate_cache_new('getgroups',$hashid);
                   7836: }
                   7837: 
1.12      www      7838: # ------------------------------------------------------------------ Plain Text
                   7839: 
                   7840: sub plaintext {
1.988     raeburn  7841:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  7842:     if ($short =~ m{^cr/}) {
1.758     albertel 7843: 	return (split('/',$short))[-1];
                   7844:     }
1.742     raeburn  7845:     if (!defined($cid)) {
                   7846:         $cid = $env{'request.course.id'};
                   7847:     }
                   7848:     my %rolenames = (
1.1008    raeburn  7849:                       Course    => 'std',
                   7850:                       Community => 'alt1',
1.742     raeburn  7851:                     );
1.1037    raeburn  7852:     if ($cid ne '') {
                   7853:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   7854:             unless ($forcedefault) {
                   7855:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   7856:                 &Apache::lonlocal::mt_escape(\$roletext);
                   7857:                 return &Apache::lonlocal::mt($roletext);
                   7858:             }
                   7859:         }
                   7860:     }
                   7861:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   7862:         (defined($rolenames{$type})) && 
                   7863:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  7864:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  7865:     } elsif ($cid ne '') {
                   7866:         my $crstype = $env{'course.'.$cid.'.type'};
                   7867:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   7868:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   7869:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   7870:         }
1.742     raeburn  7871:     }
1.1037    raeburn  7872:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      7873: }
                   7874: 
                   7875: # ----------------------------------------------------------------- Assign Role
                   7876: 
                   7877: sub assignrole {
1.957     raeburn  7878:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   7879:         $context)=@_;
1.21      www      7880:     my $mrole;
                   7881:     if ($role =~ /^cr\//) {
1.393     www      7882:         my $cwosec=$url;
1.811     albertel 7883:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      7884: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  7885:            my $refused = 1;
                   7886:            if ($context eq 'requestcourses') {
                   7887:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7888:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   7889:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   7890:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7891:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7892:                            if ($crsenv{'internal.courseowner'} eq
                   7893:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   7894:                                $refused = '';
                   7895:                            }
                   7896:                        }
                   7897:                    }
                   7898:                }
                   7899:            }
                   7900:            if ($refused) {
                   7901:                &logthis('Refused custom assignrole: '.
                   7902:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   7903:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   7904:                return 'refused';
                   7905:            }
1.104     www      7906:         }
1.21      www      7907:         $mrole='cr';
1.678     raeburn  7908:     } elsif ($role =~ /^gr\//) {
                   7909:         my $cwogrp=$url;
1.811     albertel 7910:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  7911:         unless (&allowed('mdg',$cwogrp)) {
                   7912:             &logthis('Refused group assignrole: '.
                   7913:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   7914:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   7915:             return 'refused';
                   7916:         }
                   7917:         $mrole='gr';
1.21      www      7918:     } else {
1.82      www      7919:         my $cwosec=$url;
1.811     albertel 7920:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  7921:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   7922:             my $refused;
                   7923:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   7924:                 if (!(&allowed('c'.$role,$url))) {
                   7925:                     $refused = 1;
                   7926:                 }
                   7927:             } else {
                   7928:                 $refused = 1;
                   7929:             }
1.947     raeburn  7930:             if ($refused) {
1.1045    raeburn  7931:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7932:                 if (!$selfenroll && $context eq 'course') {
                   7933:                     my %crsenv;
                   7934:                     if ($role eq 'cc' || $role eq 'co') {
                   7935:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7936:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   7937:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   7938:                                 if ($crsenv{'internal.courseowner'} eq 
                   7939:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7940:                                     $refused = '';
                   7941:                                 }
                   7942:                             }
                   7943:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   7944:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   7945:                                 if ($crsenv{'internal.courseowner'} eq 
                   7946:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7947:                                     $refused = '';
                   7948:                                 }
                   7949:                             }
                   7950:                         }
                   7951:                     }
                   7952:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  7953:                     $refused = '';
1.1017    raeburn  7954:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  7955:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  7956:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  7957:                         my $wrongcc;
                   7958:                         if ($cnum =~ /^$match_community$/) {
                   7959:                             $wrongcc = 1 if ($role eq 'cc');
                   7960:                         } else {
                   7961:                             $wrongcc = 1 if ($role eq 'co');
                   7962:                         }
                   7963:                         unless ($wrongcc) {
                   7964:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7965:                             if ($crsenv{'internal.courseowner'} eq 
                   7966:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   7967:                                 $refused = '';
                   7968:                             }
1.1017    raeburn  7969:                         }
                   7970:                     }
1.1172.2.9  raeburn  7971:                 } elsif ($context eq 'requestauthor') {
                   7972:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7973:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   7974:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   7975:                             $refused = '';
                   7976:                         } else {
                   7977:                             my %domdefaults = &get_domain_defaults($udom);
                   7978:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   7979:                                 my $checkbystatus;
                   7980:                                 if ($env{'user.adv'}) {
                   7981:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   7982:                                     if ($disposition eq 'automatic') {
                   7983:                                         $refused = '';
                   7984:                                     } elsif ($disposition eq '') {
                   7985:                                         $checkbystatus = 1;
                   7986:                                     }
                   7987:                                 } else {
                   7988:                                     $checkbystatus = 1;
                   7989:                                 }
                   7990:                                 if ($checkbystatus) {
                   7991:                                     if ($env{'environment.inststatus'}) {
                   7992:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   7993:                                         foreach my $type (@inststatuses) {
                   7994:                                             if (($type ne '') &&
                   7995:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   7996:                                                 $refused = '';
                   7997:                                             }
                   7998:                                         }
                   7999:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8000:                                         $refused = '';
                   8001:                                     }
                   8002:                                 }
                   8003:                             }
                   8004:                         }
                   8005:                     }
1.1017    raeburn  8006:                 }
                   8007:                 if ($refused) {
1.947     raeburn  8008:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8009:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8010: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8011:                     return 'refused';
                   8012:                 }
1.932     raeburn  8013:             }
1.1131    raeburn  8014:         } elsif ($role eq 'au') {
                   8015:             if ($url ne '/'.$udom.'/') {
                   8016:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8017:                          ' to assign author role for '.$uname.':'.$udom.
                   8018:                          ' in domain: '.$url.' refused (wrong domain).');
                   8019:                 return 'refused';
                   8020:             }
1.104     www      8021:         }
1.21      www      8022:         $mrole=$role;
                   8023:     }
1.620     albertel 8024:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8025:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8026:     if ($end) { $command.='_'.$end; }
1.21      www      8027:     if ($start) {
                   8028: 	if ($end) { 
1.81      www      8029:            $command.='_'.$start; 
1.21      www      8030:         } else {
1.81      www      8031:            $command.='_0_'.$start;
1.21      www      8032:         }
                   8033:     }
1.739     raeburn  8034:     my $origstart = $start;
                   8035:     my $origend = $end;
1.957     raeburn  8036:     my $delflag;
1.357     www      8037: # actually delete
                   8038:     if ($deleteflag) {
1.373     www      8039: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8040: # modify command to delete the role
1.620     albertel 8041:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8042:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8043: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8044: # set start and finish to negative values for userrolelog
                   8045:            $start=-1;
                   8046:            $end=-1;
1.957     raeburn  8047:            $delflag = 1;
1.357     www      8048:         }
                   8049:     }
                   8050: # send command
1.349     www      8051:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8052: # log new user role if status is ok
1.349     www      8053:     if ($answer eq 'ok') {
1.663     raeburn  8054: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  8055:         if (($role eq 'cc') || ($role eq 'in') ||
                   8056:             ($role eq 'ep') || ($role eq 'ad') ||
                   8057:             ($role eq 'ta') || ($role eq 'st') ||
                   8058:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8059:             ($role eq 'co')) {
1.1172.2.13  raeburn  8060: # for course roles, perform group memberships changes triggered by role change.
                   8061:             unless ($role =~ /^gr/) {
                   8062:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8063:                                                  $origstart,$selfenroll,$context);
                   8064:             }
1.1172.2.9  raeburn  8065:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8066:                            $selfenroll,$context);
                   8067:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8068:                  ($role eq 'au') || ($role eq 'dc')) {
                   8069:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8070:                            $context);
                   8071:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8072:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8073:                              $context);
                   8074:         }
1.1053    raeburn  8075:         if ($role eq 'cc') {
                   8076:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8077:         }
1.349     www      8078:     }
                   8079:     return $answer;
1.169     harris41 8080: }
                   8081: 
1.1053    raeburn  8082: sub autoupdate_coowners {
                   8083:     my ($url,$end,$start,$uname,$udom) = @_;
                   8084:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8085:     if (($cdom ne '') && ($cnum ne '')) {
                   8086:         my $now = time;
                   8087:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8088:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8089:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8090:             my $instcode = $coursehash{'internal.coursecode'};
                   8091:             if ($instcode ne '') {
1.1056    raeburn  8092:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8093:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8094:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8095:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8096:                         if ($result eq 'valid') {
                   8097:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8098:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8099:                                     push(@newcoowners,$coowner);
                   8100:                                 }
                   8101:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8102:                                     push(@newcoowners,$uname.':'.$udom);
                   8103:                                 }
                   8104:                                 @newcoowners = sort(@newcoowners);
                   8105:                             } else {
                   8106:                                 push(@newcoowners,$uname.':'.$udom);
                   8107:                             }
                   8108:                         } else {
                   8109:                             if ($coursehash{'internal.co-owners'}) {
                   8110:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8111:                                     unless ($coowner eq $uname.':'.$udom) {
                   8112:                                         push(@newcoowners,$coowner);
                   8113:                                     }
                   8114:                                 }
                   8115:                                 unless (@newcoowners > 0) {
                   8116:                                     $delcoowners = 1;
                   8117:                                     $coowners = '';
                   8118:                                 }
                   8119:                             }
                   8120:                         }
                   8121:                         if (@newcoowners || $delcoowners) {
                   8122:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8123:                                             $delcoowners,@newcoowners);
                   8124:                         }
                   8125:                     }
                   8126:                 }
                   8127:             }
                   8128:         }
                   8129:     }
                   8130: }
                   8131: 
                   8132: sub store_coowners {
                   8133:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8134:     my $cid = $cdom.'_'.$cnum;
                   8135:     my ($coowners,$delresult,$putresult);
                   8136:     if (@newcoowners) {
                   8137:         $coowners = join(',',@newcoowners);
                   8138:         my %coownershash = (
                   8139:                             'internal.co-owners' => $coowners,
                   8140:                            );
                   8141:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8142:         if ($putresult eq 'ok') {
                   8143:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8144:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8145:             }
                   8146:         }
                   8147:     }
                   8148:     if ($delcoowners) {
                   8149:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8150:         if ($delresult eq 'ok') {
                   8151:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8152:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8153:             }
                   8154:         }
                   8155:     }
                   8156:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8157:         my %crsinfo =
                   8158:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8159:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8160:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8161:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8162:         }
                   8163:     }
                   8164: }
                   8165: 
1.169     harris41 8166: # -------------------------------------------------- Modify user authentication
1.197     www      8167: # Overrides without validation
                   8168: 
1.169     harris41 8169: sub modifyuserauth {
                   8170:     my ($udom,$uname,$umode,$upass)=@_;
                   8171:     my $uhome=&homeserver($uname,$udom);
1.197     www      8172:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8173:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8174:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8175:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8176:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8177: 		     &escape($upass),$uhome);
1.620     albertel 8178:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8179:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8180:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8181:     &log($udom,,$uname,$uhome,
1.620     albertel 8182:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8183:                                      $env{'user.name'}.', '.$umode.
1.197     www      8184:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8185:     unless ($reply eq 'ok') {
1.197     www      8186:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8187: 	return 'error: '.$reply;
                   8188:     }   
1.170     harris41 8189:     return 'ok';
1.80      www      8190: }
                   8191: 
1.81      www      8192: # --------------------------------------------------------------- Modify a user
1.80      www      8193: 
1.81      www      8194: sub modifyuser {
1.206     matthew  8195:     my ($udom,    $uname, $uid,
                   8196:         $umode,   $upass, $first,
                   8197:         $middle,  $last,  $gene,
1.1058    raeburn  8198:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8199:     $udom= &LONCAPA::clean_domain($udom);
                   8200:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8201:     my $showcandelete = 'none';
                   8202:     if (ref($candelete) eq 'ARRAY') {
                   8203:         if (@{$candelete} > 0) {
                   8204:             $showcandelete = join(', ',@{$candelete});
                   8205:         }
                   8206:     }
1.81      www      8207:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8208:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8209: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8210:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8211:                                      ' desiredhome not specified'). 
1.620     albertel 8212:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8213:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8214:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8215:     my $newuser;
                   8216:     if ($uhome eq 'no_host') {
                   8217:         $newuser = 1;
                   8218:     }
1.80      www      8219: # ----------------------------------------------------------------- Create User
1.406     albertel 8220:     if (($uhome eq 'no_host') && 
                   8221: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8222:         my $unhome='';
1.844     albertel 8223:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8224:             $unhome = $desiredhome;
1.620     albertel 8225: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8226: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8227:         } else { # load balancing routine for determining $unhome
1.81      www      8228:             my $loadm=10000000;
1.841     albertel 8229: 	    my %servers = &get_servers($udom,'library');
                   8230: 	    foreach my $tryserver (keys(%servers)) {
                   8231: 		my $answer=reply('load',$tryserver);
                   8232: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8233: 		    $loadm=$answer;
                   8234: 		    $unhome=$tryserver;
                   8235: 		}
1.80      www      8236: 	    }
                   8237:         }
                   8238:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8239: 	    return 'error: unable to find a home server for '.$uname.
                   8240:                    ' in domain '.$udom;
1.80      www      8241:         }
                   8242:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8243:                          &escape($upass),$unhome);
                   8244: 	unless ($reply eq 'ok') {
                   8245:             return 'error: '.$reply;
                   8246:         }   
1.230     stredwic 8247:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8248:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8249: 	    return 'error: unable verify users home machine.';
1.80      www      8250:         }
1.209     matthew  8251:     }   # End of creation of new user
1.80      www      8252: # ---------------------------------------------------------------------- Add ID
                   8253:     if ($uid) {
                   8254:        $uid=~tr/A-Z/a-z/;
                   8255:        my %uidhash=&idrget($udom,$uname);
1.196     www      8256:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8257:          && (!$forceid)) {
1.80      www      8258: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8259: 	      return 'error: user id "'.$uid.'" does not match '.
                   8260:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8261:           }
                   8262:        } else {
                   8263: 	  &idput($udom,($uname => $uid));
                   8264:        }
                   8265:     }
                   8266: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8267:     my @tmp=&get('environment',
1.899     raeburn  8268: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8269:                     'permanentemail','inststatus'],
1.134     albertel 8270: 		   $udom,$uname);
1.1075    raeburn  8271:     my (%names,%oldnames);
1.313     matthew  8272:     if ($tmp[0] =~ m/^error:.*/) { 
                   8273:         %names=(); 
                   8274:     } else {
                   8275:         %names = @tmp;
1.1075    raeburn  8276:         %oldnames = %names;
1.313     matthew  8277:     }
1.388     www      8278: #
1.1058    raeburn  8279: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8280: # of users did not contain them), do not overwrite existing values
                   8281: # unless field is in $candelete array ref.  
                   8282: #
                   8283: 
                   8284:     my @fields = ('firstname','middlename','lastname','generation',
                   8285:                   'permanentemail','id');
                   8286:     my %newvalues;
                   8287:     if (ref($candelete) eq 'ARRAY') {
                   8288:         foreach my $field (@fields) {
                   8289:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8290:                 if ($field eq 'firstname') {
                   8291:                     $names{$field} = $first;
                   8292:                 } elsif ($field eq 'middlename') {
                   8293:                     $names{$field} = $middle;
                   8294:                 } elsif ($field eq 'lastname') {
                   8295:                     $names{$field} = $last;
                   8296:                 } elsif ($field eq 'generation') { 
                   8297:                     $names{$field} = $gene;
                   8298:                 } elsif ($field eq 'permanentemail') {
                   8299:                     $names{$field} = $email;
                   8300:                 } elsif ($field eq 'id') {
                   8301:                     $names{$field}  = $uid;
                   8302:                 }
                   8303:             }
                   8304:         }
                   8305:     }
1.388     www      8306:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  8307:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      8308:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  8309:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      8310:     if ($email) {
                   8311:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  8312:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      8313:     }
1.899     raeburn  8314:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  8315:     if (defined($inststatus)) {
                   8316:         $names{'inststatus'} = '';
                   8317:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   8318:         if (ref($usertypes) eq 'HASH') {
                   8319:             my @okstatuses; 
                   8320:             foreach my $item (split(/:/,$inststatus)) {
                   8321:                 if (defined($usertypes->{$item})) {
                   8322:                     push(@okstatuses,$item);  
                   8323:                 }
                   8324:             }
                   8325:             if (@okstatuses) {
                   8326:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   8327:             }
                   8328:         }
                   8329:     }
1.1075    raeburn  8330:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  8331:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  8332:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  8333:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   8334:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   8335:     } else {
                   8336:         $logmsg .= ' during self creation';
                   8337:     }
1.1075    raeburn  8338:     my $changed;
                   8339:     if ($newuser) {
                   8340:         $changed = 1;
                   8341:     } else {
                   8342:         foreach my $field (@fields) {
                   8343:             if ($names{$field} ne $oldnames{$field}) {
                   8344:                 $changed = 1;
                   8345:                 last;
                   8346:             }
                   8347:         }
                   8348:     }
                   8349:     unless ($changed) {
                   8350:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   8351:         &logthis($logmsg);
                   8352:         return 'ok';
                   8353:     }
                   8354:     my $reply = &put('environment', \%names, $udom,$uname);
                   8355:     if ($reply ne 'ok') { 
                   8356:         return 'error: '.$reply;
                   8357:     }
1.1087    raeburn  8358:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   8359:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   8360:     }
1.1075    raeburn  8361:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   8362:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   8363:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  8364:     &logthis($logmsg);
1.134     albertel 8365:     return 'ok';
1.80      www      8366: }
                   8367: 
1.81      www      8368: # -------------------------------------------------------------- Modify student
1.80      www      8369: 
1.81      www      8370: sub modifystudent {
                   8371:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  8372:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.19  raeburn  8373:         $selfenroll,$context,$inststatus,$credits)=@_;
1.455     albertel 8374:     if (!$cid) {
1.620     albertel 8375: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8376: 	    return 'not_in_class';
                   8377: 	}
1.80      www      8378:     }
                   8379: # --------------------------------------------------------------- Make the user
1.81      www      8380:     my $reply=&modifyuser
1.209     matthew  8381: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  8382:          $desiredhome,$email,$inststatus);
1.80      www      8383:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  8384:     # This will cause &modify_student_enrollment to get the uid from the
                   8385:     # students environment
                   8386:     $uid = undef if (!$forceid);
1.455     albertel 8387:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  8388: 					$gene,$usec,$end,$start,$type,$locktype,
                   8389:                                         $cid,$selfenroll,$context,$credits);
1.297     matthew  8390:     return $reply;
                   8391: }
                   8392: 
                   8393: sub modify_student_enrollment {
1.1172.2.19  raeburn  8394:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455     albertel 8395:     my ($cdom,$cnum,$chome);
                   8396:     if (!$cid) {
1.620     albertel 8397: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8398: 	    return 'not_in_class';
                   8399: 	}
1.620     albertel 8400: 	$cdom=$env{'course.'.$cid.'.domain'};
                   8401: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 8402:     } else {
                   8403: 	($cdom,$cnum)=split(/_/,$cid);
                   8404:     }
1.620     albertel 8405:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 8406:     if (!$chome) {
1.457     raeburn  8407: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  8408:     }
1.455     albertel 8409:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  8410:     # Make sure the user exists
1.81      www      8411:     my $uhome=&homeserver($uname,$udom);
                   8412:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8413: 	return 'error: no such user';
                   8414:     }
1.297     matthew  8415:     # Get student data if we were not given enough information
                   8416:     if (!defined($first)  || $first  eq '' || 
                   8417:         !defined($last)   || $last   eq '' || 
                   8418:         !defined($uid)    || $uid    eq '' || 
                   8419:         !defined($middle) || $middle eq '' || 
                   8420:         !defined($gene)   || $gene   eq '') {
1.294     matthew  8421:         # They did not supply us with enough data to enroll the student, so
                   8422:         # we need to pick up more information.
1.297     matthew  8423:         my %tmp = &get('environment',
1.294     matthew  8424:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  8425:                        ,$udom,$uname);
                   8426: 
1.800     albertel 8427:         #foreach my $key (keys(%tmp)) {
                   8428:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 8429:         #}
1.294     matthew  8430:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   8431:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   8432:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  8433:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  8434:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   8435:     }
1.556     albertel 8436:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  8437:     my $user = "$uname:$udom";
                   8438:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 8439:     my $reply=cput('classlist',
1.1148    raeburn  8440: 		   {$user => 
1.1172.2.19  raeburn  8441: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487     albertel 8442: 		   $cdom,$cnum);
1.1148    raeburn  8443:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   8444:         &devalidate_getsection_cache($udom,$uname,$cid);
                   8445:     } else { 
1.81      www      8446: 	return 'error: '.$reply;
                   8447:     }
1.297     matthew  8448:     # Add student role to user
1.83      www      8449:     my $uurl='/'.$cid;
1.81      www      8450:     $uurl=~s/\_/\//g;
                   8451:     if ($usec) {
                   8452: 	$uurl.='/'.$usec;
                   8453:     }
1.1148    raeburn  8454:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   8455:                              $selfenroll,$context);
                   8456:     if ($result ne 'ok') {
                   8457:         if ($old_entry{$user} ne '') {
                   8458:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   8459:         } else {
                   8460:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   8461:         }
                   8462:     }
                   8463:     return $result; 
1.21      www      8464: }
                   8465: 
1.556     albertel 8466: sub format_name {
                   8467:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   8468:     my $name;
                   8469:     if ($first ne 'lastname') {
                   8470: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   8471:     } else {
                   8472: 	if ($lastname=~/\S/) {
                   8473: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   8474: 	    $name=~s/\s+,/,/;
                   8475: 	} else {
                   8476: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   8477: 	}
                   8478:     }
                   8479:     $name=~s/^\s+//;
                   8480:     $name=~s/\s+$//;
                   8481:     $name=~s/\s+/ /g;
                   8482:     return $name;
                   8483: }
                   8484: 
1.84      www      8485: # ------------------------------------------------- Write to course preferences
                   8486: 
                   8487: sub writecoursepref {
                   8488:     my ($courseid,%prefs)=@_;
                   8489:     $courseid=~s/^\///;
                   8490:     $courseid=~s/\_/\//g;
                   8491:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   8492:     my $chome=homeserver($cnum,$cdomain);
                   8493:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   8494: 	return 'error: no such course';
                   8495:     }
                   8496:     my $cstring='';
1.800     albertel 8497:     foreach my $pref (keys(%prefs)) {
                   8498: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 8499:     }
1.84      www      8500:     $cstring=~s/\&$//;
                   8501:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   8502: }
                   8503: 
                   8504: # ---------------------------------------------------------- Make/modify course
                   8505: 
                   8506: sub createcourse {
1.741     raeburn  8507:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  8508:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      8509:     $url=&declutter($url);
                   8510:     my $cid='';
1.1028    raeburn  8511:     if ($context eq 'requestcourses') {
                   8512:         my $can_create = 0;
                   8513:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   8514:         if ($udom eq $ownerdom) {
                   8515:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   8516:                                   $context)) {
                   8517:                 $can_create = 1;
                   8518:             }
                   8519:         } else {
                   8520:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   8521:                                            $category);
                   8522:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   8523:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   8524:                 if (@curr > 0) {
                   8525:                     my @options = qw(approval validate autolimit);
                   8526:                     my $optregex = join('|',@options);
                   8527:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   8528:                         $can_create = 1;
                   8529:                     }
                   8530:                 }
                   8531:             }
                   8532:         }
                   8533:         if ($can_create) {
                   8534:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   8535:                 unless (&allowed('ccc',$udom)) {
                   8536:                     return 'refused'; 
                   8537:                 }
1.1017    raeburn  8538:             }
                   8539:         } else {
                   8540:             return 'refused';
                   8541:         }
1.1028    raeburn  8542:     } elsif (!&allowed('ccc',$udom)) {
                   8543:         return 'refused';
1.84      www      8544:     }
1.1011    raeburn  8545: # --------------------------------------------------------------- Get Unique ID
                   8546:     my $uname;
                   8547:     if ($cnum =~ /^$match_courseid$/) {
                   8548:         my $chome=&homeserver($cnum,$udom,'true');
                   8549:         if (($chome eq '') || ($chome eq 'no_host')) {
                   8550:             $uname = $cnum;
                   8551:         } else {
1.1038    raeburn  8552:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8553:         }
                   8554:     } else {
1.1038    raeburn  8555:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8556:     }
                   8557:     return $uname if ($uname =~ /^error/);
                   8558: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  8559:     if (!defined($course_server)) {
                   8560:         if (defined(&domain($udom,'primary'))) {
                   8561:             $course_server = &domain($udom,'primary');
                   8562:         } else {
                   8563:             $course_server = $env{'user.home'}; 
                   8564:         }
                   8565:     }
                   8566:     my %host_servers =
                   8567:         &Apache::lonnet::get_servers($udom,'library');
                   8568:     unless ($host_servers{$course_server}) {
                   8569:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  8570:     }
1.84      www      8571: # ------------------------------------------------------------- Make the course
                   8572:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  8573:                       $course_server);
1.84      www      8574:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  8575:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      8576:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8577: 	return 'error: no such course';
                   8578:     }
1.271     www      8579: # ----------------------------------------------------------------- Course made
1.516     raeburn  8580: # log existence
1.1029    raeburn  8581:     my $now = time;
1.918     raeburn  8582:     my $newcourse = {
                   8583:                     $udom.'_'.$uname => {
1.921     raeburn  8584:                                      description => $description,
                   8585:                                      inst_code   => $inst_code,
                   8586:                                      owner       => $course_owner,
                   8587:                                      type        => $crstype,
1.1029    raeburn  8588:                                      creator     => $env{'user.name'}.':'.
                   8589:                                                     $env{'user.domain'},
                   8590:                                      created     => $now,
                   8591:                                      context     => $context,
1.918     raeburn  8592:                                                 },
                   8593:                     };
1.921     raeburn  8594:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      8595: # set toplevel url
1.271     www      8596:     my $topurl=$url;
                   8597:     unless ($nonstandard) {
                   8598: # ------------------------------------------ For standard courses, make top url
                   8599:         my $mapurl=&clutter($url);
1.278     www      8600:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 8601:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      8602: <map>
                   8603: <resource id="1" type="start"></resource>
                   8604: <resource id="2" src="$mapurl"></resource>
                   8605: <resource id="3" type="finish"></resource>
                   8606: <link index="1" from="1" to="2"></link>
                   8607: <link index="2" from="2" to="3"></link>
                   8608: </map>
                   8609: ENDINITMAP
                   8610:         $topurl=&declutter(
1.638     albertel 8611:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      8612:                           );
                   8613:     }
                   8614: # ----------------------------------------------------------- Write preferences
1.84      www      8615:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  8616:                      ('description'              => $description,
                   8617:                       'url'                      => $topurl,
                   8618:                       'internal.creator'         => $env{'user.name'}.':'.
                   8619:                                                     $env{'user.domain'},
                   8620:                       'internal.created'         => $now,
                   8621:                       'internal.creationcontext' => $context)
                   8622:                     );
1.84      www      8623:     return '/'.$udom.'/'.$uname;
                   8624: }
                   8625: 
1.1011    raeburn  8626: # ------------------------------------------------------------------- Create ID
                   8627: sub generate_coursenum {
1.1038    raeburn  8628:     my ($udom,$crstype) = @_;
1.1011    raeburn  8629:     my $domdesc = &domain($udom);
                   8630:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  8631:     my $first;
                   8632:     if ($crstype eq 'Community') {
                   8633:         $first = '0';
                   8634:     } else {
                   8635:         $first = int(1+rand(9)); 
                   8636:     } 
                   8637:     my $uname=$first.
1.1011    raeburn  8638:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8639:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8640:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8641: # ----------------------------------------------- Make sure that does not exist
                   8642:     my $uhome=&homeserver($uname,$udom,'true');
                   8643:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  8644:         if ($crstype eq 'Community') {
                   8645:             $first = '0';
                   8646:         } else {
                   8647:             $first = int(1+rand(9));
                   8648:         }
                   8649:         $uname=$first.
1.1011    raeburn  8650:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8651:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8652:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8653:         $uhome=&homeserver($uname,$udom,'true');
                   8654:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   8655:             return 'error: unable to generate unique course-ID';
                   8656:         }
                   8657:     }
                   8658:     return $uname;
                   8659: }
                   8660: 
1.813     albertel 8661: sub is_course {
1.1167    droeschl 8662:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   8663:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   8664: 
                   8665:     return unless $cdom and $cnum;
                   8666: 
                   8667:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   8668:         '.');
                   8669: 
                   8670:     return unless exists($courses{$cdom.'_'.$cnum});
                   8671:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 8672: }
                   8673: 
1.1015    raeburn  8674: sub store_userdata {
                   8675:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  8676:     my $result;
1.1016    raeburn  8677:     if ($datakey ne '') {
1.1013    raeburn  8678:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  8679:             if ($udom eq '' || $uname eq '') {
                   8680:                 $udom = $env{'user.domain'};
                   8681:                 $uname = $env{'user.name'};
                   8682:             }
                   8683:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  8684:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   8685:                 $result = 'error: no_host';
                   8686:             } else {
                   8687:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   8688:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   8689: 
                   8690:                 my $namevalue='';
                   8691:                 foreach my $key (keys(%{$storehash})) {
                   8692:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   8693:                 }
                   8694:                 $namevalue=~s/\&$//;
1.1105    raeburn  8695:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   8696:                                   $namevalue,$uhome);
1.1013    raeburn  8697:             }
                   8698:         } else {
                   8699:             $result = 'error: data to store was not a hash reference'; 
                   8700:         }
                   8701:     } else {
                   8702:         $result= 'error: invalid requestkey'; 
                   8703:     }
                   8704:     return $result;
                   8705: }
                   8706: 
1.21      www      8707: # ---------------------------------------------------------- Assign Custom Role
                   8708: 
                   8709: sub assigncustomrole {
1.957     raeburn  8710:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8711:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  8712:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      8713: }
                   8714: 
                   8715: # ----------------------------------------------------------------- Revoke Role
                   8716: 
                   8717: sub revokerole {
1.957     raeburn  8718:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8719:     my $now=time;
1.965     raeburn  8720:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      8721: }
                   8722: 
                   8723: # ---------------------------------------------------------- Revoke Custom Role
                   8724: 
                   8725: sub revokecustomrole {
1.957     raeburn  8726:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8727:     my $now=time;
1.357     www      8728:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  8729:            $deleteflag,$selfenroll,$context);
1.17      www      8730: }
                   8731: 
1.533     banghart 8732: # ------------------------------------------------------------ Disk usage
1.535     albertel 8733: sub diskusage {
1.955     raeburn  8734:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   8735:     $directorypath =~ s/\/$//;
                   8736:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   8737:                        .&escape($getpropath).':'.&escape($uname).':'
                   8738:                        .&escape($udom),homeserver($uname,$udom));
                   8739:     if ($listing eq 'unknown_cmd') {
                   8740:         if ($getpropath) {
                   8741:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   8742:         }
                   8743:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   8744:     }
1.514     albertel 8745:     return $listing;
1.512     banghart 8746: }
                   8747: 
1.566     banghart 8748: sub is_locked {
1.1096    raeburn  8749:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 8750:     my @check;
                   8751:     my $is_locked;
1.1093    raeburn  8752:     push (@check,$file_name);
1.613     albertel 8753:     my %locked = &get('file_permissions',\@check,
1.620     albertel 8754: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 8755:     my ($tmp)=keys(%locked);
                   8756:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  8757:     
1.566     banghart 8758:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  8759:         $is_locked = 'false';
                   8760:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  8761:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  8762:                $is_locked = 'true';
1.1096    raeburn  8763:                if (ref($which) eq 'ARRAY') {
                   8764:                    push(@{$which},$entry);
                   8765:                } else {
                   8766:                    last;
                   8767:                }
1.745     raeburn  8768:            }
                   8769:        }
1.566     banghart 8770:     } else {
                   8771:         $is_locked = 'false';
                   8772:     }
1.1093    raeburn  8773:     return $is_locked;
1.566     banghart 8774: }
                   8775: 
1.759     albertel 8776: sub declutter_portfile {
                   8777:     my ($file) = @_;
1.833     albertel 8778:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 8779:     return $file;
                   8780: }
                   8781: 
1.559     banghart 8782: # ------------------------------------------------------------- Mark as Read Only
                   8783: 
                   8784: sub mark_as_readonly {
                   8785:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 8786:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8787:     my ($tmp)=keys(%current_permissions);
                   8788:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 8789:     foreach my $file (@{$files}) {
1.759     albertel 8790: 	$file = &declutter_portfile($file);
1.561     banghart 8791:         push(@{$current_permissions{$file}},$what);
1.559     banghart 8792:     }
1.613     albertel 8793:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8794:     return;
                   8795: }
                   8796: 
1.572     banghart 8797: # ------------------------------------------------------------Save Selected Files
                   8798: 
                   8799: sub save_selected_files {
                   8800:     my ($user, $path, @files) = @_;
                   8801:     my $filename = $user."savedfiles";
1.573     banghart 8802:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 8803:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 8804:     foreach my $file (@files) {
1.620     albertel 8805:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 8806:     }
                   8807:     foreach my $file (@other_files) {
1.574     banghart 8808:         print (OUT $file."\n");
1.572     banghart 8809:     }
1.574     banghart 8810:     close (OUT);
1.572     banghart 8811:     return 'ok';
                   8812: }
                   8813: 
1.574     banghart 8814: sub clear_selected_files {
                   8815:     my ($user) = @_;
                   8816:     my $filename = $user."savedfiles";
1.1117    foxr     8817:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 8818:     print (OUT undef);
                   8819:     close (OUT);
                   8820:     return ("ok");    
                   8821: }
                   8822: 
1.572     banghart 8823: sub files_in_path {
                   8824:     my ($user, $path) = @_;
                   8825:     my $filename = $user."savedfiles";
                   8826:     my %return_files;
1.1117    foxr     8827:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 8828:     while (my $line_in = <IN>) {
1.574     banghart 8829:         chomp ($line_in);
                   8830:         my @paths_and_file = split (m!/!, $line_in);
                   8831:         my $file_part = pop (@paths_and_file);
                   8832:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 8833:         $path_part.='/';
                   8834:         my $path_and_file = $path_part.$file_part;
                   8835:         if ($path_part eq $path) {
                   8836:             $return_files{$file_part}= 'selected';
                   8837:         }
                   8838:     }
1.574     banghart 8839:     close (IN);
                   8840:     return (\%return_files);
1.572     banghart 8841: }
                   8842: 
                   8843: # called in portfolio select mode, to show files selected NOT in current directory
                   8844: sub files_not_in_path {
                   8845:     my ($user, $path) = @_;
                   8846:     my $filename = $user."savedfiles";
                   8847:     my @return_files;
                   8848:     my $path_part;
1.1117    foxr     8849:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 8850:     while (my $line = <IN>) {
1.572     banghart 8851:         #ok, I know it's clunky, but I want it to work
1.800     albertel 8852:         my @paths_and_file = split(m|/|, $line);
                   8853:         my $file_part = pop(@paths_and_file);
                   8854:         chomp($file_part);
                   8855:         my $path_part = join('/', @paths_and_file);
1.572     banghart 8856:         $path_part .= '/';
                   8857:         my $path_and_file = $path_part.$file_part;
                   8858:         if ($path_part ne $path) {
1.800     albertel 8859:             push(@return_files, ($path_and_file));
1.572     banghart 8860:         }
                   8861:     }
1.800     albertel 8862:     close(OUT);
1.574     banghart 8863:     return (@return_files);
1.572     banghart 8864: }
                   8865: 
1.745     raeburn  8866: #----------------------------------------------Get portfolio file permissions
1.629     banghart 8867: 
1.745     raeburn  8868: sub get_portfile_permissions {
                   8869:     my ($domain,$user) = @_;
1.613     albertel 8870:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8871:     my ($tmp)=keys(%current_permissions);
                   8872:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8873:     return \%current_permissions;
                   8874: }
                   8875: 
                   8876: #---------------------------------------------Get portfolio file access controls
                   8877: 
1.749     raeburn  8878: sub get_access_controls {
1.745     raeburn  8879:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 8880:     my %access;
                   8881:     my $real_file = $file;
                   8882:     $file =~ s/\.meta$//;
1.745     raeburn  8883:     if (defined($file)) {
1.749     raeburn  8884:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   8885:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 8886:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  8887:             }
                   8888:         }
1.745     raeburn  8889:     } else {
1.749     raeburn  8890:         foreach my $key (keys(%{$current_permissions})) {
                   8891:             if ($key =~ /\0accesscontrol$/) {
                   8892:                 if (defined($group)) {
                   8893:                     if ($key !~ m-^\Q$group\E/-) {
                   8894:                         next;
                   8895:                     }
                   8896:                 }
                   8897:                 my ($fullpath) = split(/\0/,$key);
                   8898:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   8899:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   8900:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   8901:                     }
                   8902:                 }
                   8903:             }
                   8904:         }
                   8905:     }
                   8906:     return %access;
                   8907: }
                   8908: 
                   8909: sub modify_access_controls {
                   8910:     my ($file_name,$changes,$domain,$user)=@_;
                   8911:     my ($outcome,$deloutcome);
                   8912:     my %store_permissions;
                   8913:     my %new_values;
                   8914:     my %new_control;
                   8915:     my %translation;
                   8916:     my @deletions = ();
                   8917:     my $now = time;
                   8918:     if (exists($$changes{'activate'})) {
                   8919:         if (ref($$changes{'activate'}) eq 'HASH') {
                   8920:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   8921:             my $numnew = scalar(@newitems);
                   8922:             for (my $i=0; $i<$numnew; $i++) {
                   8923:                 my $newkey = $newitems[$i];
                   8924:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  8925:                 if ($newkey =~ /^\d+:/) { 
                   8926:                     $newkey =~ s/^(\d+)/$newid/;
                   8927:                     $translation{$1} = $newid;
                   8928:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   8929:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   8930:                     $translation{$1} = $newid;
                   8931:                 }
1.749     raeburn  8932:                 $new_values{$file_name."\0".$newkey} = 
                   8933:                                           $$changes{'activate'}{$newitems[$i]};
                   8934:                 $new_control{$newkey} = $now;
                   8935:             }
                   8936:         }
                   8937:     }
                   8938:     my %todelete;
                   8939:     my %changed_items;
                   8940:     foreach my $action ('delete','update') {
                   8941:         if (exists($$changes{$action})) {
                   8942:             if (ref($$changes{$action}) eq 'HASH') {
                   8943:                 foreach my $key (keys(%{$$changes{$action}})) {
                   8944:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   8945:                     if ($action eq 'delete') { 
                   8946:                         $todelete{$itemnum} = 1;
                   8947:                     } else {
                   8948:                         $changed_items{$itemnum} = $key;
                   8949:                     }
                   8950:                 }
1.745     raeburn  8951:             }
                   8952:         }
1.749     raeburn  8953:     }
                   8954:     # get lock on access controls for file.
                   8955:     my $lockhash = {
                   8956:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   8957:                                                        ':'.$env{'user.domain'},
                   8958:                    }; 
                   8959:     my $tries = 0;
                   8960:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8961:    
                   8962:     while (($gotlock ne 'ok') && $tries <3) {
                   8963:         $tries ++;
                   8964:         sleep 1;
                   8965:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8966:     }
                   8967:     if ($gotlock eq 'ok') {
                   8968:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   8969:         my ($tmp)=keys(%curr_permissions);
                   8970:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   8971:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   8972:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   8973:             if (ref($curr_controls) eq 'HASH') {
                   8974:                 foreach my $control_item (keys(%{$curr_controls})) {
                   8975:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   8976:                     if (defined($todelete{$itemnum})) {
                   8977:                         push(@deletions,$file_name."\0".$control_item);
                   8978:                     } else {
                   8979:                         if (defined($changed_items{$itemnum})) {
                   8980:                             $new_control{$changed_items{$itemnum}} = $now;
                   8981:                             push(@deletions,$file_name."\0".$control_item);
                   8982:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   8983:                         } else {
                   8984:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   8985:                         }
                   8986:                     }
1.745     raeburn  8987:                 }
                   8988:             }
                   8989:         }
1.970     raeburn  8990:         my ($group);
                   8991:         if (&is_course($domain,$user)) {
                   8992:             ($group,my $file) = split(/\//,$file_name,2);
                   8993:         }
1.749     raeburn  8994:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   8995:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   8996:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   8997:         #  remove lock
                   8998:         my @del_lock = ($file_name."\0".'locked_access_records');
                   8999:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9000:         my $sqlresult =
1.970     raeburn  9001:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9002:                                     $group);
1.749     raeburn  9003:     } else {
                   9004:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9005:     }
1.749     raeburn  9006:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9007: }
                   9008: 
1.827     raeburn  9009: sub make_public_indefinitely {
                   9010:     my ($requrl) = @_;
                   9011:     my $now = time;
                   9012:     my $action = 'activate';
                   9013:     my $aclnum = 0;
                   9014:     if (&is_portfolio_url($requrl)) {
                   9015:         my (undef,$udom,$unum,$file_name,$group) =
                   9016:             &parse_portfolio_url($requrl);
                   9017:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   9018:         my %access_controls = &get_access_controls($current_perms,
                   9019:                                                    $group,$file_name);
                   9020:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9021:             my ($num,$scope,$end,$start) = 
                   9022:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   9023:             if ($scope eq 'public') {
                   9024:                 if ($start <= $now && $end == 0) {
                   9025:                     $action = 'none';
                   9026:                 } else {
                   9027:                     $action = 'update';
                   9028:                     $aclnum = $num;
                   9029:                 }
                   9030:                 last;
                   9031:             }
                   9032:         }
                   9033:         if ($action eq 'none') {
                   9034:              return 'ok';
                   9035:         } else {
                   9036:             my %changes;
                   9037:             my $newend = 0;
                   9038:             my $newstart = $now;
                   9039:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   9040:             $changes{$action}{$newkey} = {
                   9041:                 type => 'public',
                   9042:                 time => {
                   9043:                     start => $newstart,
                   9044:                     end   => $newend,
                   9045:                 },
                   9046:             };
                   9047:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9048:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   9049:             return $outcome;
                   9050:         }
                   9051:     } else {
                   9052:         return 'invalid';
                   9053:     }
                   9054: }
                   9055: 
1.745     raeburn  9056: #------------------------------------------------------Get Marked as Read Only
                   9057: 
                   9058: sub get_marked_as_readonly {
                   9059:     my ($domain,$user,$what,$group) = @_;
                   9060:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 9061:     my @readonly_files;
1.629     banghart 9062:     my $cmp1=$what;
                   9063:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  9064:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9065:         if (defined($group)) {
                   9066:             if ($file_name !~ m-^\Q$group\E/-) {
                   9067:                 next;
                   9068:             }
                   9069:         }
1.561     banghart 9070:         if (ref($value) eq "ARRAY"){
                   9071:             foreach my $stored_what (@{$value}) {
1.629     banghart 9072:                 my $cmp2=$stored_what;
1.759     albertel 9073:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  9074:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  9075:                 }
1.629     banghart 9076:                 if ($cmp1 eq $cmp2) {
1.561     banghart 9077:                     push(@readonly_files, $file_name);
1.745     raeburn  9078:                     last;
1.563     banghart 9079:                 } elsif (!defined($what)) {
                   9080:                     push(@readonly_files, $file_name);
1.745     raeburn  9081:                     last;
1.561     banghart 9082:                 }
                   9083:             }
1.745     raeburn  9084:         }
1.561     banghart 9085:     }
                   9086:     return @readonly_files;
                   9087: }
1.577     banghart 9088: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 9089: 
1.577     banghart 9090: sub get_marked_as_readonly_hash {
1.745     raeburn  9091:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 9092:     my %readonly_files;
1.745     raeburn  9093:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9094:         if (defined($group)) {
                   9095:             if ($file_name !~ m-^\Q$group\E/-) {
                   9096:                 next;
                   9097:             }
                   9098:         }
1.577     banghart 9099:         if (ref($value) eq "ARRAY"){
                   9100:             foreach my $stored_what (@{$value}) {
1.745     raeburn  9101:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 9102:                     foreach my $lock_descriptor(@{$stored_what}) {
                   9103:                         if ($lock_descriptor eq 'graded') {
                   9104:                             $readonly_files{$file_name} = 'graded';
                   9105:                         } elsif ($lock_descriptor eq 'handback') {
                   9106:                             $readonly_files{$file_name} = 'handback';
                   9107:                         } else {
                   9108:                             if (!exists($readonly_files{$file_name})) {
                   9109:                                 $readonly_files{$file_name} = 'locked';
                   9110:                             }
                   9111:                         }
1.745     raeburn  9112:                     }
1.750     banghart 9113:                 } 
1.577     banghart 9114:             }
                   9115:         } 
                   9116:     }
                   9117:     return %readonly_files;
                   9118: }
1.559     banghart 9119: # ------------------------------------------------------------ Unmark as Read Only
                   9120: 
                   9121: sub unmark_as_readonly {
1.629     banghart 9122:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   9123:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  9124:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 9125:     $file_name = &declutter_portfile($file_name);
1.634     albertel 9126:     my $symb_crs = $what;
                   9127:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  9128:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 9129:     my ($tmp)=keys(%current_permissions);
                   9130:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9131:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 9132:     foreach my $file (@readonly_files) {
1.759     albertel 9133: 	my $clean_file = &declutter_portfile($file);
                   9134: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 9135: 	my $current_locks = $current_permissions{$file};
1.563     banghart 9136:         my @new_locks;
                   9137:         my @del_keys;
                   9138:         if (ref($current_locks) eq "ARRAY"){
                   9139:             foreach my $locker (@{$current_locks}) {
1.632     albertel 9140:                 my $compare=$locker;
1.749     raeburn  9141:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  9142:                     $compare=join('',@{$locker});
1.746     raeburn  9143:                     if ($compare ne $symb_crs) {
                   9144:                         push(@new_locks, $locker);
                   9145:                     }
1.563     banghart 9146:                 }
                   9147:             }
1.650     albertel 9148:             if (scalar(@new_locks) > 0) {
1.563     banghart 9149:                 $current_permissions{$file} = \@new_locks;
                   9150:             } else {
                   9151:                 push(@del_keys, $file);
1.613     albertel 9152:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 9153:                 delete($current_permissions{$file});
1.563     banghart 9154:             }
                   9155:         }
1.561     banghart 9156:     }
1.613     albertel 9157:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9158:     return;
                   9159: }
1.512     banghart 9160: 
1.17      www      9161: # ------------------------------------------------------------ Directory lister
                   9162: 
                   9163: sub dirlist {
1.955     raeburn  9164:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      9165:     $uri=~s/^\///;
                   9166:     $uri=~s/\/$//;
1.253     stredwic 9167:     my ($udom, $uname);
1.955     raeburn  9168:     if ($getuserdir) {
1.253     stredwic 9169:         $udom = $userdomain;
                   9170:         $uname = $username;
1.955     raeburn  9171:     } else {
                   9172:         (undef,$udom,$uname)=split(/\//,$uri);
                   9173:         if(defined($userdomain)) {
                   9174:             $udom = $userdomain;
                   9175:         }
                   9176:         if(defined($username)) {
                   9177:             $uname = $username;
                   9178:         }
1.253     stredwic 9179:     }
1.955     raeburn  9180:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 9181: 
1.955     raeburn  9182:     $dirRoot = $perlvar{'lonDocRoot'};
                   9183:     if (defined($getpropath)) {
                   9184:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 9185:         $dirRoot =~ s/\/$//;
1.955     raeburn  9186:     } elsif (defined($getuserdir)) {
                   9187:         my $subdir=$uname.'__';
                   9188:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   9189:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   9190:                    ."/$udom/$subdir/$uname";
                   9191:     } elsif (defined($alternateRoot)) {
                   9192:         $dirRoot = $alternateRoot;
1.751     banghart 9193:     }
1.253     stredwic 9194: 
                   9195:     if($udom) {
                   9196:         if($uname) {
1.1135    raeburn  9197:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  9198:             if ($uhome eq 'no_host') {
                   9199:                 return ([],'no_host');
                   9200:             }
1.955     raeburn  9201:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  9202:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  9203:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  9204:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9205:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  9206:             } else {
                   9207:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9208:             }
1.605     matthew  9209:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9210:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  9211:                 @listing_results = split(/:/,$listing);
                   9212:             } else {
                   9213:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9214:             }
1.1135    raeburn  9215:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  9216:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9217:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9218:                 return ([],$listing);
                   9219:             } else {
                   9220:                 return (\@listing_results);
1.1135    raeburn  9221:             }
1.955     raeburn  9222:         } elsif(!$alternateRoot) {
1.1136    raeburn  9223:             my (%allusers,%listerror);
1.841     albertel 9224: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  9225:  	    foreach my $tryserver (keys(%servers)) {
                   9226:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   9227:                                   &escape($udom),$tryserver);
                   9228:                 if ($listing eq 'unknown_cmd') {
                   9229: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9230: 				      $udom, $tryserver);
                   9231:                 } else {
                   9232:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9233:                 }
1.841     albertel 9234: 		if ($listing eq 'unknown_cmd') {
                   9235: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9236: 				      $udom, $tryserver);
                   9237: 		    @listing_results = split(/:/,$listing);
                   9238: 		} else {
                   9239: 		    @listing_results =
                   9240: 			map { &unescape($_); } split(/:/,$listing);
                   9241: 		}
1.1136    raeburn  9242:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   9243:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9244:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9245:                     $listerror{$tryserver} = $listing;
                   9246:                 } else {
1.841     albertel 9247: 		    foreach my $line (@listing_results) {
                   9248: 			my ($entry) = split(/&/,$line,2);
                   9249: 			$allusers{$entry} = 1;
                   9250: 		    }
                   9251: 		}
1.253     stredwic 9252:             }
1.1136    raeburn  9253:             my @alluserslist=();
1.800     albertel 9254:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  9255:                 push(@alluserslist,$user.'&user');
1.253     stredwic 9256:             }
1.1136    raeburn  9257:             return (\@alluserslist);
1.253     stredwic 9258:         } else {
1.1136    raeburn  9259:             return ([],'missing username');
1.253     stredwic 9260:         }
1.955     raeburn  9261:     } elsif(!defined($getpropath)) {
1.1136    raeburn  9262:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   9263:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   9264:         return (\@all_domains);
1.955     raeburn  9265:     } else {
1.1136    raeburn  9266:         return ([],'missing domain');
1.275     stredwic 9267:     }
                   9268: }
                   9269: 
                   9270: # --------------------------------------------- GetFileTimestamp
                   9271: # This function utilizes dirlist and returns the date stamp for
                   9272: # when it was last modified.  It will also return an error of -1
                   9273: # if an error occurs
                   9274: 
                   9275: sub GetFileTimestamp {
1.955     raeburn  9276:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 9277:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   9278:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  9279:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   9280:                                     undef,$getuserdir);
                   9281:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9282:         return -1;
                   9283:     }
                   9284:     if (ref($fileref) eq 'ARRAY') {
                   9285:         my @stats = split('&',$fileref->[0]);
1.375     matthew  9286:         # @stats contains first the filename, then the stat output
                   9287:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 9288:     } else {
                   9289:         return -1;
1.253     stredwic 9290:     }
1.26      www      9291: }
                   9292: 
1.712     albertel 9293: sub stat_file {
                   9294:     my ($uri) = @_;
1.787     albertel 9295:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 9296: 
1.955     raeburn  9297:     my ($udom,$uname,$file);
1.712     albertel 9298:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   9299: 	($udom,$uname,$file) =
1.811     albertel 9300: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 9301: 	$file = 'userfiles/'.$file;
                   9302:     }
                   9303:     if ($uri =~ m-^/res/-) {
                   9304: 	($udom,$uname) = 
1.807     albertel 9305: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 9306: 	$file = $uri;
                   9307:     }
                   9308: 
                   9309:     if (!$udom || !$uname || !$file) {
                   9310: 	# unable to handle the uri
                   9311: 	return ();
                   9312:     }
1.956     raeburn  9313:     my $getpropath;
                   9314:     if ($file =~ /^userfiles\//) {
                   9315:         $getpropath = 1;
                   9316:     }
1.1136    raeburn  9317:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   9318:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9319:         return ();
                   9320:     } else {
                   9321:         if (ref($listref) eq 'ARRAY') {
                   9322:             my @stats = split('&',$listref->[0]);
                   9323: 	    shift(@stats); #filename is first
                   9324: 	    return @stats;
                   9325:         }
1.712     albertel 9326:     }
                   9327:     return ();
                   9328: }
                   9329: 
1.26      www      9330: # -------------------------------------------------------- Value of a Condition
                   9331: 
1.713     albertel 9332: # gets the value of a specific preevaluated condition
                   9333: #    stored in the string  $env{user.state.<cid>}
                   9334: # or looks up a condition reference in the bighash and if if hasn't
                   9335: # already been evaluated recurses into docondval to get the value of
                   9336: # the condition, then memoizing it to 
                   9337: #   $env{user.state.<cid>.<condition>}
1.40      www      9338: sub directcondval {
                   9339:     my $number=shift;
1.620     albertel 9340:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 9341: 	&Apache::lonuserstate::evalstate();
                   9342:     }
1.713     albertel 9343:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   9344: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   9345:     } elsif ($number =~ /^_/) {
                   9346: 	my $sub_condition;
                   9347: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9348: 		&GDBM_READER(),0640)) {
                   9349: 	    $sub_condition=$bighash{'conditions'.$number};
                   9350: 	    untie(%bighash);
                   9351: 	}
                   9352: 	my $value = &docondval($sub_condition);
1.949     raeburn  9353: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 9354: 	return $value;
                   9355:     }
1.620     albertel 9356:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   9357:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      9358:     } else {
                   9359:        return 2;
                   9360:     }
                   9361: }
                   9362: 
1.713     albertel 9363: # get the collection of conditions for this resource
1.26      www      9364: sub condval {
                   9365:     my $condidx=shift;
1.54      www      9366:     my $allpathcond='';
1.713     albertel 9367:     foreach my $cond (split(/\|/,$condidx)) {
                   9368: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   9369: 	    $allpathcond.=
                   9370: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   9371: 	}
1.191     harris41 9372:     }
1.54      www      9373:     $allpathcond=~s/\|$//;
1.713     albertel 9374:     return &docondval($allpathcond);
                   9375: }
                   9376: 
                   9377: #evaluates an expression of conditions
                   9378: sub docondval {
                   9379:     my ($allpathcond) = @_;
                   9380:     my $result=0;
                   9381:     if ($env{'request.course.id'}
                   9382: 	&& defined($allpathcond)) {
                   9383: 	my $operand='|';
                   9384: 	my @stack;
                   9385: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   9386: 	    if ($chunk eq '(') {
                   9387: 		push @stack,($operand,$result);
                   9388: 	    } elsif ($chunk eq ')') {
                   9389: 		my $before=pop @stack;
                   9390: 		if (pop @stack eq '&') {
                   9391: 		    $result=$result>$before?$before:$result;
                   9392: 		} else {
                   9393: 		    $result=$result>$before?$result:$before;
                   9394: 		}
                   9395: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   9396: 		$operand=$chunk;
                   9397: 	    } else {
                   9398: 		my $new=directcondval($chunk);
                   9399: 		if ($operand eq '&') {
                   9400: 		    $result=$result>$new?$new:$result;
                   9401: 		} else {
                   9402: 		    $result=$result>$new?$result:$new;
                   9403: 		}
                   9404: 	    }
                   9405: 	}
1.26      www      9406:     }
                   9407:     return $result;
1.421     albertel 9408: }
                   9409: 
                   9410: # ---------------------------------------------------- Devalidate courseresdata
                   9411: 
                   9412: sub devalidatecourseresdata {
                   9413:     my ($coursenum,$coursedomain)=@_;
                   9414:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9415:     &devalidate_cache_new('courseres',$hashid);
1.28      www      9416: }
                   9417: 
1.763     www      9418: 
1.200     www      9419: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     9420: #
                   9421: #  Parameters:
                   9422: #      $coursenum    - Number of the course.
                   9423: #      $coursedomain - Domain at which the course was created.
                   9424: #  Returns:
                   9425: #     A hash of the course parameters along (I think) with timestamps
                   9426: #     and version info.
1.877     foxr     9427: 
1.624     albertel 9428: sub get_courseresdata {
                   9429:     my ($coursenum,$coursedomain)=@_;
1.200     www      9430:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   9431:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9432:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 9433:     my %dumpreply;
1.417     albertel 9434:     unless (defined($cached)) {
1.624     albertel 9435: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 9436: 	$result=\%dumpreply;
1.251     albertel 9437: 	my ($tmp) = keys(%dumpreply);
                   9438: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 9439: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 9440: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   9441: 	    return $tmp;
1.416     albertel 9442: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 9443: 	    $result=undef;
1.599     albertel 9444: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 9445: 	}
                   9446:     }
1.624     albertel 9447:     return $result;
                   9448: }
                   9449: 
1.633     albertel 9450: sub devalidateuserresdata {
                   9451:     my ($uname,$udom)=@_;
                   9452:     my $hashid="$udom:$uname";
                   9453:     &devalidate_cache_new('userres',$hashid);
                   9454: }
                   9455: 
1.624     albertel 9456: sub get_userresdata {
                   9457:     my ($uname,$udom)=@_;
                   9458:     #most student don\'t have any data set, check if there is some data
                   9459:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   9460: 
                   9461:     my $hashid="$udom:$uname";
                   9462:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   9463:     if (!defined($cached)) {
                   9464: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   9465: 	$result=\%resourcedata;
                   9466: 	&do_cache_new('userres',$hashid,$result,600);
                   9467:     }
                   9468:     my ($tmp)=keys(%$result);
                   9469:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   9470: 	return $result;
                   9471:     }
                   9472:     #error 2 occurs when the .db doesn't exist
                   9473:     if ($tmp!~/error: 2 /) {
1.672     albertel 9474: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 9475: 		 " Trying to get resource data for ".
                   9476: 		 $uname." at ".$udom.": ".
                   9477: 		 $tmp."</font>");
                   9478:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 9479: 	#&EXT_cache_set($udom,$uname);
                   9480: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 9481: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 9482:     }
                   9483:     return $tmp;
                   9484: }
1.879     foxr     9485: #----------------------------------------------- resdata - return resource data
                   9486: #  Purpose:
                   9487: #    Return resource data for either users or for a course.
                   9488: #  Parameters:
                   9489: #     $name      - Course/user name.
                   9490: #     $domain    - Name of the domain the user/course is registered on.
                   9491: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   9492: #     @which     - Array of names of resources desired.
                   9493: #  Returns:
                   9494: #     The value of the first reasource in @which that is found in the
                   9495: #     resource hash.
                   9496: #  Exceptional Conditions:
                   9497: #     If the $type passed in is not valid (not the string 'course' or 
                   9498: #     'user', an undefined  reference is returned.
                   9499: #     If none of the resources are found, an undef is returned
1.624     albertel 9500: sub resdata {
                   9501:     my ($name,$domain,$type,@which)=@_;
                   9502:     my $result;
                   9503:     if ($type eq 'course') {
                   9504: 	$result=&get_courseresdata($name,$domain);
                   9505:     } elsif ($type eq 'user') {
                   9506: 	$result=&get_userresdata($name,$domain);
                   9507:     }
                   9508:     if (!ref($result)) { return $result; }    
1.251     albertel 9509:     foreach my $item (@which) {
1.927     albertel 9510: 	if (defined($result->{$item->[0]})) {
                   9511: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 9512: 	}
1.250     albertel 9513:     }
1.291     albertel 9514:     return undef;
1.200     www      9515: }
                   9516: 
1.379     matthew  9517: #
                   9518: # EXT resource caching routines
                   9519: #
                   9520: 
                   9521: sub clear_EXT_cache_status {
1.383     albertel 9522:     &delenv('cache.EXT.');
1.379     matthew  9523: }
                   9524: 
                   9525: sub EXT_cache_status {
                   9526:     my ($target_domain,$target_user) = @_;
1.383     albertel 9527:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 9528:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  9529:         # We know already the user has no data
                   9530:         return 1;
                   9531:     } else {
                   9532:         return 0;
                   9533:     }
                   9534: }
                   9535: 
                   9536: sub EXT_cache_set {
                   9537:     my ($target_domain,$target_user) = @_;
1.383     albertel 9538:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  9539:     #&appenv({$cachename => time});
1.379     matthew  9540: }
                   9541: 
1.28      www      9542: # --------------------------------------------------------- Value of a Variable
1.58      www      9543: sub EXT {
1.715     albertel 9544: 
1.395     albertel 9545:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      9546:     unless ($varname) { return ''; }
1.218     albertel 9547:     #get real user name/domain, courseid and symb
                   9548:     my $courseid;
1.359     albertel 9549:     my $publicuser;
1.427     www      9550:     if ($symbparm) {
                   9551: 	$symbparm=&get_symb_from_alias($symbparm);
                   9552:     }
1.218     albertel 9553:     if (!($uname && $udom)) {
1.790     albertel 9554:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 9555:       if (!$symbparm) {	$symbparm=$cursymb; }
                   9556:     } else {
1.620     albertel 9557: 	$courseid=$env{'request.course.id'};
1.218     albertel 9558:     }
1.48      www      9559:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   9560:     my $rest;
1.320     albertel 9561:     if (defined($therest[0])) {
1.48      www      9562:        $rest=join('.',@therest);
                   9563:     } else {
                   9564:        $rest='';
                   9565:     }
1.320     albertel 9566: 
1.57      www      9567:     my $qualifierrest=$qualifier;
                   9568:     if ($rest) { $qualifierrest.='.'.$rest; }
                   9569:     my $spacequalifierrest=$space;
                   9570:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      9571:     if ($realm eq 'user') {
1.48      www      9572: # --------------------------------------------------------------- user.resource
                   9573: 	if ($space eq 'resource') {
1.651     albertel 9574: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   9575: 		  || defined($Apache::lonhomework::parsing_a_task))
                   9576: 		 &&
1.744     albertel 9577: 		 ($symbparm eq &symbread()) ) {	
                   9578: 		# if we are in the middle of processing the resource the
                   9579: 		# get the value we are planning on committing
                   9580:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   9581:                     return $Apache::lonhomework::results{$qualifierrest};
                   9582:                 } else {
                   9583:                     return $Apache::lonhomework::history{$qualifierrest};
                   9584:                 }
1.335     albertel 9585: 	    } else {
1.359     albertel 9586: 		my %restored;
1.620     albertel 9587: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 9588: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   9589: 		} else {
                   9590: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   9591: 		}
1.335     albertel 9592: 		return $restored{$qualifierrest};
                   9593: 	    }
1.48      www      9594: # ----------------------------------------------------------------- user.access
                   9595:         } elsif ($space eq 'access') {
1.218     albertel 9596: 	    # FIXME - not supporting calls for a specific user
1.48      www      9597:             return &allowed($qualifier,$rest);
                   9598: # ------------------------------------------ user.preferences, user.environment
                   9599:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 9600: 	    if (($uname eq $env{'user.name'}) &&
                   9601: 		($udom eq $env{'user.domain'})) {
                   9602: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 9603: 	    } else {
1.359     albertel 9604: 		my %returnhash;
                   9605: 		if (!$publicuser) {
                   9606: 		    %returnhash=&userenvironment($udom,$uname,
                   9607: 						 $qualifierrest);
                   9608: 		}
1.218     albertel 9609: 		return $returnhash{$qualifierrest};
                   9610: 	    }
1.48      www      9611: # ----------------------------------------------------------------- user.course
                   9612:         } elsif ($space eq 'course') {
1.218     albertel 9613: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9614:             return $env{join('.',('request.course',$qualifier))};
1.48      www      9615: # ------------------------------------------------------------------- user.role
                   9616:         } elsif ($space eq 'role') {
1.218     albertel 9617: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9618:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      9619:             if ($qualifier eq 'value') {
                   9620: 		return $role;
                   9621:             } elsif ($qualifier eq 'extent') {
                   9622:                 return $where;
                   9623:             }
                   9624: # ----------------------------------------------------------------- user.domain
                   9625:         } elsif ($space eq 'domain') {
1.218     albertel 9626:             return $udom;
1.48      www      9627: # ------------------------------------------------------------------- user.name
                   9628:         } elsif ($space eq 'name') {
1.218     albertel 9629:             return $uname;
1.48      www      9630: # ---------------------------------------------------- Any other user namespace
1.29      www      9631:         } else {
1.359     albertel 9632: 	    my %reply;
                   9633: 	    if (!$publicuser) {
                   9634: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   9635: 	    }
                   9636: 	    return $reply{$qualifierrest};
1.48      www      9637:         }
1.236     www      9638:     } elsif ($realm eq 'query') {
                   9639: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 9640:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   9641: 						[$spacequalifierrest]);
1.620     albertel 9642: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      9643:    } elsif ($realm eq 'request') {
1.48      www      9644: # ------------------------------------------------------------- request.browser
                   9645:         if ($space eq 'browser') {
1.1145    bisitz   9646:             return $env{'browser.'.$qualifier};
1.57      www      9647: # ------------------------------------------------------------ request.filename
                   9648:         } else {
1.620     albertel 9649:             return $env{'request.'.$spacequalifierrest};
1.29      www      9650:         }
1.28      www      9651:     } elsif ($realm eq 'course') {
1.48      www      9652: # ---------------------------------------------------------- course.description
1.620     albertel 9653:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      9654:     } elsif ($realm eq 'resource') {
1.165     www      9655: 
1.620     albertel 9656: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 9657: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   9658: 	}
1.693     albertel 9659: 
                   9660: 	if ($space eq 'title') {
                   9661: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   9662: 	    return &gettitle($symbparm);
                   9663: 	}
                   9664: 	
                   9665: 	if ($space eq 'map') {
                   9666: 	    my ($map) = &decode_symb($symbparm);
                   9667: 	    return &symbread($map);
                   9668: 	}
1.905     albertel 9669: 	if ($space eq 'filename') {
                   9670: 	    if ($symbparm) {
                   9671: 		return &clutter((&decode_symb($symbparm))[2]);
                   9672: 	    }
                   9673: 	    return &hreflocation('',$env{'request.filename'});
                   9674: 	}
1.693     albertel 9675: 
                   9676: 	my ($section, $group, @groups);
1.593     albertel 9677: 	my ($courselevelm,$courselevel);
1.539     albertel 9678: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9679: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      9680: 
1.218     albertel 9681: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      9682: 
1.60      www      9683: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 9684: 	    my $symbp=$symbparm;
1.735     albertel 9685: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 9686: 
                   9687: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   9688: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   9689: 
1.620     albertel 9690: 	    if (($env{'user.name'} eq $uname) &&
                   9691: 		($env{'user.domain'} eq $udom)) {
                   9692: 		$section=$env{'request.course.sec'};
1.733     raeburn  9693:                 @groups = split(/:/,$env{'request.course.groups'});  
                   9694:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 9695: 	    } else {
1.539     albertel 9696: 		if (! defined($usection)) {
1.551     albertel 9697: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 9698: 		} else {
                   9699: 		    $section = $usection;
                   9700: 		}
1.733     raeburn  9701:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 9702: 	    }
                   9703: 
                   9704: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   9705: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   9706: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   9707: 
1.593     albertel 9708: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 9709: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 9710: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      9711: 
1.60      www      9712: # ----------------------------------------------------------- first, check user
1.624     albertel 9713: 
                   9714: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 9715: 				       ([$courselevelr,'resource'],
                   9716: 					[$courselevelm,'map'     ],
                   9717: 					[$courselevel, 'course'  ]));
1.931     albertel 9718: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      9719: 
1.594     albertel 9720: # ------------------------------------------------ second, check some of course
1.684     raeburn  9721:             my $coursereply;
1.691     raeburn  9722:             if (@groups > 0) {
                   9723:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   9724:                                        $mapparm,$spacequalifierrest);
1.927     albertel 9725:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  9726:             }
1.96      www      9727: 
1.684     raeburn  9728: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 9729: 				  $env{'course.'.$courseid.'.domain'},
                   9730: 				  'course',
                   9731: 				  ([$seclevelr,   'resource'],
                   9732: 				   [$seclevelm,   'map'     ],
                   9733: 				   [$seclevel,    'course'  ],
                   9734: 				   [$courselevelr,'resource']));
                   9735: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      9736: 
1.60      www      9737: # ------------------------------------------------------ third, check map parms
1.218     albertel 9738: 	    my %parmhash=();
                   9739: 	    my $thisparm='';
                   9740: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 9741: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 9742: 		    &GDBM_READER(),0640)) {
1.218     albertel 9743: 		$thisparm=$parmhash{$symbparm};
                   9744: 		untie(%parmhash);
                   9745: 	    }
1.927     albertel 9746: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 9747: 	}
1.594     albertel 9748: # ------------------------------------------ fourth, look in resource metadata
1.71      www      9749: 
1.218     albertel 9750: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 9751: 	my $filename;
                   9752: 	if (!$symbparm) { $symbparm=&symbread(); }
                   9753: 	if ($symbparm) {
1.409     www      9754: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 9755: 	} else {
1.620     albertel 9756: 	    $filename=$env{'request.filename'};
1.282     albertel 9757: 	}
                   9758: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 9759: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 9760: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 9761: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      9762: 
1.927     albertel 9763: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 9764: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9765: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 9766: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   9767: 				     $env{'course.'.$courseid.'.domain'},
                   9768: 				     'course',
1.927     albertel 9769: 				     ([$courselevelm,'map'   ],
                   9770: 				      [$courselevel, 'course']));
                   9771: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 9772: 	}
1.145     www      9773: # ------------------------------------------------------------------ Cascade up
1.218     albertel 9774: 	unless ($space eq '0') {
1.336     albertel 9775: 	    my @parts=split(/_/,$space);
                   9776: 	    my $id=pop(@parts);
                   9777: 	    my $part=join('_',@parts);
                   9778: 	    if ($part eq '') { $part='0'; }
1.927     albertel 9779: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 9780: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  9781: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 9782: 	}
1.395     albertel 9783: 	if ($recurse) { return undef; }
                   9784: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 9785: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      9786: # ---------------------------------------------------- Any other user namespace
                   9787:     } elsif ($realm eq 'environment') {
                   9788: # ----------------------------------------------------------------- environment
1.620     albertel 9789: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   9790: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 9791: 	} else {
1.770     albertel 9792: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   9793: 		return '';
                   9794: 	    }
1.219     albertel 9795: 	    my %returnhash=&userenvironment($udom,$uname,
                   9796: 					    $spacequalifierrest);
                   9797: 	    return $returnhash{$spacequalifierrest};
                   9798: 	}
1.28      www      9799:     } elsif ($realm eq 'system') {
1.48      www      9800: # ----------------------------------------------------------------- system.time
                   9801: 	if ($space eq 'time') {
                   9802: 	    return time;
                   9803:         }
1.696     albertel 9804:     } elsif ($realm eq 'server') {
                   9805: # ----------------------------------------------------------------- system.time
                   9806: 	if ($space eq 'name') {
                   9807: 	    return $ENV{'SERVER_NAME'};
                   9808:         }
1.28      www      9809:     }
1.48      www      9810:     return '';
1.61      www      9811: }
                   9812: 
1.927     albertel 9813: sub get_reply {
                   9814:     my ($reply_value) = @_;
1.940     raeburn  9815:     if (ref($reply_value) eq 'ARRAY') {
                   9816:         if (wantarray) {
                   9817: 	    return @$reply_value;
                   9818:         }
                   9819:         return $reply_value->[0];
                   9820:     } else {
                   9821:         return $reply_value;
1.927     albertel 9822:     }
                   9823: }
                   9824: 
1.691     raeburn  9825: sub check_group_parms {
                   9826:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   9827:     my @groupitems = ();
                   9828:     my $resultitem;
1.927     albertel 9829:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  9830:     foreach my $group (@{$groups}) {
                   9831:         foreach my $level (@levels) {
1.927     albertel 9832:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   9833:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  9834:         }
                   9835:     }
                   9836:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   9837:                             $env{'course.'.$courseid.'.domain'},
                   9838:                                      'course',@groupitems);
                   9839:     return $coursereply;
                   9840: }
                   9841: 
                   9842: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  9843:     my ($courseid,@groups) = @_;
                   9844:     @groups = sort(@groups);
1.691     raeburn  9845:     return @groups;
                   9846: }
                   9847: 
1.395     albertel 9848: sub packages_tab_default {
                   9849:     my ($uri,$varname)=@_;
                   9850:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 9851: 
                   9852:     my (@extension,@specifics,$do_default);
                   9853:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 9854: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 9855: 	if ($pack_type eq 'default') {
                   9856: 	    $do_default=1;
                   9857: 	} elsif ($pack_type eq 'extension') {
                   9858: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 9859: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 9860: 	    # only look at packages defaults for packages that this id is
1.738     albertel 9861: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   9862: 	}
                   9863:     }
                   9864:     # first look for a package that matches the requested part id
                   9865:     foreach my $package (@specifics) {
                   9866: 	my (undef,$pack_type,$pack_part)=@{$package};
                   9867: 	next if ($pack_part ne $part);
                   9868: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9869: 	    return $packagetab{"$pack_type&$name&default"};
                   9870: 	}
                   9871:     }
                   9872:     # look for any possible matching non extension_ package
                   9873:     foreach my $package (@specifics) {
                   9874: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 9875: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9876: 	    return $packagetab{"$pack_type&$name&default"};
                   9877: 	}
1.585     albertel 9878: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 9879: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   9880: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 9881: 	}
                   9882:     }
1.738     albertel 9883:     # look for any posible extension_ match
                   9884:     foreach my $package (@extension) {
                   9885: 	my ($package,$pack_type)=@{$package};
                   9886: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9887: 	    return $packagetab{"$pack_type&$name&default"};
                   9888: 	}
                   9889: 	if (defined($packagetab{$package."&$name&default"})) {
                   9890: 	    return $packagetab{$package."&$name&default"};
                   9891: 	}
                   9892:     }
                   9893:     # look for a global default setting
                   9894:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   9895: 	return $packagetab{"default&$name&default"};
                   9896:     }
1.395     albertel 9897:     return undef;
                   9898: }
                   9899: 
1.334     albertel 9900: sub add_prefix_and_part {
                   9901:     my ($prefix,$part)=@_;
                   9902:     my $keyroot;
                   9903:     if (defined($prefix) && $prefix !~ /^__/) {
                   9904: 	# prefix that has a part already
                   9905: 	$keyroot=$prefix;
                   9906:     } elsif (defined($prefix)) {
                   9907: 	# prefix that is missing a part
                   9908: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   9909:     } else {
                   9910: 	# no prefix at all
                   9911: 	if (defined($part)) { $keyroot='_'.$part; }
                   9912:     }
                   9913:     return $keyroot;
                   9914: }
                   9915: 
1.71      www      9916: # ---------------------------------------------------------------- Get metadata
                   9917: 
1.599     albertel 9918: my %metaentry;
1.1070    www      9919: my %importedpartids;
1.71      www      9920: sub metadata {
1.176     www      9921:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      9922:     $uri=&declutter($uri);
1.288     albertel 9923:     # if it is a non metadata possible uri return quickly
1.529     albertel 9924:     if (($uri eq '') || 
                   9925: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  9926: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  9927:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 9928: 	return undef;
                   9929:     }
1.1140    www      9930:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
1.924     albertel 9931: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 9932: 	return undef;
1.288     albertel 9933:     }
1.73      www      9934:     my $filename=$uri;
                   9935:     $uri=~s/\.meta$//;
1.172     www      9936: #
                   9937: # Is the metadata already cached?
1.177     www      9938: # Look at timestamp of caching
1.172     www      9939: # Everything is cached by the main uri, libraries are never directly cached
                   9940: #
1.428     albertel 9941:     if (!defined($liburi)) {
1.599     albertel 9942: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 9943: 	if (defined($cached)) { return $result->{':'.$what}; }
                   9944:     }
                   9945:     {
1.1069    www      9946: # Imported parts would go here
1.1070    www      9947:         my %importedids=();
                   9948:         my @origfileimportpartids=();
1.1069    www      9949:         my $importedparts=0;
1.172     www      9950: #
                   9951: # Is this a recursive call for a library?
                   9952: #
1.599     albertel 9953: #	if (! exists($metacache{$uri})) {
                   9954: #	    $metacache{$uri}={};
                   9955: #	}
1.924     albertel 9956: 	my $cachetime = 60*60;
1.171     www      9957:         if ($liburi) {
                   9958: 	    $liburi=&declutter($liburi);
                   9959:             $filename=$liburi;
1.401     bowersj2 9960:         } else {
1.599     albertel 9961: 	    &devalidate_cache_new('meta',$uri);
                   9962: 	    undef(%metaentry);
1.401     bowersj2 9963: 	}
1.140     www      9964:         my %metathesekeys=();
1.73      www      9965:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 9966: 	my $metastring;
1.1140    www      9967: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 9968: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 9969: 	    $metastring = 
1.929     albertel 9970: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 9971: 					  ('grade_target' => 'meta'));
                   9972: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  9973: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   9974:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 9975: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 9976: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 9977: 	    $metastring=&getfile($file);
1.489     albertel 9978: 	}
1.208     albertel 9979:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      9980:         my $token;
1.140     www      9981:         undef %metathesekeys;
1.71      www      9982:         while ($token=$parser->get_token) {
1.339     albertel 9983: 	    if ($token->[0] eq 'S') {
                   9984: 		if (defined($token->[2]->{'package'})) {
1.172     www      9985: #
                   9986: # This is a package - get package info
                   9987: #
1.339     albertel 9988: 		    my $package=$token->[2]->{'package'};
                   9989: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9990: 		    if (defined($token->[2]->{'id'})) { 
                   9991: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   9992: 		    }
1.599     albertel 9993: 		    if ($metaentry{':packages'}) {
                   9994: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 9995: 		    } else {
1.599     albertel 9996: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 9997: 		    }
1.736     albertel 9998: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 9999: 			my $part=$keyroot;
                   10000: 			$part=~s/^\_//;
1.736     albertel 10001: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   10002: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   10003: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 10004: 			    # ignore package.tab specified default values
                   10005:                             # here &package_tab_default() will fetch those
                   10006: 			    if ($subp eq 'default') { next; }
1.736     albertel 10007: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 10008: 			    my $unikey;
                   10009: 			    if ($pack =~ /_0$/) {
                   10010: 				$unikey='parameter_0_'.$name;
                   10011: 				$part=0;
                   10012: 			    } else {
                   10013: 				$unikey='parameter'.$keyroot.'_'.$name;
                   10014: 			    }
1.339     albertel 10015: 			    if ($subp eq 'display') {
                   10016: 				$value.=' [Part: '.$part.']';
                   10017: 			    }
1.599     albertel 10018: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 10019: 			    $metathesekeys{$unikey}=1;
1.599     albertel 10020: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10021: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 10022: 			    }
1.599     albertel 10023: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   10024: 				$metaentry{':'.$unikey}=
                   10025: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 10026: 			    }
1.339     albertel 10027: 			}
                   10028: 		    }
                   10029: 		} else {
1.172     www      10030: #
                   10031: # This is not a package - some other kind of start tag
1.339     albertel 10032: #
                   10033: 		    my $entry=$token->[1];
1.1068    www      10034: 		    my $unikey='';
1.175     www      10035: 
1.339     albertel 10036: 		    if ($entry eq 'import') {
1.175     www      10037: #
                   10038: # Importing a library here
1.339     albertel 10039: #
1.1067    www      10040:                         my $location=$parser->get_text('/import');
                   10041:                         my $dir=$filename;
                   10042:                         $dir=~s|[^/]*$||;
                   10043:                         $location=&filelocation($dir,$location);
1.1069    www      10044:                        
1.1068    www      10045:                         my $importmode=$token->[2]->{'importmode'};
                   10046:                         if ($importmode eq 'problem') {
1.1069    www      10047: # Import as problem/response
1.1068    www      10048:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10049:                         } elsif ($importmode eq 'part') {
                   10050: # Import as part(s)
1.1069    www      10051:                            $importedparts=1;
                   10052: # We need to get the original file and the imported file to get the part order correct
                   10053: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   10054: # Load and inspect original file
1.1070    www      10055:                            if ($#origfileimportpartids<0) {
                   10056:                               undef(%importedpartids);
                   10057:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   10058:                               my $origfile=&getfile($origfilelocation);
                   10059:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10060:                            }
                   10061: 
1.1069    www      10062: # Load and inspect imported file
                   10063:                            my $impfile=&getfile($location);
                   10064:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10065:                            if ($#impfilepartids>=0) {
                   10066: # This problem had parts
1.1070    www      10067:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      10068:                            } else {
                   10069: # Importing by turning a single problem into a problem part
                   10070: # It gets the import-tags ID as part-ID
                   10071:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      10072:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      10073:                            }
1.1068    www      10074:                         } else {
                   10075: # Normal import
                   10076:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10077:                            if (defined($token->[2]->{'id'})) {
                   10078:                               $unikey.='_'.$token->[2]->{'id'};
                   10079:                            }
1.1067    www      10080:                         }
                   10081: 
1.339     albertel 10082: 			if ($depthcount<20) {
1.736     albertel 10083: 			    my $metadata = 
                   10084: 				&metadata($uri,'keys', $location,$unikey,
                   10085: 					  $depthcount+1);
                   10086: 			    foreach my $meta (split(',',$metadata)) {
                   10087: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   10088: 				$metathesekeys{$meta}=1;
1.339     albertel 10089: 			    }
1.1068    www      10090: 			
                   10091:                         }
1.1067    www      10092: 		    } else {
                   10093: #
                   10094: # Not importing, some other kind of non-package, non-library start tag
                   10095: # 
                   10096:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10097:                         if (defined($token->[2]->{'id'})) {
                   10098:                             $unikey.='_'.$token->[2]->{'id'};
                   10099:                         }
1.339     albertel 10100: 			if (defined($token->[2]->{'name'})) { 
                   10101: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   10102: 			}
                   10103: 			$metathesekeys{$unikey}=1;
1.736     albertel 10104: 			foreach my $param (@{$token->[3]}) {
                   10105: 			    $metaentry{':'.$unikey.'.'.$param} =
                   10106: 				$token->[2]->{$param};
1.339     albertel 10107: 			}
                   10108: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 10109: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 10110: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   10111: 		 # only ws inside the tag, and not in default, so use default
                   10112: 		 # as value
1.599     albertel 10113: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 10114: 			} elsif ( $internaltext =~ /\S/ ) {
                   10115: 		  # something interesting inside the tag
                   10116: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 10117: 			} else {
1.908     albertel 10118: 		  # no interesting values, don't set a default
1.339     albertel 10119: 			}
1.172     www      10120: # end of not-a-package not-a-library import
1.339     albertel 10121: 		    }
1.172     www      10122: # end of not-a-package start tag
1.339     albertel 10123: 		}
1.172     www      10124: # the next is the end of "start tag"
1.339     albertel 10125: 	    }
                   10126: 	}
1.483     albertel 10127: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 10128: 	$extension = lc($extension);
                   10129: 	if ($extension eq 'htm') { $extension='html'; }
                   10130: 
1.737     albertel 10131: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 10132: 	    #no specific packages #how's our extension
                   10133: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 10134: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 10135: 					 \%metathesekeys);
                   10136: 	}
1.883     albertel 10137: 
                   10138: 	if (!exists($metaentry{':packages'})
                   10139: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 10140: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 10141: 		#no specific packages well let's get default then
                   10142: 		if ($key!~/^default&/) { next; }
1.488     albertel 10143: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 10144: 					     \%metathesekeys);
                   10145: 	    }
                   10146: 	}
1.338     www      10147: # are there custom rights to evaluate
1.599     albertel 10148: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 10149: 
1.338     www      10150:     #
                   10151:     # Importing a rights file here
1.339     albertel 10152:     #
                   10153: 	    unless ($depthcount) {
1.599     albertel 10154: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 10155: 		my $dir=$filename;
                   10156: 		$dir=~s|[^/]*$||;
                   10157: 		$location=&filelocation($dir,$location);
1.736     albertel 10158: 		my $rights_metadata =
                   10159: 		    &metadata($uri,'keys',$location,'_rights',
                   10160: 			      $depthcount+1);
                   10161: 		foreach my $rights (split(',',$rights_metadata)) {
                   10162: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   10163: 		    $metathesekeys{$rights}=1;
1.339     albertel 10164: 		}
                   10165: 	    }
                   10166: 	}
1.737     albertel 10167: 	# uniqifiy package listing
                   10168: 	my %seen;
                   10169: 	my @uniq_packages =
                   10170: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   10171: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   10172: 
1.1070    www      10173:         if ($importedparts) {
                   10174: # We had imported parts and need to rebuild partorder
                   10175:            $metaentry{':partorder'}='';
                   10176:            $metathesekeys{'partorder'}=1;
                   10177:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   10178:                if ($origfileimportpartids[$index] eq 'part') {
                   10179: # original part, part of the problem
                   10180:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   10181:                } else {
                   10182: # we have imported parts at this position
                   10183:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   10184:                }
                   10185:            }
                   10186:            $metaentry{':partorder'}=~s/^\,//;
                   10187:         }
                   10188: 
1.737     albertel 10189: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 10190: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   10191: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 10192: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      10193: # this is the end of "was not already recently cached
1.71      www      10194:     }
1.599     albertel 10195:     return $metaentry{':'.$what};
1.261     albertel 10196: }
                   10197: 
1.488     albertel 10198: sub metadata_create_package_def {
1.483     albertel 10199:     my ($uri,$key,$package,$metathesekeys)=@_;
                   10200:     my ($pack,$name,$subp)=split(/\&/,$key);
                   10201:     if ($subp eq 'default') { next; }
                   10202:     
1.599     albertel 10203:     if (defined($metaentry{':packages'})) {
                   10204: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 10205:     } else {
1.599     albertel 10206: 	$metaentry{':packages'}=$package;
1.483     albertel 10207:     }
                   10208:     my $value=$packagetab{$key};
                   10209:     my $unikey;
                   10210:     $unikey='parameter_0_'.$name;
1.599     albertel 10211:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 10212:     $$metathesekeys{$unikey}=1;
1.599     albertel 10213:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10214: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 10215:     }
1.599     albertel 10216:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   10217: 	$metaentry{':'.$unikey}=
                   10218: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 10219:     }
                   10220: }
                   10221: 
1.261     albertel 10222: sub metadata_generate_part0 {
                   10223:     my ($metadata,$metacache,$uri) = @_;
                   10224:     my %allnames;
1.737     albertel 10225:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 10226: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 10227: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   10228: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 10229: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 10230: 	    $allnames{$name}=$part;
                   10231: 	  }
                   10232: 	}
                   10233:     }
                   10234:     foreach my $name (keys(%allnames)) {
                   10235:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 10236:       my $key=":parameter_0_$name";
1.261     albertel 10237:       $$metacache{"$key.part"}='0';
                   10238:       $$metacache{"$key.name"}=$name;
1.428     albertel 10239:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 10240: 					   $allnames{$name}.'_'.$name.
                   10241: 					   '.type'};
1.428     albertel 10242:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 10243: 			     '.display'};
1.644     www      10244:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 10245:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 10246:       $$metacache{"$key.display"}=$olddis;
                   10247:     }
1.71      www      10248: }
                   10249: 
1.764     albertel 10250: # ------------------------------------------------------ Devalidate title cache
                   10251: 
                   10252: sub devalidate_title_cache {
                   10253:     my ($url)=@_;
                   10254:     if (!$env{'request.course.id'}) { return; }
                   10255:     my $symb=&symbread($url);
                   10256:     if (!$symb) { return; }
                   10257:     my $key=$env{'request.course.id'}."\0".$symb;
                   10258:     &devalidate_cache_new('title',$key);
                   10259: }
                   10260: 
1.1014    droeschl 10261: # ------------------------------------------------- Get the title of a course
                   10262: 
                   10263: sub current_course_title {
                   10264:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   10265: }
1.301     www      10266: # ------------------------------------------------- Get the title of a resource
                   10267: 
                   10268: sub gettitle {
                   10269:     my $urlsymb=shift;
                   10270:     my $symb=&symbread($urlsymb);
1.534     albertel 10271:     if ($symb) {
1.620     albertel 10272: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 10273: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 10274: 	if (defined($cached)) { 
                   10275: 	    return $result;
                   10276: 	}
1.534     albertel 10277: 	my ($map,$resid,$url)=&decode_symb($symb);
                   10278: 	my $title='';
1.907     albertel 10279: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   10280: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   10281: 	} else {
                   10282: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10283: 		    &GDBM_READER(),0640)) {
                   10284: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   10285: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   10286: 		untie(%bighash);
                   10287: 	    }
1.534     albertel 10288: 	}
                   10289: 	$title=~s/\&colon\;/\:/gs;
                   10290: 	if ($title) {
1.1159    www      10291: # Remember both $symb and $title for dynamic metadata
                   10292:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      10293:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      10294: # Cache this title and then return it
1.599     albertel 10295: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 10296: 	}
                   10297: 	$urlsymb=$url;
                   10298:     }
                   10299:     my $title=&metadata($urlsymb,'title');
                   10300:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   10301:     return $title;
1.301     www      10302: }
1.613     albertel 10303: 
1.1172.2.13  raeburn  10304: sub getdocspath {
                   10305:     my ($symb) = @_;
                   10306:     my $path;
                   10307:     if ($symb) {
                   10308:         my ($mapurl,$id,$resurl) = &decode_symb($symb);
                   10309:         if ($resurl=~/\.(sequence|page)$/) {
                   10310:             $mapurl=$resurl;
                   10311:         } elsif ($resurl eq 'adm/navmaps') {
                   10312:             $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   10313:         }
                   10314:         my $mapresobj;
                   10315:         my $navmap = Apache::lonnavmaps::navmap->new();
                   10316:         if (ref($navmap)) {
                   10317:             $mapresobj = $navmap->getResourceByUrl($mapurl);
                   10318:         }
                   10319:         $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   10320:         my $type=$2;
                   10321:         if (ref($mapresobj)) {
                   10322:             my $pcslist = $mapresobj->map_hierarchy();
                   10323:             if ($pcslist ne '') {
                   10324:                 foreach my $pc (split(/,/,$pcslist)) {
                   10325:                     next if ($pc <= 1);
                   10326:                     my $res = $navmap->getByMapPc($pc);
                   10327:                     if (ref($res)) {
                   10328:                         my $thisurl = $res->src();
                   10329:                         $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   10330:                         my $thistitle = $res->title();
                   10331:                         $path .= '&'.
                   10332:                                  &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
                   10333:                                  &Apache::lonhtmlcommon::entity_encode($thistitle).
                   10334:                                  ':'.$res->randompick().
                   10335:                                  ':'.$res->randomout().
                   10336:                                  ':'.$res->encrypted().
                   10337:                                  ':'.$res->randomorder().
                   10338:                                  ':'.$res->is_page();
                   10339:                     }
                   10340:                 }
                   10341:             }
                   10342:             $path =~ s/^\&//;
                   10343:             my $maptitle = $mapresobj->title();
                   10344:             if ($mapurl eq 'default') {
                   10345:                 $maptitle = 'Main Course Documents';
                   10346:             }
                   10347:             $path .= ($path ne '')? '&' : ''.
                   10348:                     &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
                   10349:                     &Apache::lonhtmlcommon::entity_encode($maptitle).
                   10350:                     ':'.$mapresobj->randompick().
                   10351:                     ':'.$mapresobj->randomout().
                   10352:                     ':'.$mapresobj->encrypted().
                   10353:                     ':'.$mapresobj->randomorder().
                   10354:                     ':'.$mapresobj->is_page();
                   10355:         } else {
                   10356:             my $maptitle = &gettitle($mapurl);
                   10357:             my $ispage;
                   10358:             if ($mapurl =~ /\.page$/) {
                   10359:                 $ispage = 1;
                   10360:             }
                   10361:             if ($mapurl eq 'default') {
                   10362:                 $maptitle = 'Main Course Documents';
                   10363:             }
                   10364:             $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
                   10365:                     &Apache::lonhtmlcommon::entity_encode($maptitle).':::::'.$ispage;
                   10366:         }
                   10367:         unless ($mapurl eq 'default') {
                   10368:             $path = 'default&'.
                   10369:                     &Apache::lonhtmlcommon::entity_encode('Main Course Documents').
                   10370:                     ':::::&'.$path;
                   10371:         }
                   10372:     }
                   10373:     return $path;
                   10374: }
                   10375: 
1.614     albertel 10376: sub get_slot {
                   10377:     my ($which,$cnum,$cdom)=@_;
                   10378:     if (!$cnum || !$cdom) {
1.790     albertel 10379: 	(undef,my $courseid)=&whichuser();
1.620     albertel 10380: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   10381: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 10382:     }
1.703     albertel 10383:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   10384:     my %slotinfo;
                   10385:     if (exists($remembered{$key})) {
                   10386: 	$slotinfo{$which} = $remembered{$key};
                   10387:     } else {
                   10388: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   10389: 	&Apache::lonhomework::showhash(%slotinfo);
                   10390: 	my ($tmp)=keys(%slotinfo);
                   10391: 	if ($tmp=~/^error:/) { return (); }
                   10392: 	$remembered{$key} = $slotinfo{$which};
                   10393:     }
1.616     albertel 10394:     if (ref($slotinfo{$which}) eq 'HASH') {
                   10395: 	return %{$slotinfo{$which}};
                   10396:     }
                   10397:     return $slotinfo{$which};
1.614     albertel 10398: }
1.1150    raeburn  10399: 
                   10400: sub get_reservable_slots {
                   10401:     my ($cnum,$cdom,$uname,$udom) = @_;
                   10402:     my $now = time;
                   10403:     my $reservable_info;
                   10404:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   10405:     if (exists($remembered{$key})) {
                   10406:         $reservable_info = $remembered{$key};
                   10407:     } else {
                   10408:         my %resv;
                   10409:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   10410:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   10411:         $reservable_info = \%resv;
                   10412:         $remembered{$key} = $reservable_info;
                   10413:     }
                   10414:     return $reservable_info;
                   10415: }
                   10416: 
                   10417: sub get_course_slots {
                   10418:     my ($cnum,$cdom) = @_;
                   10419:     my $hashid=$cnum.':'.$cdom;
                   10420:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   10421:     if (defined($cached)) {
                   10422:         if (ref($result) eq 'HASH') {
                   10423:             return %{$result};
                   10424:         }
                   10425:     } else {
                   10426:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   10427:         my ($tmp) = keys(%slots);
                   10428:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   10429:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
                   10430:             return %slots;
                   10431:         }
                   10432:     }
                   10433:     return;
                   10434: }
                   10435: 
                   10436: sub devalidate_slots_cache {
                   10437:     my ($cnum,$cdom)=@_;
                   10438:     my $hashid=$cnum.':'.$cdom;
                   10439:     &devalidate_cache_new('allslots',$hashid);
                   10440: }
                   10441: 
1.1172.2.8  raeburn  10442: sub get_coursechange {
                   10443:     my ($cdom,$cnum) = @_;
                   10444:     if ($cdom eq '' || $cnum eq '') {
                   10445:         return unless ($env{'request.course.id'});
                   10446:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10447:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10448:     }
                   10449:     my $hashid=$cdom.'_'.$cnum;
                   10450:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   10451:     if ((defined($cached)) && ($change ne '')) {
                   10452:         return $change;
                   10453:     } else {
                   10454:         my %crshash;
                   10455:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   10456:         if ($crshash{'internal.contentchange'} eq '') {
                   10457:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   10458:             if ($change eq '') {
                   10459:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   10460:                 $change = $crshash{'internal.created'};
                   10461:             }
                   10462:         } else {
                   10463:             $change = $crshash{'internal.contentchange'};
                   10464:         }
                   10465:         my $cachetime = 600;
                   10466:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   10467:     }
                   10468:     return $change;
                   10469: }
                   10470: 
                   10471: sub devalidate_coursechange_cache {
                   10472:     my ($cnum,$cdom)=@_;
                   10473:     my $hashid=$cnum.':'.$cdom;
                   10474:     &devalidate_cache_new('crschange',$hashid);
                   10475: }
                   10476: 
1.31      www      10477: # ------------------------------------------------- Update symbolic store links
                   10478: 
                   10479: sub symblist {
                   10480:     my ($mapname,%newhash)=@_;
1.438     www      10481:     $mapname=&deversion(&declutter($mapname));
1.31      www      10482:     my %hash;
1.620     albertel 10483:     if (($env{'request.course.fn'}) && (%newhash)) {
                   10484:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10485:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  10486: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 10487: 		next if ($url eq 'last_known'
                   10488: 			 && $env{'form.no_update_last_known'});
                   10489: 		$hash{declutter($url)}=&encode_symb($mapname,
                   10490: 						    $newhash{$url}->[1],
                   10491: 						    $newhash{$url}->[0]);
1.191     harris41 10492:             }
1.31      www      10493:             if (untie(%hash)) {
                   10494: 		return 'ok';
                   10495:             }
                   10496:         }
                   10497:     }
                   10498:     return 'error';
1.212     www      10499: }
                   10500: 
                   10501: # --------------------------------------------------------------- Verify a symb
                   10502: 
                   10503: sub symbverify {
1.1172.2.11  raeburn  10504:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      10505:     my $thisfn=$thisurl;
1.439     www      10506:     $thisfn=&declutter($thisfn);
1.215     www      10507: # direct jump to resource in page or to a sequence - will construct own symbs
                   10508:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   10509: # check URL part
1.409     www      10510:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      10511: 
1.431     www      10512:     unless ($url eq $thisfn) { return 0; }
1.213     www      10513: 
1.216     www      10514:     $symb=&symbclean($symb);
1.510     www      10515:     $thisurl=&deversion($thisurl);
1.439     www      10516:     $thisfn=&deversion($thisfn);
1.213     www      10517: 
                   10518:     my %bighash;
                   10519:     my $okay=0;
1.431     www      10520: 
1.620     albertel 10521:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10522:                             &GDBM_READER(),0640)) {
1.1172.2.13  raeburn  10523:         my $noclutter;
1.1032    raeburn  10524:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   10525:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  10526:             if ($map =~ m{^uploaded/.+\.page$}) {
                   10527:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   10528:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   10529:                 $noclutter = 1;
                   10530:             }
                   10531:         }
                   10532:         my $ids;
                   10533:         if ($noclutter) {
                   10534:             $ids=$bighash{'ids_'.$thisurl};
                   10535:         } else {
                   10536:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  10537:         }
1.1102    raeburn  10538:         unless ($ids) {
1.1172.2.13  raeburn  10539:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  10540:             $ids=$bighash{$idkey};
1.216     www      10541:         }
                   10542:         if ($ids) {
                   10543: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  10544:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   10545:                 $symb =~ s/\?.+$//;
                   10546:             }
1.800     albertel 10547: 	    foreach my $id (split(/\,/,$ids)) {
                   10548: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      10549:                if (
                   10550:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  10551:    eq $symb) {
1.1172.2.11  raeburn  10552:                    if (ref($encstate)) {
                   10553:                        $$encstate = $bighash{'encrypted_'.$id};
                   10554:                    }
1.1172.2.13  raeburn  10555:                    if (($env{'request.role.adv'}) ||
                   10556:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  10557:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  10558:                        $okay=1;
                   10559:                        last;
                   10560:                    }
                   10561:                }
                   10562:            }
1.216     www      10563:         }
1.213     www      10564: 	untie(%bighash);
                   10565:     }
                   10566:     return $okay;
1.31      www      10567: }
                   10568: 
1.210     www      10569: # --------------------------------------------------------------- Clean-up symb
                   10570: 
                   10571: sub symbclean {
                   10572:     my $symb=shift;
1.568     albertel 10573:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      10574: # remove version from map
                   10575:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      10576: 
1.210     www      10577: # remove version from URL
                   10578:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      10579: 
1.507     www      10580: # remove wrapper
                   10581: 
1.510     www      10582:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 10583:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      10584:     return $symb;
1.409     www      10585: }
                   10586: 
                   10587: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 10588: 
                   10589: sub encode_symb {
                   10590:     my ($map,$resid,$url)=@_;
                   10591:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   10592: }
1.409     www      10593: 
                   10594: sub decode_symb {
1.568     albertel 10595:     my $symb=shift;
                   10596:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   10597:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      10598:     return (&fixversion($map),$resid,&fixversion($url));
                   10599: }
                   10600: 
                   10601: sub fixversion {
                   10602:     my $fn=shift;
1.609     banghart 10603:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      10604:     my %bighash;
                   10605:     my $uri=&clutter($fn);
1.620     albertel 10606:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      10607: # is this cached?
1.599     albertel 10608:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      10609:     if (defined($cached)) { return $result; }
                   10610: # unfortunately not cached, or expired
1.620     albertel 10611:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      10612: 	    &GDBM_READER(),0640)) {
                   10613:  	if ($bighash{'version_'.$uri}) {
                   10614:  	    my $version=$bighash{'version_'.$uri};
1.444     www      10615:  	    unless (($version eq 'mostrecent') || 
                   10616: 		    ($version==&getversion($uri))) {
1.440     www      10617:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   10618:  	    }
                   10619:  	}
                   10620:  	untie %bighash;
1.413     www      10621:     }
1.599     albertel 10622:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      10623: }
                   10624: 
                   10625: sub deversion {
                   10626:     my $url=shift;
                   10627:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   10628:     return $url;
1.210     www      10629: }
                   10630: 
1.31      www      10631: # ------------------------------------------------------ Return symb list entry
                   10632: 
                   10633: sub symbread {
1.249     www      10634:     my ($thisfn,$donotrecurse)=@_;
1.1172.2.13  raeburn  10635:     my $cache_str;
                   10636:     if ($thisfn ne '') {
                   10637:         $cache_str='request.symbread.cached.'.$thisfn;
                   10638:         if ($env{$cache_str} ne '') {
1.1172.2.8  raeburn  10639:             return $env{$cache_str};
                   10640:         }
1.1172.2.13  raeburn  10641:    } else {
1.242     www      10642: # no filename provided? try from environment
1.620     albertel 10643:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  10644:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   10645:         }
                   10646:         $thisfn=$env{'request.filename'};
1.44      www      10647:     }
1.569     albertel 10648:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      10649: # is that filename actually a symb? Verify, clean, and return
                   10650:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 10651: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 10652: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 10653: 	}
1.242     www      10654:     }
1.44      www      10655:     $thisfn=declutter($thisfn);
1.31      www      10656:     my %hash;
1.37      www      10657:     my %bighash;
                   10658:     my $syval='';
1.620     albertel 10659:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  10660:         my $targetfn = $thisfn;
1.609     banghart 10661:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  10662:             $targetfn = 'adm/wrapper/'.$thisfn;
                   10663:         }
1.687     albertel 10664: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   10665: 	    $targetfn=$1;
                   10666: 	}
1.620     albertel 10667:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10668:                       &GDBM_READER(),0640)) {
1.481     raeburn  10669: 	    $syval=$hash{$targetfn};
1.37      www      10670:             untie(%hash);
                   10671:         }
                   10672: # ---------------------------------------------------------- There was an entry
                   10673:         if ($syval) {
1.601     albertel 10674: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 10675: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  10676: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10677: 		    #return $env{$cache_str}='';
1.601     albertel 10678: 		#}    
                   10679: 		#$syval.=$1;
                   10680: 	    #}
1.37      www      10681:         } else {
                   10682: # ------------------------------------------------------- Was not in symb table
1.620     albertel 10683:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10684:                             &GDBM_READER(),0640)) {
1.37      www      10685: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      10686:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      10687:               unless ($ids) { 
                   10688:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      10689:               }
                   10690:               unless ($ids) {
                   10691: # alias?
                   10692: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      10693:               }
1.37      www      10694:               if ($ids) {
                   10695: # ------------------------------------------------------------------- Has ID(s)
                   10696:                  my @possibilities=split(/\,/,$ids);
1.39      www      10697:                  if ($#possibilities==0) {
                   10698: # ----------------------------------------------- There is only one possibility
1.37      www      10699: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 10700: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10701: 						    $resid,$thisfn);
1.249     www      10702:                  } elsif (!$donotrecurse) {
1.39      www      10703: # ------------------------------------------ There is more than one possibility
                   10704:                      my $realpossible=0;
1.800     albertel 10705:                      foreach my $id (@possibilities) {
                   10706: 			 my $file=$bighash{'src_'.$id};
1.39      www      10707:                          if (&allowed('bre',$file)) {
1.800     albertel 10708:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      10709:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   10710: 				$realpossible++;
1.626     albertel 10711:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10712: 						    $resid,$thisfn);
1.39      www      10713:                             }
                   10714: 			 }
1.191     harris41 10715:                      }
1.39      www      10716: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      10717:                  } else {
                   10718:                      $syval='';
1.37      www      10719:                  }
                   10720: 	      }
                   10721:               untie(%bighash)
1.481     raeburn  10722:            }
1.31      www      10723:         }
1.62      www      10724:         if ($syval) {
1.620     albertel 10725: 	    return $env{$cache_str}=$syval;
1.62      www      10726:         }
1.31      www      10727:     }
1.949     raeburn  10728:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10729:     return $env{$cache_str}='';
1.31      www      10730: }
                   10731: 
                   10732: # ---------------------------------------------------------- Return random seed
                   10733: 
1.32      www      10734: sub numval {
                   10735:     my $txt=shift;
                   10736:     $txt=~tr/A-J/0-9/;
                   10737:     $txt=~tr/a-j/0-9/;
                   10738:     $txt=~tr/K-T/0-9/;
                   10739:     $txt=~tr/k-t/0-9/;
                   10740:     $txt=~tr/U-Z/0-5/;
                   10741:     $txt=~tr/u-z/0-5/;
                   10742:     $txt=~s/\D//g;
1.564     albertel 10743:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      10744:     return int($txt);
1.368     albertel 10745: }
                   10746: 
1.484     albertel 10747: sub numval2 {
                   10748:     my $txt=shift;
                   10749:     $txt=~tr/A-J/0-9/;
                   10750:     $txt=~tr/a-j/0-9/;
                   10751:     $txt=~tr/K-T/0-9/;
                   10752:     $txt=~tr/k-t/0-9/;
                   10753:     $txt=~tr/U-Z/0-5/;
                   10754:     $txt=~tr/u-z/0-5/;
                   10755:     $txt=~s/\D//g;
                   10756:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10757:     my $total;
                   10758:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 10759:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 10760:     return int($total);
                   10761: }
                   10762: 
1.575     albertel 10763: sub numval3 {
                   10764:     use integer;
                   10765:     my $txt=shift;
                   10766:     $txt=~tr/A-J/0-9/;
                   10767:     $txt=~tr/a-j/0-9/;
                   10768:     $txt=~tr/K-T/0-9/;
                   10769:     $txt=~tr/k-t/0-9/;
                   10770:     $txt=~tr/U-Z/0-5/;
                   10771:     $txt=~tr/u-z/0-5/;
                   10772:     $txt=~s/\D//g;
                   10773:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10774:     my $total;
                   10775:     foreach my $val (@txts) { $total+=$val; }
                   10776:     if ($_64bit) { $total=(($total<<32)>>32); }
                   10777:     return $total;
                   10778: }
                   10779: 
1.675     albertel 10780: sub digest {
                   10781:     my ($data)=@_;
                   10782:     my $digest=&Digest::MD5::md5($data);
                   10783:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   10784:     my ($e,$f);
                   10785:     {
                   10786:         use integer;
                   10787:         $e=($a+$b);
                   10788:         $f=($c+$d);
                   10789:         if ($_64bit) {
                   10790:             $e=(($e<<32)>>32);
                   10791:             $f=(($f<<32)>>32);
                   10792:         }
                   10793:     }
                   10794:     if (wantarray) {
                   10795: 	return ($e,$f);
                   10796:     } else {
                   10797: 	my $g;
                   10798: 	{
                   10799: 	    use integer;
                   10800: 	    $g=($e+$f);
                   10801: 	    if ($_64bit) {
                   10802: 		$g=(($g<<32)>>32);
                   10803: 	    }
                   10804: 	}
                   10805: 	return $g;
                   10806:     }
                   10807: }
                   10808: 
1.368     albertel 10809: sub latest_rnd_algorithm_id {
1.675     albertel 10810:     return '64bit5';
1.366     albertel 10811: }
1.32      www      10812: 
1.503     albertel 10813: sub get_rand_alg {
                   10814:     my ($courseid)=@_;
1.790     albertel 10815:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 10816:     if ($courseid) {
1.620     albertel 10817: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 10818:     }
                   10819:     return &latest_rnd_algorithm_id();
                   10820: }
                   10821: 
1.562     albertel 10822: sub validCODE {
                   10823:     my ($CODE)=@_;
                   10824:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   10825:     return 0;
                   10826: }
                   10827: 
1.491     albertel 10828: sub getCODE {
1.620     albertel 10829:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 10830:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   10831: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   10832: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 10833: 	return $Apache::lonhomework::history{'resource.CODE'};
                   10834:     }
                   10835:     return undef;
                   10836: }
1.1133    foxr     10837: #
                   10838: #  Determines the random seed for a specific context:
                   10839: #
                   10840: # parameters:
                   10841: #   symb      - in course context the symb for the seed.
                   10842: #   course_id - The course id of the form domain_coursenum.
                   10843: #   domain    - Domain for the user.
                   10844: #   course    - Course for the user.
                   10845: #   cenv      - environment of the course.
                   10846: #
                   10847: # NOTE:
                   10848: #   All parameters are picked out of the environment if missing
                   10849: #   or not defined.
                   10850: #   If a symb cannot be determined the current time is used instead.
                   10851: #
                   10852: #  For a given well defined symb, courside, domain, username,
                   10853: #  and course environment, the seed is reproducible.
                   10854: #
1.31      www      10855: sub rndseed {
1.1133    foxr     10856:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 10857:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 10858:     if (!defined($symb)) {
1.366     albertel 10859: 	unless ($symb=$wsymb) { return time; }
                   10860:     }
1.1146    foxr     10861:     if (!defined $courseid) { 
                   10862: 	$courseid=$wcourseid; 
                   10863:     }
                   10864:     if (!defined $domain) { $domain=$wdomain; }
                   10865:     if (!defined $username) { $username=$wusername }
1.1133    foxr     10866: 
                   10867:     my $which;
                   10868:     if (defined($cenv->{'rndseed'})) {
                   10869: 	$which = $cenv->{'rndseed'};
                   10870:     } else {
                   10871: 	$which =&get_rand_alg($courseid);
                   10872:     }
1.491     albertel 10873:     if (defined(&getCODE())) {
1.675     albertel 10874: 	if ($which eq '64bit5') {
                   10875: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   10876: 	} elsif ($which eq '64bit4') {
1.575     albertel 10877: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   10878: 	} else {
                   10879: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   10880: 	}
1.675     albertel 10881:     } elsif ($which eq '64bit5') {
                   10882: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 10883:     } elsif ($which eq '64bit4') {
                   10884: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 10885:     } elsif ($which eq '64bit3') {
                   10886: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 10887:     } elsif ($which eq '64bit2') {
                   10888: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 10889:     } elsif ($which eq '64bit') {
                   10890: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   10891:     }
                   10892:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   10893: }
                   10894: 
                   10895: sub rndseed_32bit {
                   10896:     my ($symb,$courseid,$domain,$username)=@_;
                   10897:     {
                   10898: 	use integer;
                   10899: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   10900: 	my $symbseed=numval($symb) << 22;
                   10901: 	my $namechck=unpack("%32C*",$username) << 17;
                   10902: 	my $nameseed=numval($username) << 12;
                   10903: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   10904: 	my $courseseed=unpack("%32C*",$courseid);
                   10905: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 10906: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10907: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10908: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 10909: 	return $num;
                   10910:     }
                   10911: }
                   10912: 
                   10913: sub rndseed_64bit {
                   10914:     my ($symb,$courseid,$domain,$username)=@_;
                   10915:     {
                   10916: 	use integer;
                   10917: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   10918: 	my $symbseed=numval($symb) << 10;
                   10919: 	my $namechck=unpack("%32S*",$username);
                   10920: 	
                   10921: 	my $nameseed=numval($username) << 21;
                   10922: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   10923: 	my $courseseed=unpack("%32S*",$courseid);
                   10924: 	
                   10925: 	my $num1=$symbchck+$symbseed+$namechck;
                   10926: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10927: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10928: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10929: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 10930: 	return "$num1,$num2";
1.155     albertel 10931:     }
1.366     albertel 10932: }
                   10933: 
1.443     albertel 10934: sub rndseed_64bit2 {
                   10935:     my ($symb,$courseid,$domain,$username)=@_;
                   10936:     {
                   10937: 	use integer;
                   10938: 	# strings need to be an even # of cahracters long, it it is odd the
                   10939:         # last characters gets thrown away
                   10940: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10941: 	my $symbseed=numval($symb) << 10;
                   10942: 	my $namechck=unpack("%32S*",$username.' ');
                   10943: 	
                   10944: 	my $nameseed=numval($username) << 21;
1.501     albertel 10945: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10946: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10947: 	
                   10948: 	my $num1=$symbchck+$symbseed+$namechck;
                   10949: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10950: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10951: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 10952: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 10953: 	return "$num1,$num2";
                   10954:     }
                   10955: }
                   10956: 
                   10957: sub rndseed_64bit3 {
                   10958:     my ($symb,$courseid,$domain,$username)=@_;
                   10959:     {
                   10960: 	use integer;
                   10961: 	# strings need to be an even # of cahracters long, it it is odd the
                   10962:         # last characters gets thrown away
                   10963: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10964: 	my $symbseed=numval2($symb) << 10;
                   10965: 	my $namechck=unpack("%32S*",$username.' ');
                   10966: 	
                   10967: 	my $nameseed=numval2($username) << 21;
1.443     albertel 10968: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10969: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10970: 	
                   10971: 	my $num1=$symbchck+$symbseed+$namechck;
                   10972: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10973: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10974: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 10975: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      10976: 	
1.503     albertel 10977: 	return "$num1:$num2";
1.443     albertel 10978:     }
                   10979: }
                   10980: 
1.575     albertel 10981: sub rndseed_64bit4 {
                   10982:     my ($symb,$courseid,$domain,$username)=@_;
                   10983:     {
                   10984: 	use integer;
                   10985: 	# strings need to be an even # of cahracters long, it it is odd the
                   10986:         # last characters gets thrown away
                   10987: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10988: 	my $symbseed=numval3($symb) << 10;
                   10989: 	my $namechck=unpack("%32S*",$username.' ');
                   10990: 	
                   10991: 	my $nameseed=numval3($username) << 21;
                   10992: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10993: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10994: 	
                   10995: 	my $num1=$symbchck+$symbseed+$namechck;
                   10996: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10997: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10998: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 10999: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11000: 	
1.575     albertel 11001: 	return "$num1:$num2";
                   11002:     }
                   11003: }
                   11004: 
1.675     albertel 11005: sub rndseed_64bit5 {
                   11006:     my ($symb,$courseid,$domain,$username)=@_;
                   11007:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   11008:     return "$num1:$num2";
                   11009: }
                   11010: 
1.366     albertel 11011: sub rndseed_CODE_64bit {
                   11012:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 11013:     {
1.366     albertel 11014: 	use integer;
1.443     albertel 11015: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 11016: 	my $symbseed=numval2($symb);
1.491     albertel 11017: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11018: 	my $CODEseed=numval(&getCODE());
1.443     albertel 11019: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 11020: 	my $num1=$symbseed+$CODEchck;
                   11021: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11022: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11023: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 11024: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11025: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 11026: 	return "$num1:$num2";
1.366     albertel 11027:     }
                   11028: }
                   11029: 
1.575     albertel 11030: sub rndseed_CODE_64bit4 {
                   11031:     my ($symb,$courseid,$domain,$username)=@_;
                   11032:     {
                   11033: 	use integer;
                   11034: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   11035: 	my $symbseed=numval3($symb);
                   11036: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11037: 	my $CODEseed=numval3(&getCODE());
                   11038: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11039: 	my $num1=$symbseed+$CODEchck;
                   11040: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11041: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11042: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 11043: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11044: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   11045: 	return "$num1:$num2";
                   11046:     }
                   11047: }
                   11048: 
1.675     albertel 11049: sub rndseed_CODE_64bit5 {
                   11050:     my ($symb,$courseid,$domain,$username)=@_;
                   11051:     my $code = &getCODE();
                   11052:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   11053:     return "$num1:$num2";
                   11054: }
                   11055: 
1.366     albertel 11056: sub setup_random_from_rndseed {
                   11057:     my ($rndseed)=@_;
1.503     albertel 11058:     if ($rndseed =~/([,:])/) {
                   11059: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 11060: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   11061:     } else {
                   11062: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 11063:     }
1.36      albertel 11064: }
                   11065: 
1.474     albertel 11066: sub latest_receipt_algorithm_id {
1.835     albertel 11067:     return 'receipt3';
1.474     albertel 11068: }
                   11069: 
1.480     www      11070: sub recunique {
                   11071:     my $fucourseid=shift;
                   11072:     my $unique;
1.835     albertel 11073:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   11074: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11075: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      11076:     } else {
                   11077: 	$unique=$perlvar{'lonReceipt'};
                   11078:     }
                   11079:     return unpack("%32C*",$unique);
                   11080: }
                   11081: 
                   11082: sub recprefix {
                   11083:     my $fucourseid=shift;
                   11084:     my $prefix;
1.835     albertel 11085:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   11086: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11087: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      11088:     } else {
                   11089: 	$prefix=$perlvar{'lonHostID'};
                   11090:     }
                   11091:     return unpack("%32C*",$prefix);
                   11092: }
                   11093: 
1.76      www      11094: sub ireceipt {
1.474     albertel 11095:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 11096: 
                   11097:     my $return =&recprefix($fucourseid).'-';
                   11098: 
                   11099:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   11100: 	$env{'request.state'} eq 'construct') {
                   11101: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   11102: 	return $return;
                   11103:     }
                   11104: 
1.76      www      11105:     my $cuname=unpack("%32C*",$funame);
                   11106:     my $cudom=unpack("%32C*",$fudom);
                   11107:     my $cucourseid=unpack("%32C*",$fucourseid);
                   11108:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      11109:     my $cunique=&recunique($fucourseid);
1.474     albertel 11110:     my $cpart=unpack("%32S*",$part);
1.835     albertel 11111:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   11112: 
1.790     albertel 11113: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 11114: 			       
                   11115: 	$return.= ($cunique%$cuname+
                   11116: 		   $cunique%$cudom+
                   11117: 		   $cusymb%$cuname+
                   11118: 		   $cusymb%$cudom+
                   11119: 		   $cucourseid%$cuname+
                   11120: 		   $cucourseid%$cudom+
                   11121: 		   $cpart%$cuname+
                   11122: 		   $cpart%$cudom);
                   11123:     } else {
                   11124: 	$return.= ($cunique%$cuname+
                   11125: 		   $cunique%$cudom+
                   11126: 		   $cusymb%$cuname+
                   11127: 		   $cusymb%$cudom+
                   11128: 		   $cucourseid%$cuname+
                   11129: 		   $cucourseid%$cudom);
                   11130:     }
                   11131:     return $return;
1.76      www      11132: }
                   11133: 
                   11134: sub receipt {
1.474     albertel 11135:     my ($part)=@_;
1.790     albertel 11136:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 11137:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      11138: }
1.260     ng       11139: 
1.790     albertel 11140: sub whichuser {
                   11141:     my ($passedsymb)=@_;
                   11142:     my ($symb,$courseid,$domain,$name,$publicuser);
                   11143:     if (defined($env{'form.grade_symb'})) {
                   11144: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   11145: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   11146: 	if (!$allowed &&
                   11147: 	    exists($env{'request.course.sec'}) &&
                   11148: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   11149: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   11150: 			      '/'.$env{'request.course.sec'});
                   11151: 	}
                   11152: 	if ($allowed) {
                   11153: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   11154: 	    $courseid=$tmp_courseid;
                   11155: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   11156: 	    ($name)=&get_env_multiple('form.grade_username');
                   11157: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   11158: 	}
                   11159:     }
                   11160:     if (!$passedsymb) {
                   11161: 	$symb=&symbread();
                   11162:     } else {
                   11163: 	$symb=$passedsymb;
                   11164:     }
                   11165:     $courseid=$env{'request.course.id'};
                   11166:     $domain=$env{'user.domain'};
                   11167:     $name=$env{'user.name'};
                   11168:     if ($name eq 'public' && $domain eq 'public') {
                   11169: 	if (!defined($env{'form.username'})) {
                   11170: 	    $env{'form.username'}.=time.rand(10000000);
                   11171: 	}
                   11172: 	$name.=$env{'form.username'};
                   11173:     }
                   11174:     return ($symb,$courseid,$domain,$name,$publicuser);
                   11175: 
                   11176: }
                   11177: 
1.36      albertel 11178: # ------------------------------------------------------------ Serves up a file
1.472     albertel 11179: # returns either the contents of the file or 
                   11180: # -1 if the file doesn't exist
1.481     raeburn  11181: #
                   11182: # if the target is a file that was uploaded via DOCS, 
                   11183: # a check will be made to see if a current copy exists on the local server,
                   11184: # if it does this will be served, otherwise a copy will be retrieved from
                   11185: # the home server for the course and stored in /home/httpd/html/userfiles on
                   11186: # the local server.   
1.472     albertel 11187: 
1.36      albertel 11188: sub getfile {
1.538     albertel 11189:     my ($file) = @_;
1.609     banghart 11190:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 11191:     &repcopy($file);
                   11192:     return &readfile($file);
                   11193: }
                   11194: 
                   11195: sub repcopy_userfile {
                   11196:     my ($file)=@_;
1.1142    raeburn  11197:     my $londocroot = $perlvar{'lonDocRoot'};
                   11198:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  11199:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 11200:     my ($cdom,$cnum,$filename) = 
1.811     albertel 11201: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 11202:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   11203:     if (-e "$file") {
1.828     www      11204: # we already have a local copy, check it out
1.538     albertel 11205: 	my @fileinfo = stat($file);
1.828     www      11206: 	my $rtncode;
                   11207: 	my $info;
1.538     albertel 11208: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 11209: 	if ($lwpresp ne 'ok') {
1.828     www      11210: # there is no such file anymore, even though we had a local copy
1.482     albertel 11211: 	    if ($rtncode eq '404') {
1.538     albertel 11212: 		unlink($file);
1.482     albertel 11213: 	    }
                   11214: 	    return -1;
                   11215: 	}
                   11216: 	if ($info < $fileinfo[9]) {
1.828     www      11217: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  11218: 	    return 'ok';
1.828     www      11219: 	} else {
                   11220: # the file is outdated, get rid of it
                   11221: 	    unlink($file);
1.482     albertel 11222: 	}
1.828     www      11223:     }
                   11224: # one way or the other, at this point, we don't have the file
                   11225: # construct the correct path for the file
                   11226:     my @parts = ($cdom,$cnum); 
                   11227:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   11228: 	push @parts, split(/\//,$1);
                   11229:     }
                   11230:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   11231:     foreach my $part (@parts) {
                   11232: 	$path .= '/'.$part;
                   11233: 	if (!-e $path) {
                   11234: 	    mkdir($path,0770);
1.482     albertel 11235: 	}
                   11236:     }
1.828     www      11237: # now the path exists for sure
                   11238: # get a user agent
                   11239:     my $ua=new LWP::UserAgent;
                   11240:     my $transferfile=$file.'.in.transfer';
                   11241: # FIXME: this should flock
                   11242:     if (-e $transferfile) { return 'ok'; }
                   11243:     my $request;
                   11244:     $uri=~s/^\///;
1.980     raeburn  11245:     my $homeserver = &homeserver($cnum,$cdom);
                   11246:     my $protocol = $protocol{$homeserver};
                   11247:     $protocol = 'http' if ($protocol ne 'https');
                   11248:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      11249:     my $response=$ua->request($request,$transferfile);
                   11250: # did it work?
                   11251:     if ($response->is_error()) {
                   11252: 	unlink($transferfile);
                   11253: 	&logthis("Userfile repcopy failed for $uri");
                   11254: 	return -1;
                   11255:     }
                   11256: # worked, rename the transfer file
                   11257:     rename($transferfile,$file);
1.607     raeburn  11258:     return 'ok';
1.481     raeburn  11259: }
                   11260: 
1.517     albertel 11261: sub tokenwrapper {
                   11262:     my $uri=shift;
1.980     raeburn  11263:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 11264:     $uri=~s|^/||;
1.620     albertel 11265:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 11266:     my $token=$1;
1.552     albertel 11267:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   11268:     if ($udom && $uname && $file) {
                   11269: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  11270:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  11271:         my $homeserver = &homeserver($uname,$udom);
                   11272:         my $protocol = $protocol{$homeserver};
                   11273:         $protocol = 'http' if ($protocol ne 'https');
                   11274:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 11275:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   11276:                                '&tokenissued='.$perlvar{'lonHostID'};
                   11277:     } else {
                   11278:         return '/adm/notfound.html';
                   11279:     }
                   11280: }
                   11281: 
1.828     www      11282: # call with reqtype HEAD: get last modification time
                   11283: # call with reqtype GET: get the file contents
                   11284: # Do not call this with reqtype GET for large files! It loads everything into memory
                   11285: #
1.481     raeburn  11286: sub getuploaded {
                   11287:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   11288:     $uri=~s/^\///;
1.980     raeburn  11289:     my $homeserver = &homeserver($cnum,$cdom);
                   11290:     my $protocol = $protocol{$homeserver};
                   11291:     $protocol = 'http' if ($protocol ne 'https');
                   11292:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  11293:     my $ua=new LWP::UserAgent;
                   11294:     my $request=new HTTP::Request($reqtype,$uri);
                   11295:     my $response=$ua->request($request);
                   11296:     $$rtncode = $response->code;
1.482     albertel 11297:     if (! $response->is_success()) {
                   11298: 	return 'failed';
                   11299:     }      
                   11300:     if ($reqtype eq 'HEAD') {
1.486     www      11301: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 11302:     } elsif ($reqtype eq 'GET') {
                   11303: 	$$info = $response->content;
1.472     albertel 11304:     }
1.482     albertel 11305:     return 'ok';
1.36      albertel 11306: }
                   11307: 
1.481     raeburn  11308: sub readfile {
                   11309:     my $file = shift;
                   11310:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   11311:     my $fh;
                   11312:     open($fh,"<$file");
                   11313:     my $a='';
1.800     albertel 11314:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  11315:     return $a;
                   11316: }
                   11317: 
1.36      albertel 11318: sub filelocation {
1.590     banghart 11319:     my ($dir,$file) = @_;
                   11320:     my $location;
                   11321:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 11322: 
                   11323:     if ($file =~ m-^/adm/-) {
                   11324: 	$file=~s-^/adm/wrapper/-/-;
                   11325: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   11326:     }
1.882     albertel 11327: 
1.1139    www      11328:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  11329:         $location = $file;
1.609     banghart 11330:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 11331:         my ($udom,$uname,$filename)=
1.811     albertel 11332:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 11333:         my $home=&homeserver($uname,$udom);
                   11334:         my $is_me=0;
                   11335:         my @ids=&current_machine_ids();
                   11336:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   11337:         if ($is_me) {
1.1117    foxr     11338:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 11339:         } else {
                   11340:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   11341:   	      $udom.'/'.$uname.'/'.$filename;
                   11342:         }
1.882     albertel 11343:     } elsif ($file =~ m-^/adm/-) {
                   11344: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 11345:     } else {
                   11346:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      11347:         $file=~s:^/(res|priv)/:/:;
                   11348:         my $space=$1;
1.590     banghart 11349:         if ( !( $file =~ m:^/:) ) {
                   11350:             $location = $dir. '/'.$file;
                   11351:         } else {
1.1142    raeburn  11352:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 11353:         }
1.59      albertel 11354:     }
1.590     banghart 11355:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 11356:     while ($location=~m{/\.\./}) {
                   11357: 	if ($location =~ m{/[^/]+/\.\./}) {
                   11358: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   11359: 	} else {
                   11360: 	    $location=~ s{/\.\./}{/}g;
                   11361: 	}
                   11362:     } #remove dir/..
1.590     banghart 11363:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   11364:     return $location;
1.46      www      11365: }
1.36      albertel 11366: 
1.46      www      11367: sub hreflocation {
                   11368:     my ($dir,$file)=@_;
1.980     raeburn  11369:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 11370: 	$file=filelocation($dir,$file);
1.700     albertel 11371:     } elsif ($file=~m-^/adm/-) {
                   11372: 	$file=~s-^/adm/wrapper/-/-;
                   11373: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 11374:     }
                   11375:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   11376: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   11377:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  11378: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   11379: 	        {/uploaded/$1/$2/}x;
1.46      www      11380:     }
1.913     albertel 11381:     if ($file=~ m{^/userfiles/}) {
                   11382: 	$file =~ s{^/userfiles/}{/uploaded/};
                   11383:     }
1.462     albertel 11384:     return $file;
1.465     albertel 11385: }
                   11386: 
1.1139    www      11387: 
                   11388: 
                   11389: 
                   11390: 
1.465     albertel 11391: sub current_machine_domains {
1.853     albertel 11392:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   11393: }
                   11394: 
                   11395: sub machine_domains {
                   11396:     my ($hostname) = @_;
1.465     albertel 11397:     my @domains;
1.838     albertel 11398:     my %hostname = &all_hostnames();
1.465     albertel 11399:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  11400: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 11401: 	if ($hostname eq $name) {
1.844     albertel 11402: 	    push(@domains,&host_domain($id));
1.465     albertel 11403: 	}
                   11404:     }
                   11405:     return @domains;
                   11406: }
                   11407: 
                   11408: sub current_machine_ids {
1.853     albertel 11409:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   11410: }
                   11411: 
                   11412: sub machine_ids {
                   11413:     my ($hostname) = @_;
                   11414:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 11415:     my @ids;
1.888     albertel 11416:     my %name_to_host = &all_names();
1.889     albertel 11417:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   11418: 	return @{ $name_to_host{$hostname} };
                   11419:     }
                   11420:     return;
1.31      www      11421: }
                   11422: 
1.824     raeburn  11423: sub additional_machine_domains {
                   11424:     my @domains;
                   11425:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   11426:     while( my $line = <$fh>) {
                   11427:         $line =~ s/\s//g;
                   11428:         push(@domains,$line);
                   11429:     }
                   11430:     return @domains;
                   11431: }
                   11432: 
                   11433: sub default_login_domain {
                   11434:     my $domain = $perlvar{'lonDefDomain'};
                   11435:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   11436:     foreach my $posdom (&current_machine_domains(),
                   11437:                         &additional_machine_domains()) {
                   11438:         if (lc($posdom) eq lc($testdomain)) {
                   11439:             $domain=$posdom;
                   11440:             last;
                   11441:         }
                   11442:     }
                   11443:     return $domain;
                   11444: }
                   11445: 
1.31      www      11446: # ------------------------------------------------------------- Declutters URLs
                   11447: 
                   11448: sub declutter {
                   11449:     my $thisfn=shift;
1.569     albertel 11450:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 11451:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      11452:     $thisfn=~s/^\///;
1.697     albertel 11453:     $thisfn=~s|^adm/wrapper/||;
                   11454:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      11455:     $thisfn=~s/^res\///;
1.1172    bisitz   11456:     $thisfn=~s/^priv\///;
1.1032    raeburn  11457:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   11458:         $thisfn=~s/\?.+$//;
                   11459:     }
1.268     www      11460:     return $thisfn;
                   11461: }
                   11462: 
                   11463: # ------------------------------------------------------------- Clutter up URLs
                   11464: 
                   11465: sub clutter {
                   11466:     my $thisfn='/'.&declutter(shift);
1.887     albertel 11467:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 11468: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      11469:        $thisfn='/res'.$thisfn; 
                   11470:     }
1.1031    raeburn  11471:     if ($thisfn !~m|^/adm|) {
                   11472: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 11473: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 11474: 	} else {
                   11475: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   11476: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 11477: 	    if ($embstyle eq 'ssi'
                   11478: 		|| ($embstyle eq 'hdn')
                   11479: 		|| ($embstyle eq 'rat')
                   11480: 		|| ($embstyle eq 'prv')
                   11481: 		|| ($embstyle eq 'ign')) {
                   11482: 		#do nothing with these
                   11483: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 11484: 		|| ($embstyle eq 'emb')
                   11485: 		|| ($embstyle eq 'wrp')) {
                   11486: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 11487: 	    } elsif ($embstyle eq 'unk'
                   11488: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 11489: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 11490: 	    } else {
1.718     www      11491: #		&logthis("Got a blank emb style");
1.695     albertel 11492: 	    }
1.694     albertel 11493: 	}
                   11494:     }
1.31      www      11495:     return $thisfn;
1.12      www      11496: }
                   11497: 
1.787     albertel 11498: sub clutter_with_no_wrapper {
                   11499:     my $uri = &clutter(shift);
                   11500:     if ($uri =~ m-^/adm/-) {
                   11501: 	$uri =~ s-^/adm/wrapper/-/-;
                   11502: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   11503:     }
                   11504:     return $uri;
                   11505: }
                   11506: 
1.557     albertel 11507: sub freeze_escape {
                   11508:     my ($value)=@_;
                   11509:     if (ref($value)) {
                   11510: 	$value=&nfreeze($value);
                   11511: 	return '__FROZEN__'.&escape($value);
                   11512:     }
                   11513:     return &escape($value);
                   11514: }
                   11515: 
1.11      www      11516: 
1.557     albertel 11517: sub thaw_unescape {
                   11518:     my ($value)=@_;
                   11519:     if ($value =~ /^__FROZEN__/) {
                   11520: 	substr($value,0,10,undef);
                   11521: 	$value=&unescape($value);
                   11522: 	return &thaw($value);
                   11523:     }
                   11524:     return &unescape($value);
                   11525: }
                   11526: 
1.436     albertel 11527: sub correct_line_ends {
                   11528:     my ($result)=@_;
                   11529:     $$result =~s/\r\n/\n/mg;
                   11530:     $$result =~s/\r/\n/mg;
1.415     albertel 11531: }
1.1       albertel 11532: # ================================================================ Main Program
                   11533: 
1.184     www      11534: sub goodbye {
1.204     albertel 11535:    &logthis("Starting Shut down");
1.443     albertel 11536: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 11537:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 11538: #converted
1.599     albertel 11539: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 11540:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   11541: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   11542: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 11543: #1.1 only
1.870     albertel 11544: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   11545: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   11546: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   11547: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   11548:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 11549:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   11550:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      11551:    &flushcourselogs();
                   11552:    &logthis("Shutting down");
                   11553: }
                   11554: 
1.852     albertel 11555: sub get_dns {
1.1172.2.17  raeburn  11556:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 11557:     if (!$ignore_cache) {
                   11558: 	my ($content,$cached)=
                   11559: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   11560: 	if ($cached) {
1.1172.2.17  raeburn  11561: 	    &$func($content,$hashref);
1.869     albertel 11562: 	    return;
                   11563: 	}
                   11564:     }
                   11565: 
                   11566:     my %alldns;
1.852     albertel 11567:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11568:     foreach my $dns (<$config>) {
                   11569: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  11570:         my $line = $1;
                   11571:         my ($host,$protocol) = split(/:/,$line);
                   11572:         if ($protocol ne 'https') {
                   11573:             $protocol = 'http';
                   11574:         }
                   11575: 	$alldns{$host} = $protocol;
1.869     albertel 11576:     }
                   11577:     while (%alldns) {
                   11578: 	my ($dns) = keys(%alldns);
1.852     albertel 11579: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  11580:         $ua->timeout(30);
1.979     raeburn  11581: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 11582: 	my $response=$ua->request($request);
1.979     raeburn  11583:         delete($alldns{$dns});
1.852     albertel 11584: 	next if ($response->is_error());
                   11585: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  11586:         unless ($nocache) {
                   11587: 	    &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
                   11588:         }
                   11589: 	&$func(\@content,$hashref);
1.869     albertel 11590: 	return;
1.852     albertel 11591:     }
                   11592:     close($config);
1.871     albertel 11593:     my $which = (split('/',$url))[3];
                   11594:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   11595:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 11596:     my @content = <$config>;
1.1172.2.17  raeburn  11597:     &$func(\@content,$hashref);
                   11598:     return;
                   11599: }
                   11600: 
                   11601: # ------------------------------------------------------Get DNS checksums file
                   11602: sub parse_dns_checksums_tab {
                   11603:     my ($lines,$hashref) = @_;
                   11604:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
                   11605:     my $loncaparev = &get_server_loncaparev($machine_dom);
                   11606:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   11607:     my (%chksum,%revnum);
                   11608:     if (ref($lines) eq 'ARRAY') {
                   11609:         chomp(@{$lines});
                   11610:         my $versions = shift(@{$lines});
                   11611:         my %supported;
                   11612:         if ($versions =~ /^VERSIONS\:([\w\.\,]+)$/) {
                   11613:             my $releaseslist = $1;
                   11614:             if ($releaseslist =~ /,/) {
                   11615:                 map { $supported{$_} = 1; } split(/,/,$releaseslist);
                   11616:             } elsif ($releaseslist) {
                   11617:                 $supported{$releaseslist} = 1;
                   11618:             }
                   11619:         }
                   11620:         if ($supported{$release}) {
                   11621:             my $matchthis = 0;
                   11622:             foreach my $line (@{$lines}) {
                   11623:                 if ($line =~ /^(\d[\w\.]+)$/) {
                   11624:                     if ($matchthis) {
                   11625:                         last;
                   11626:                     } elsif ($1 eq $release) {
                   11627:                         $matchthis = 1;
                   11628:                     }
                   11629:                 } elsif ($matchthis) {
                   11630:                     my ($file,$version,$shasum) = split(/,/,$line);
                   11631:                     $chksum{$file} = $shasum;
                   11632:                     $revnum{$file} = $version;
                   11633:                 }
                   11634:             }
                   11635:             if (ref($hashref) eq 'HASH') {
                   11636:                 %{$hashref} = (
                   11637:                                 sums     => \%chksum,
                   11638:                                 versions => \%revnum,
                   11639:                               );
                   11640:             }
                   11641:         }
                   11642:     }
1.869     albertel 11643:     return;
1.852     albertel 11644: }
1.1172.2.17  raeburn  11645: 
                   11646: sub fetch_dns_checksums {
                   11647:     my %checksums;
                   11648:     &get_dns('/adm/dns/checksums',\&parse_dns_checksums_tab,1,1,
                   11649:              \%checksums);
                   11650:     return \%checksums;
                   11651: }
                   11652: 
1.327     albertel 11653: # ------------------------------------------------------------ Read domain file
                   11654: {
1.852     albertel 11655:     my $loaded;
1.846     albertel 11656:     my %domain;
                   11657: 
1.852     albertel 11658:     sub parse_domain_tab {
                   11659: 	my ($lines) = @_;
                   11660: 	foreach my $line (@$lines) {
                   11661: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      11662: 
1.846     albertel 11663: 	    chomp($line);
1.852     albertel 11664: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 11665: 	    my %this_domain;
                   11666: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   11667: 			       'lang_def', 'city', 'longi', 'lati',
                   11668: 			       'primary') {
                   11669: 		$this_domain{$field} = shift(@elements);
                   11670: 	    }
                   11671: 	    $domain{$name} = \%this_domain;
1.852     albertel 11672: 	}
                   11673:     }
1.864     albertel 11674: 
                   11675:     sub reset_domain_info {
                   11676: 	undef($loaded);
                   11677: 	undef(%domain);
                   11678:     }
                   11679: 
1.852     albertel 11680:     sub load_domain_tab {
1.869     albertel 11681: 	my ($ignore_cache) = @_;
                   11682: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 11683: 	my $fh;
                   11684: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   11685: 	    my @lines = <$fh>;
                   11686: 	    &parse_domain_tab(\@lines);
1.448     albertel 11687: 	}
1.852     albertel 11688: 	close($fh);
                   11689: 	$loaded = 1;
1.327     albertel 11690:     }
1.846     albertel 11691: 
                   11692:     sub domain {
1.852     albertel 11693: 	&load_domain_tab() if (!$loaded);
                   11694: 
1.846     albertel 11695: 	my ($name,$what) = @_;
                   11696: 	return if ( !exists($domain{$name}) );
                   11697: 
                   11698: 	if (!$what) {
                   11699: 	    return $domain{$name}{'description'};
                   11700: 	}
                   11701: 	return $domain{$name}{$what};
                   11702:     }
1.974     raeburn  11703: 
                   11704:     sub domain_info {
                   11705:         &load_domain_tab() if (!$loaded);
                   11706:         return %domain;
                   11707:     }
                   11708: 
1.327     albertel 11709: }
                   11710: 
                   11711: 
1.1       albertel 11712: # ------------------------------------------------------------- Read hosts file
                   11713: {
1.838     albertel 11714:     my %hostname;
1.844     albertel 11715:     my %hostdom;
1.845     albertel 11716:     my %libserv;
1.852     albertel 11717:     my $loaded;
1.888     albertel 11718:     my %name_to_host;
1.1074    raeburn  11719:     my %internetdom;
1.1107    raeburn  11720:     my %LC_dns_serv;
1.852     albertel 11721: 
                   11722:     sub parse_hosts_tab {
                   11723: 	my ($file) = @_;
                   11724: 	foreach my $configline (@$file) {
                   11725: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  11726:             chomp($configline);
                   11727: 	    if ($configline =~ /^\^/) {
                   11728:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   11729:                     $LC_dns_serv{$1} = 1;
                   11730:                 }
                   11731:                 next;
                   11732:             }
1.1074    raeburn  11733: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 11734: 	    $name=~s/\s//g;
                   11735: 	    if ($id && $domain && $role && $name) {
                   11736: 		$hostname{$id}=$name;
1.888     albertel 11737: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 11738: 		$hostdom{$id}=$domain;
                   11739: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  11740:                 if (defined($protocol)) {
                   11741:                     if ($protocol eq 'https') {
                   11742:                         $protocol{$id} = $protocol;
                   11743:                     } else {
                   11744:                         $protocol{$id} = 'http'; 
                   11745:                     }
1.968     raeburn  11746:                 } else {
1.969     raeburn  11747:                     $protocol{$id} = 'http';
1.968     raeburn  11748:                 }
1.1074    raeburn  11749:                 if (defined($intdom)) {
                   11750:                     $internetdom{$id} = $intdom;
                   11751:                 }
1.852     albertel 11752: 	    }
                   11753: 	}
                   11754:     }
1.864     albertel 11755:     
                   11756:     sub reset_hosts_info {
1.897     albertel 11757: 	&purge_remembered();
1.864     albertel 11758: 	&reset_domain_info();
                   11759: 	&reset_hosts_ip_info();
1.892     albertel 11760: 	undef(%name_to_host);
1.864     albertel 11761: 	undef(%hostname);
                   11762: 	undef(%hostdom);
                   11763: 	undef(%libserv);
                   11764: 	undef($loaded);
                   11765:     }
1.1       albertel 11766: 
1.852     albertel 11767:     sub load_hosts_tab {
1.869     albertel 11768: 	my ($ignore_cache) = @_;
                   11769: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 11770: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11771: 	my @config = <$config>;
                   11772: 	&parse_hosts_tab(\@config);
                   11773: 	close($config);
                   11774: 	$loaded=1;
1.1       albertel 11775:     }
1.852     albertel 11776: 
1.838     albertel 11777:     sub hostname {
1.852     albertel 11778: 	&load_hosts_tab() if (!$loaded);
                   11779: 
1.838     albertel 11780: 	my ($lonid) = @_;
                   11781: 	return $hostname{$lonid};
                   11782:     }
1.845     albertel 11783: 
1.838     albertel 11784:     sub all_hostnames {
1.852     albertel 11785: 	&load_hosts_tab() if (!$loaded);
                   11786: 
1.838     albertel 11787: 	return %hostname;
                   11788:     }
1.845     albertel 11789: 
1.888     albertel 11790:     sub all_names {
                   11791: 	&load_hosts_tab() if (!$loaded);
                   11792: 
                   11793: 	return %name_to_host;
                   11794:     }
                   11795: 
1.974     raeburn  11796:     sub all_host_domain {
                   11797:         &load_hosts_tab() if (!$loaded);
                   11798:         return %hostdom;
                   11799:     }
                   11800: 
1.845     albertel 11801:     sub is_library {
1.852     albertel 11802: 	&load_hosts_tab() if (!$loaded);
                   11803: 
1.845     albertel 11804: 	return exists($libserv{$_[0]});
                   11805:     }
                   11806: 
                   11807:     sub all_library {
1.852     albertel 11808: 	&load_hosts_tab() if (!$loaded);
                   11809: 
1.845     albertel 11810: 	return %libserv;
                   11811:     }
                   11812: 
1.1062    droeschl 11813:     sub unique_library {
                   11814: 	#2x reverse removes all hostnames that appear more than once
                   11815:         my %unique = reverse &all_library();
                   11816:         return reverse %unique;
                   11817:     }
                   11818: 
1.841     albertel 11819:     sub get_servers {
1.852     albertel 11820: 	&load_hosts_tab() if (!$loaded);
                   11821: 
1.841     albertel 11822: 	my ($domain,$type) = @_;
                   11823: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   11824: 	                                          : %hostname;
                   11825: 	my %result;
1.842     albertel 11826: 	if (ref($domain) eq 'ARRAY') {
                   11827: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 11828: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 11829: 		    $result{$host} = $hostname;
                   11830: 		}
                   11831: 	    }
                   11832: 	} else {
                   11833: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   11834: 		if ($hostdom{$host} eq $domain) {
                   11835: 		    $result{$host} = $hostname;
                   11836: 		}
1.841     albertel 11837: 	    }
                   11838: 	}
                   11839: 	return %result;
                   11840:     }
1.845     albertel 11841: 
1.1062    droeschl 11842:     sub get_unique_servers {
                   11843:         my %unique = reverse &get_servers(@_);
                   11844: 	return reverse %unique;
                   11845:     }
                   11846: 
1.844     albertel 11847:     sub host_domain {
1.852     albertel 11848: 	&load_hosts_tab() if (!$loaded);
                   11849: 
1.844     albertel 11850: 	my ($lonid) = @_;
                   11851: 	return $hostdom{$lonid};
                   11852:     }
                   11853: 
1.841     albertel 11854:     sub all_domains {
1.852     albertel 11855: 	&load_hosts_tab() if (!$loaded);
                   11856: 
1.841     albertel 11857: 	my %seen;
                   11858: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   11859: 	return @uniq;
                   11860:     }
1.1074    raeburn  11861: 
                   11862:     sub internet_dom {
                   11863:         &load_hosts_tab() if (!$loaded);
                   11864: 
                   11865:         my ($lonid) = @_;
                   11866:         return $internetdom{$lonid};
                   11867:     }
1.1107    raeburn  11868: 
                   11869:     sub is_LC_dns {
                   11870:         &load_hosts_tab() if (!$loaded);
                   11871: 
                   11872:         my ($hostname) = @_;
                   11873:         return exists($LC_dns_serv{$hostname});
                   11874:     }
                   11875: 
1.1       albertel 11876: }
                   11877: 
1.847     albertel 11878: { 
                   11879:     my %iphost;
1.856     albertel 11880:     my %name_to_ip;
                   11881:     my %lonid_to_ip;
1.869     albertel 11882: 
1.847     albertel 11883:     sub get_hosts_from_ip {
                   11884: 	my ($ip) = @_;
                   11885: 	my %iphosts = &get_iphost();
                   11886: 	if (ref($iphosts{$ip})) {
                   11887: 	    return @{$iphosts{$ip}};
                   11888: 	}
                   11889: 	return;
1.839     albertel 11890:     }
1.864     albertel 11891:     
                   11892:     sub reset_hosts_ip_info {
                   11893: 	undef(%iphost);
                   11894: 	undef(%name_to_ip);
                   11895: 	undef(%lonid_to_ip);
                   11896:     }
1.856     albertel 11897: 
                   11898:     sub get_host_ip {
                   11899: 	my ($lonid) = @_;
                   11900: 	if (exists($lonid_to_ip{$lonid})) {
                   11901: 	    return $lonid_to_ip{$lonid};
                   11902: 	}
                   11903: 	my $name=&hostname($lonid);
                   11904:    	my $ip = gethostbyname($name);
                   11905: 	return if (!$ip || length($ip) ne 4);
                   11906: 	$ip=inet_ntoa($ip);
                   11907: 	$name_to_ip{$name}   = $ip;
                   11908: 	$lonid_to_ip{$lonid} = $ip;
                   11909: 	return $ip;
                   11910:     }
1.847     albertel 11911:     
                   11912:     sub get_iphost {
1.869     albertel 11913: 	my ($ignore_cache) = @_;
1.894     albertel 11914: 
1.869     albertel 11915: 	if (!$ignore_cache) {
                   11916: 	    if (%iphost) {
                   11917: 		return %iphost;
                   11918: 	    }
                   11919: 	    my ($ip_info,$cached)=
                   11920: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   11921: 	    if ($cached) {
                   11922: 		%iphost      = %{$ip_info->[0]};
                   11923: 		%name_to_ip  = %{$ip_info->[1]};
                   11924: 		%lonid_to_ip = %{$ip_info->[2]};
                   11925: 		return %iphost;
                   11926: 	    }
                   11927: 	}
1.894     albertel 11928: 
                   11929: 	# get yesterday's info for fallback
                   11930: 	my %old_name_to_ip;
                   11931: 	my ($ip_info,$cached)=
                   11932: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   11933: 	if ($cached) {
                   11934: 	    %old_name_to_ip = %{$ip_info->[1]};
                   11935: 	}
                   11936: 
1.888     albertel 11937: 	my %name_to_host = &all_names();
                   11938: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 11939: 	    my $ip;
                   11940: 	    if (!exists($name_to_ip{$name})) {
                   11941: 		$ip = gethostbyname($name);
                   11942: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 11943: 		    if (defined($old_name_to_ip{$name})) {
                   11944: 			$ip = $old_name_to_ip{$name};
                   11945: 			&logthis("Can't find $name defaulting to old $ip");
                   11946: 		    } else {
                   11947: 			&logthis("Name $name no IP found");
                   11948: 			next;
                   11949: 		    }
                   11950: 		} else {
                   11951: 		    $ip=inet_ntoa($ip);
1.847     albertel 11952: 		}
                   11953: 		$name_to_ip{$name} = $ip;
                   11954: 	    } else {
                   11955: 		$ip = $name_to_ip{$name};
1.653     albertel 11956: 	    }
1.888     albertel 11957: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   11958: 		$lonid_to_ip{$id} = $ip;
                   11959: 	    }
                   11960: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 11961: 	}
1.869     albertel 11962: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   11963: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 11964: 				      48*60*60);
1.869     albertel 11965: 
1.847     albertel 11966: 	return %iphost;
1.598     albertel 11967:     }
                   11968: 
1.992     raeburn  11969:     #
                   11970:     #  Given a DNS returns the loncapa host name for that DNS 
                   11971:     # 
                   11972:     sub host_from_dns {
                   11973:         my ($dns) = @_;
                   11974:         my @hosts;
                   11975:         my $ip;
                   11976: 
1.993     raeburn  11977:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  11978:             $ip = $name_to_ip{$dns};
                   11979:         }
                   11980:         if (!$ip) {
                   11981:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   11982:             if (length($ip) == 4) { 
                   11983: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   11984:             }
                   11985:         }
                   11986:         if ($ip) {
                   11987: 	    @hosts = get_hosts_from_ip($ip);
                   11988: 	    return $hosts[0];
                   11989:         }
                   11990:         return undef;
1.986     foxr     11991:     }
1.992     raeburn  11992: 
1.1074    raeburn  11993:     sub get_internet_names {
                   11994:         my ($lonid) = @_;
                   11995:         return if ($lonid eq '');
                   11996:         my ($idnref,$cached)=
                   11997:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   11998:         if ($cached) {
                   11999:             return $idnref;
                   12000:         }
                   12001:         my $ip = &get_host_ip($lonid);
                   12002:         my @hosts = &get_hosts_from_ip($ip);
                   12003:         my %iphost = &get_iphost();
                   12004:         my (@idns,%seen);
                   12005:         foreach my $id (@hosts) {
                   12006:             my $dom = &host_domain($id);
                   12007:             my $prim_id = &domain($dom,'primary');
                   12008:             my $prim_ip = &get_host_ip($prim_id);
                   12009:             next if ($seen{$prim_ip});
                   12010:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   12011:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   12012:                     my $intdom = &internet_dom($id);
                   12013:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   12014:                         push(@idns,$intdom);
                   12015:                     }
                   12016:                 }
                   12017:             }
                   12018:             $seen{$prim_ip} = 1;
                   12019:         }
                   12020:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   12021:     }
                   12022: 
1.986     foxr     12023: }
                   12024: 
1.1079    raeburn  12025: sub all_loncaparevs {
                   12026:     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);
                   12027: }
                   12028: 
1.862     albertel 12029: BEGIN {
                   12030: 
                   12031: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   12032:     unless ($readit) {
                   12033: {
                   12034:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   12035:     %perlvar = (%perlvar,%{$configvars});
                   12036: }
                   12037: 
                   12038: 
1.1       albertel 12039: # ------------------------------------------------------ Read spare server file
                   12040: {
1.448     albertel 12041:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 12042: 
                   12043:     while (my $configline=<$config>) {
                   12044:        chomp($configline);
1.284     matthew  12045:        if ($configline) {
1.784     albertel 12046: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 12047: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 12048: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 12049:        }
                   12050:     }
1.448     albertel 12051:     close($config);
1.1       albertel 12052: }
1.11      www      12053: # ------------------------------------------------------------ Read permissions
                   12054: {
1.448     albertel 12055:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      12056: 
                   12057:     while (my $configline=<$config>) {
1.448     albertel 12058: 	chomp($configline);
                   12059: 	if ($configline) {
                   12060: 	    my ($role,$perm)=split(/ /,$configline);
                   12061: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   12062: 	}
1.11      www      12063:     }
1.448     albertel 12064:     close($config);
1.11      www      12065: }
                   12066: 
                   12067: # -------------------------------------------- Read plain texts for permissions
                   12068: {
1.448     albertel 12069:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      12070: 
                   12071:     while (my $configline=<$config>) {
1.448     albertel 12072: 	chomp($configline);
                   12073: 	if ($configline) {
1.742     raeburn  12074: 	    my ($short,@plain)=split(/:/,$configline);
                   12075:             %{$prp{$short}} = ();
                   12076: 	    if (@plain > 0) {
                   12077:                 $prp{$short}{'std'} = $plain[0];
                   12078:                 for (my $i=1; $i<@plain; $i++) {
                   12079:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   12080:                 }
                   12081:             }
1.448     albertel 12082: 	}
1.135     www      12083:     }
1.448     albertel 12084:     close($config);
1.135     www      12085: }
                   12086: 
                   12087: # ---------------------------------------------------------- Read package table
                   12088: {
1.448     albertel 12089:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      12090: 
                   12091:     while (my $configline=<$config>) {
1.483     albertel 12092: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 12093: 	chomp($configline);
                   12094: 	my ($short,$plain)=split(/:/,$configline);
                   12095: 	my ($pack,$name)=split(/\&/,$short);
                   12096: 	if ($plain ne '') {
                   12097: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   12098: 	    $packagetab{$short}=$plain; 
                   12099: 	}
1.11      www      12100:     }
1.448     albertel 12101:     close($config);
1.329     matthew  12102: }
                   12103: 
1.1073    raeburn  12104: # ---------------------------------------------------------- Read loncaparev table
                   12105: {
                   12106:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   12107:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   12108:             while (my $configline=<$config>) {
                   12109:                 chomp($configline);
                   12110:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   12111:                 $loncaparevs{$hostid}=$loncaparev;
                   12112:             }
                   12113:             close($config);
                   12114:         }
                   12115:     }
                   12116: }
                   12117: 
1.1074    raeburn  12118: # ---------------------------------------------------------- Read serverhostID table
                   12119: {
                   12120:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   12121:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   12122:             while (my $configline=<$config>) {
                   12123:                 chomp($configline);
                   12124:                 my ($name,$id)=split(/:/,$configline);
                   12125:                 $serverhomeIDs{$name}=$id;
                   12126:             }
                   12127:             close($config);
                   12128:         }
                   12129:     }
                   12130: }
                   12131: 
1.1079    raeburn  12132: {
                   12133:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   12134:     if (-e $file) {
                   12135:         my $parser = HTML::LCParser->new($file);
                   12136:         while (my $token = $parser->get_token()) {
                   12137:             if ($token->[0] eq 'S') {
                   12138:                 my $item = $token->[1];
                   12139:                 my $name = $token->[2]{'name'};
                   12140:                 my $value = $token->[2]{'value'};
                   12141:                 if ($item ne '' && $name ne '' && $value ne '') {
                   12142:                     my $release = $parser->get_text();
                   12143:                     $release =~ s/(^\s*|\s*$ )//gx;
                   12144:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   12145:                 }
                   12146:             }
                   12147:         }
                   12148:     }
1.1073    raeburn  12149: }
                   12150: 
1.1138    raeburn  12151: # ---------------------------------------------------------- Read managers table
                   12152: {
                   12153:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   12154:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   12155:             while (my $configline=<$config>) {
                   12156:                 chomp($configline);
                   12157:                 next if ($configline =~ /^\#/);
                   12158:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   12159:                     $managerstab{$configline} = 1;
                   12160:                 }
                   12161:             }
                   12162:             close($config);
                   12163:         }
                   12164:     }
                   12165: }
                   12166: 
1.329     matthew  12167: # ------------- set up temporary directory
                   12168: {
1.1117    foxr     12169:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  12170: 
1.11      www      12171: }
                   12172: 
1.794     albertel 12173: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   12174: 				'compress_threshold'=> 20_000,
                   12175:  			        });
1.185     www      12176: 
1.281     www      12177: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      12178: $dumpcount=0;
1.958     www      12179: $locknum=0;
1.22      www      12180: 
1.163     harris41 12181: &logtouch();
1.672     albertel 12182: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      12183: $readit=1;
1.564     albertel 12184:     {
                   12185: 	use integer;
                   12186: 	my $test=(2**32)+1;
1.568     albertel 12187: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 12188: 	&logthis(" Detected 64bit platform ($_64bit)");
                   12189:     }
1.1172.2.18  raeburn  12190: 
                   12191:     {
                   12192:         eval {
                   12193:             ($apache) =
                   12194:                 (Apache2::ServerUtil::get_server_version() =~ m{Apache/(\d+\.\d+)});
                   12195:         };
                   12196:         if ($@) {
                   12197:            $apache = 1.3;
                   12198:         }
                   12199:     }
                   12200: 
1.195     www      12201: }
1.1       albertel 12202: }
1.179     www      12203: 
1.1       albertel 12204: 1;
1.191     harris41 12205: __END__
                   12206: 
1.243     albertel 12207: =pod
                   12208: 
1.191     harris41 12209: =head1 NAME
                   12210: 
1.243     albertel 12211: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 12212: 
                   12213: =head1 SYNOPSIS
                   12214: 
1.243     albertel 12215: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 12216: 
                   12217:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   12218: 
1.243     albertel 12219: Common parameters:
                   12220: 
                   12221: =over 4
                   12222: 
                   12223: =item *
                   12224: 
                   12225: $uname : an internal username (if $cname expecting a course Id specifically)
                   12226: 
                   12227: =item *
                   12228: 
                   12229: $udom : a domain (if $cdom expecting a course's domain specifically)
                   12230: 
                   12231: =item *
                   12232: 
                   12233: $symb : a resource instance identifier
                   12234: 
                   12235: =item *
                   12236: 
                   12237: $namespace : the name of a .db file that contains the data needed or
                   12238: being set.
                   12239: 
                   12240: =back
                   12241: 
1.394     bowersj2 12242: =head1 OVERVIEW
1.191     harris41 12243: 
1.394     bowersj2 12244: lonnet provides subroutines which interact with the
                   12245: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   12246: about classes, users, and resources.
1.243     albertel 12247: 
                   12248: For many of these objects you can also use this to store data about
                   12249: them or modify them in various ways.
1.191     harris41 12250: 
1.394     bowersj2 12251: =head2 Symbs
1.191     harris41 12252: 
1.394     bowersj2 12253: To identify a specific instance of a resource, LON-CAPA uses symbols
                   12254: or "symbs"X<symb>. These identifiers are built from the URL of the
                   12255: map, the resource number of the resource in the map, and the URL of
                   12256: the resource itself. The latter is somewhat redundant, but might help
                   12257: if maps change.
                   12258: 
                   12259: An example is
                   12260: 
                   12261:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   12262: 
                   12263: The respective map entry is
                   12264: 
                   12265:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   12266:   title="Problem 2">
                   12267:  </resource>
                   12268: 
                   12269: Symbs are used by the random number generator, as well as to store and
                   12270: restore data specific to a certain instance of for example a problem.
                   12271: 
                   12272: =head2 Storing And Retrieving Data
                   12273: 
                   12274: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   12275: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   12276: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   12277: is is the non-critical message twin of cstore. These functions are for
                   12278: handlers to store a perl hash to a user's permanent data space in an
                   12279: easy manner, and to retrieve it again on another call. It is expected
                   12280: that a handler would use this once at the beginning to retrieve data,
                   12281: and then again once at the end to send only the new data back.
                   12282: 
                   12283: The data is stored in the user's data directory on the user's
                   12284: homeserver under the ID of the course.
                   12285: 
                   12286: The hash that is returned by restore will have all of the previous
                   12287: value for all of the elements of the hash.
                   12288: 
                   12289: Example:
                   12290: 
                   12291:  #creating a hash
                   12292:  my %hash;
                   12293:  $hash{'foo'}='bar';
                   12294: 
                   12295:  #storing it
                   12296:  &Apache::lonnet::cstore(\%hash);
                   12297: 
                   12298:  #changing a value
                   12299:  $hash{'foo'}='notbar';
                   12300: 
                   12301:  #adding a new value
                   12302:  $hash{'bar'}='foo';
                   12303:  &Apache::lonnet::cstore(\%hash);
                   12304: 
                   12305:  #retrieving the hash
                   12306:  my %history=&Apache::lonnet::restore();
                   12307: 
                   12308:  #print the hash
                   12309:  foreach my $key (sort(keys(%history))) {
                   12310:    print("\%history{$key} = $history{$key}");
                   12311:  }
                   12312: 
                   12313: Will print out:
1.191     harris41 12314: 
1.394     bowersj2 12315:  %history{1:foo} = bar
                   12316:  %history{1:keys} = foo:timestamp
                   12317:  %history{1:timestamp} = 990455579
                   12318:  %history{2:bar} = foo
                   12319:  %history{2:foo} = notbar
                   12320:  %history{2:keys} = foo:bar:timestamp
                   12321:  %history{2:timestamp} = 990455580
                   12322:  %history{bar} = foo
                   12323:  %history{foo} = notbar
                   12324:  %history{timestamp} = 990455580
                   12325:  %history{version} = 2
                   12326: 
                   12327: Note that the special hash entries C<keys>, C<version> and
                   12328: C<timestamp> were added to the hash. C<version> will be equal to the
                   12329: total number of versions of the data that have been stored. The
                   12330: C<timestamp> attribute will be the UNIX time the hash was
                   12331: stored. C<keys> is available in every historical section to list which
                   12332: keys were added or changed at a specific historical revision of a
                   12333: hash.
                   12334: 
                   12335: B<Warning>: do not store the hash that restore returns directly. This
                   12336: will cause a mess since it will restore the historical keys as if the
                   12337: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 12338: 
1.394     bowersj2 12339: Calling convention:
1.191     harris41 12340: 
1.394     bowersj2 12341:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   12342:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 12343: 
1.394     bowersj2 12344: For more detailed information, see lonnet specific documentation.
1.191     harris41 12345: 
1.394     bowersj2 12346: =head1 RETURN MESSAGES
1.191     harris41 12347: 
1.394     bowersj2 12348: =over 4
1.191     harris41 12349: 
1.394     bowersj2 12350: =item * B<con_lost>: unable to contact remote host
1.191     harris41 12351: 
1.394     bowersj2 12352: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   12353: when the connection is brought back up
1.191     harris41 12354: 
1.394     bowersj2 12355: =item * B<con_failed>: unable to contact remote host and unable to save message
                   12356: for later delivery
1.191     harris41 12357: 
1.967     bisitz   12358: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 12359: 
1.394     bowersj2 12360: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 12361: that was requested
1.191     harris41 12362: 
1.243     albertel 12363: =back
1.191     harris41 12364: 
1.243     albertel 12365: =head1 PUBLIC SUBROUTINES
1.191     harris41 12366: 
1.243     albertel 12367: =head2 Session Environment Functions
1.191     harris41 12368: 
1.243     albertel 12369: =over 4
1.191     harris41 12370: 
1.394     bowersj2 12371: =item * 
                   12372: X<appenv()>
1.949     raeburn  12373: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 12374: the user envirnoment file, and will be restored for each access this
1.620     albertel 12375: user makes during this session, also modifies the %env for the current
1.949     raeburn  12376: process. Optional rolesarrayref - if defined contains a reference to an array
                   12377: of roles which are exempt from the restriction on modifying user.role entries 
                   12378: in the user's environment.db and in %env.    
1.191     harris41 12379: 
                   12380: =item *
1.394     bowersj2 12381: X<delenv()>
1.987     raeburn  12382: B<delenv($delthis,$regexp)>: removes all items from the session
                   12383: environment file that begin with $delthis. If the 
                   12384: optional second arg - $regexp - is true, $delthis is treated as a 
                   12385: regular expression, otherwise \Q$delthis\E is used. 
                   12386: The values are also deleted from the current processes %env.
1.191     harris41 12387: 
1.795     albertel 12388: =item * get_env_multiple($name) 
                   12389: 
                   12390: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   12391: values may be defined and end up as an array ref.
                   12392: 
                   12393: returns an array of values
                   12394: 
1.243     albertel 12395: =back
                   12396: 
                   12397: =head2 User Information
1.191     harris41 12398: 
1.243     albertel 12399: =over 4
1.191     harris41 12400: 
                   12401: =item *
1.394     bowersj2 12402: X<queryauthenticate()>
                   12403: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 12404: authentication scheme
                   12405: 
                   12406: =item *
1.394     bowersj2 12407: X<authenticate()>
1.1073    raeburn  12408: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 12409: authenticate user from domain's lib servers (first use the current
                   12410: one). C<$upass> should be the users password.
1.1073    raeburn  12411: $checkdefauth is optional (value is 1 if a check should be made to
                   12412:    authenticate user using default authentication method, and allow
                   12413:    account creation if username does not have account in the domain).
                   12414: $clientcancheckhost is optional (value is 1 if checking whether the
                   12415:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 12416: 
                   12417: =item *
1.394     bowersj2 12418: X<homeserver()>
                   12419: B<homeserver($uname,$udom)>: find the server which has
                   12420: the user's directory and files (there must be only one), this caches
                   12421: the answer, and also caches if there is a borken connection.
1.191     harris41 12422: 
                   12423: =item *
1.394     bowersj2 12424: X<idget()>
                   12425: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   12426: (IDs are a unique resource in a domain, there must be only 1 ID per
                   12427: username, and only 1 username per ID in a specific domain) (returns
                   12428: hash: id=>name,id=>name)
1.191     harris41 12429: 
                   12430: =item *
1.394     bowersj2 12431: X<idrget()>
                   12432: B<idrget($udom,@unames)>: find the IDs behind a list of
                   12433: usernames (returns hash: name=>id,name=>id)
1.191     harris41 12434: 
                   12435: =item *
1.394     bowersj2 12436: X<idput()>
                   12437: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 12438: 
                   12439: =item *
1.394     bowersj2 12440: X<rolesinit()>
1.1169    droeschl 12441: B<rolesinit($udom,$username)>: get user privileges.
                   12442: returns user role, first access and timer interval hashes
1.243     albertel 12443: 
                   12444: =item *
1.1171    droeschl 12445: X<privileged()>
                   12446: B<privileged($username,$domain)>: returns a true if user has a
                   12447: privileged and active role (i.e. su or dc), false otherwise.
                   12448: 
                   12449: =item *
1.551     albertel 12450: X<getsection()>
                   12451: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 12452: course $cname, return section name/number or '' for "not in course"
                   12453: and '-1' for "no section"
                   12454: 
                   12455: =item *
1.394     bowersj2 12456: X<userenvironment()>
                   12457: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 12458: passed in @what from the requested user's environment, returns a hash
                   12459: 
1.858     raeburn  12460: =item * 
                   12461: X<userlog_query()>
1.859     albertel 12462: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   12463: activity.log file. %filters defines filters applied when parsing the
                   12464: log file. These can be start or end timestamps, or the type of action
                   12465: - log to look for Login or Logout events, check for Checkin or
                   12466: Checkout, role for role selection. The response is in the form
                   12467: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   12468: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  12469: 
1.243     albertel 12470: =back
                   12471: 
                   12472: =head2 User Roles
                   12473: 
                   12474: =over 4
                   12475: 
                   12476: =item *
                   12477: 
1.810     raeburn  12478: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 12479:  F: full access
                   12480:  U,I,K: authentication modes (cxx only)
                   12481:  '': forbidden
                   12482:  1: user needs to choose course
                   12483:  2: browse allowed
1.766     albertel 12484:  A: passphrase authentication needed
1.243     albertel 12485: 
                   12486: =item *
                   12487: 
1.1172.2.13  raeburn  12488: constructaccess($url,$setpriv) : check for access to construction space URL
                   12489: 
                   12490: See if the owner domain and name in the URL match those in the
                   12491: expected environment.  If so, return three element list
                   12492: ($ownername,$ownerdomain,$ownerhome).
                   12493: 
                   12494: Otherwise return the null string.
                   12495: 
                   12496: If second argument 'setpriv' is true, it assigns the privileges,
                   12497: and returns the same three element list, unless the owner has
                   12498: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   12499: in which case the null string is returned.
                   12500: 
                   12501: =item *
                   12502: 
1.243     albertel 12503: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   12504: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   12505: and course level
                   12506: 
                   12507: =item *
                   12508: 
1.988     raeburn  12509: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   12510: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  12511: $type is Course (default) or Community.
1.988     raeburn  12512: If $forcedefault evaluates to true, text returned will be default 
                   12513: text for $type. Otherwise, if this is a course, the text returned 
                   12514: will be a custom name for the role (if defined in the course's 
                   12515: environment).  If no custom name is defined the default is returned.
                   12516:    
1.832     raeburn  12517: =item *
                   12518: 
1.935     raeburn  12519: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  12520: All arguments are optional. Returns a hash of a roles, either for
                   12521: co-author/assistant author roles for a user's Construction Space
1.906     albertel 12522: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  12523: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   12524: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   12525: For each key, value is set to colon-separated start and end times for
                   12526: the role.  If no username and domain are specified, will default to
1.934     raeburn  12527: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  12528: of role statuses (active, future or previous), roles 
                   12529: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   12530: to restrict the list of roles reported. If no array ref is 
                   12531: provided for types, will default to return only active roles.
1.834     albertel 12532: 
1.1172.2.13  raeburn  12533: =item *
                   12534: 
                   12535: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   12536: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   12537: 
                   12538: Additional optional arguments are: $type (if role checking is to be restricted
                   12539: to certain user status types -- previous (expired roles), active (currently
                   12540: available roles) or future (roles available in the future), and
                   12541: $hideprivileged -- if true will not report course roles for users who
                   12542: have active Domain Coordinator or Super User roles.
                   12543: 
1.243     albertel 12544: =back
                   12545: 
                   12546: =head2 User Modification
                   12547: 
                   12548: =over 4
                   12549: 
                   12550: =item *
                   12551: 
1.957     raeburn  12552: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 12553: user for the level given by URL.  Optional start and end dates (leave empty
                   12554: string or zero for "no date")
1.191     harris41 12555: 
                   12556: =item *
                   12557: 
1.243     albertel 12558: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   12559: change a users, password, possible return values are: ok,
                   12560: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   12561: refused
1.191     harris41 12562: 
                   12563: =item *
                   12564: 
1.243     albertel 12565: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 12566: 
                   12567: =item *
                   12568: 
1.1058    raeburn  12569: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   12570:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   12571: 
                   12572: will update user information (firstname,middlename,lastname,generation,
                   12573: permanentemail), and if forceid is true, student/employee ID also.
                   12574: A user's institutional affiliation(s) can also be updated.
                   12575: User information fields will not be overwritten with empty entries 
                   12576: unless the field is included in the $candelete array reference.
                   12577: This array is included when a single user is modified via "Manage Users",
                   12578: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 12579: 
                   12580: =item *
                   12581: 
1.286     matthew  12582: modifystudent
                   12583: 
1.957     raeburn  12584: modify a student's enrollment and identification information.
1.286     matthew  12585: The course id is resolved based on the current users environment.  
                   12586: This means the envoking user must be a course coordinator or otherwise
                   12587: associated with a course.
                   12588: 
1.297     matthew  12589: This call is essentially a wrapper for lonnet::modifyuser and
                   12590: lonnet::modify_student_enrollment
1.286     matthew  12591: 
                   12592: Inputs: 
                   12593: 
                   12594: =over 4
                   12595: 
1.957     raeburn  12596: =item B<$udom> Student's loncapa domain
1.286     matthew  12597: 
1.957     raeburn  12598: =item B<$uname> Student's loncapa login name
1.286     matthew  12599: 
1.964     bisitz   12600: =item B<$uid> Student/Employee ID
1.286     matthew  12601: 
1.957     raeburn  12602: =item B<$umode> Student's authentication mode
1.286     matthew  12603: 
1.957     raeburn  12604: =item B<$upass> Student's password
1.286     matthew  12605: 
1.957     raeburn  12606: =item B<$first> Student's first name
1.286     matthew  12607: 
1.957     raeburn  12608: =item B<$middle> Student's middle name
1.286     matthew  12609: 
1.957     raeburn  12610: =item B<$last> Student's last name
1.286     matthew  12611: 
1.957     raeburn  12612: =item B<$gene> Student's generation
1.286     matthew  12613: 
1.957     raeburn  12614: =item B<$usec> Student's section in course
1.286     matthew  12615: 
                   12616: =item B<$end> Unix time of the roles expiration
                   12617: 
                   12618: =item B<$start> Unix time of the roles start date
                   12619: 
                   12620: =item B<$forceid> If defined, allow $uid to be changed
                   12621: 
                   12622: =item B<$desiredhome> server to use as home server for student
                   12623: 
1.957     raeburn  12624: =item B<$email> Student's permanent e-mail address
                   12625: 
                   12626: =item B<$type> Type of enrollment (auto or manual)
                   12627: 
1.963     raeburn  12628: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   12629: 
                   12630: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  12631: 
1.963     raeburn  12632: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  12633: 
1.963     raeburn  12634: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  12635: 
1.1172.2.19  raeburn  12636: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   12637: 
                   12638: =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  12639: 
1.286     matthew  12640: =back
1.297     matthew  12641: 
                   12642: =item *
                   12643: 
                   12644: modify_student_enrollment
                   12645: 
                   12646: Change a students enrollment status in a class.  The environment variable
                   12647: 'role.request.course' must be defined for this function to proceed.
                   12648: 
                   12649: Inputs:
                   12650: 
                   12651: =over 4
                   12652: 
                   12653: =item $udom, students domain
                   12654: 
                   12655: =item $uname, students name
                   12656: 
                   12657: =item $uid, students user id
                   12658: 
                   12659: =item $first, students first name
                   12660: 
                   12661: =item $middle
                   12662: 
                   12663: =item $last
                   12664: 
                   12665: =item $gene
                   12666: 
                   12667: =item $usec
                   12668: 
                   12669: =item $end
                   12670: 
                   12671: =item $start
                   12672: 
1.957     raeburn  12673: =item $type
                   12674: 
                   12675: =item $locktype
                   12676: 
                   12677: =item $cid
                   12678: 
                   12679: =item $selfenroll
                   12680: 
                   12681: =item $context
                   12682: 
1.1172.2.19  raeburn  12683: =item $credits, number of credits student will earn from this class
                   12684: 
1.297     matthew  12685: =back
                   12686: 
1.191     harris41 12687: 
                   12688: =item *
                   12689: 
1.243     albertel 12690: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   12691: custom role; give a custom role to a user for the level given by URL.  Specify
                   12692: name and domain of role author, and role name
1.191     harris41 12693: 
                   12694: =item *
                   12695: 
1.243     albertel 12696: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 12697: 
                   12698: =item *
                   12699: 
1.243     albertel 12700: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   12701: 
                   12702: =back
                   12703: 
                   12704: =head2 Course Infomation
                   12705: 
                   12706: =over 4
1.191     harris41 12707: 
                   12708: =item *
                   12709: 
1.1118    foxr     12710: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 12711: specified course id, including all environment settings for the
                   12712: course, the description of the course will be in the hash under the
                   12713: key 'description'
1.191     harris41 12714: 
1.1118    foxr     12715: $options is an optional parameter that if supplied is a hash reference that controls
                   12716: what how this function works.  It has the following key/values:
                   12717: 
                   12718: =over 4
                   12719: 
                   12720: =item freshen_cache
                   12721: 
                   12722: If defined, and the environment cache for the course is valid, it is 
                   12723: returned in the returned hash.
                   12724: 
                   12725: =item one_time
                   12726: 
                   12727: If defined, the last cache time is set to _now_
                   12728: 
                   12729: =item user
                   12730: 
                   12731: If defined, the supplied username is used instead of the current user.
                   12732: 
                   12733: 
                   12734: =back
                   12735: 
1.191     harris41 12736: =item *
                   12737: 
1.624     albertel 12738: resdata($name,$domain,$type,@which) : request for current parameter
                   12739: setting for a specific $type, where $type is either 'course' or 'user',
                   12740: @what should be a list of parameters to ask about. This routine caches
                   12741: answers for 5 minutes.
1.243     albertel 12742: 
1.877     foxr     12743: =item *
                   12744: 
                   12745: get_courseresdata($courseid, $domain) : dump the entire course resource
                   12746: data base, returning a hash that is keyed by the resource name and has
                   12747: values that are the resource value.  I believe that the timestamps and
                   12748: versions are also returned.
                   12749: 
1.243     albertel 12750: =back
                   12751: 
                   12752: =head2 Course Modification
                   12753: 
                   12754: =over 4
1.191     harris41 12755: 
                   12756: =item *
                   12757: 
1.243     albertel 12758: writecoursepref($courseid,%prefs) : write preferences (environment
                   12759: database) for a course
1.191     harris41 12760: 
                   12761: =item *
                   12762: 
1.1011    raeburn  12763: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   12764: 
                   12765: =item *
                   12766: 
1.1038    raeburn  12767: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 12768: 
1.1167    droeschl 12769: =item *
                   12770: 
                   12771: is_course($courseid), is_course($cdom, $cnum)
                   12772: 
                   12773: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   12774: two component version $cdom, $cnum. It checks if the specified course exists.
                   12775: 
                   12776: Returns:
                   12777:     undef if the course doesn't exist, otherwise
                   12778:     in scalar context the combined courseid.
                   12779:     in list context the two components of the course identifier, domain and 
                   12780:     courseid.    
                   12781: 
1.243     albertel 12782: =back
                   12783: 
                   12784: =head2 Resource Subroutines
                   12785: 
                   12786: =over 4
1.191     harris41 12787: 
                   12788: =item *
                   12789: 
1.243     albertel 12790: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 12791: 
                   12792: =item *
                   12793: 
1.243     albertel 12794: repcopy($filename) : subscribes to the requested file, and attempts to
                   12795: replicate from the owning library server, Might return
1.607     raeburn  12796: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   12797: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 12798: resource. Expects the local filesystem pathname
                   12799: (/home/httpd/html/res/....)
                   12800: 
                   12801: =back
                   12802: 
                   12803: =head2 Resource Information
                   12804: 
                   12805: =over 4
1.191     harris41 12806: 
                   12807: =item *
                   12808: 
1.243     albertel 12809: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   12810: a vairety of different possible values, $varname should be a request
                   12811: string, and the other parameters can be used to specify who and what
                   12812: one is asking about.
                   12813: 
                   12814: Possible values for $varname are environment.lastname (or other item
                   12815: from the envirnment hash), user.name (or someother aspect about the
                   12816: user), resource.0.maxtries (or some other part and parameter of a
                   12817: resource)
1.204     albertel 12818: 
                   12819: =item *
                   12820: 
1.243     albertel 12821: directcondval($number) : get current value of a condition; reads from a state
                   12822: string
1.204     albertel 12823: 
                   12824: =item *
                   12825: 
1.243     albertel 12826: condval($condidx) : value of condition index based on state
1.204     albertel 12827: 
                   12828: =item *
                   12829: 
1.243     albertel 12830: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   12831: resource's metadata, $what should be either a specific key, or either
                   12832: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   12833: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   12834: 
                   12835: this function automatically caches all requests
1.191     harris41 12836: 
                   12837: =item *
                   12838: 
1.243     albertel 12839: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   12840: network of library servers; returns file handle of where SQL and regex results
                   12841: will be stored for query
1.191     harris41 12842: 
                   12843: =item *
                   12844: 
1.243     albertel 12845: symbread($filename) : return symbolic list entry (filename argument optional);
                   12846: returns the data handle
1.191     harris41 12847: 
                   12848: =item *
                   12849: 
1.1172.2.17  raeburn  12850: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  12851: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 12852: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  12853: on failure, user must be in a course, as it assumes the existence of
                   12854: the course initial hash, and uses $env('request.course.id'}.  The third
                   12855: arg is an optional reference to a scalar.  If this arg is passed in the
                   12856: call to symbverify, it will be set to 1 if the symb has been set to be 
                   12857: encrypted; otherwise it will be null.
1.243     albertel 12858: 
1.191     harris41 12859: =item *
                   12860: 
1.243     albertel 12861: symbclean($symb) : removes versions numbers from a symb, returns the
                   12862: cleaned symb
1.191     harris41 12863: 
                   12864: =item *
                   12865: 
1.243     albertel 12866: is_on_map($uri) : checks if the $uri is somewhere on the current
                   12867: course map, user must be in a course for it to work.
1.191     harris41 12868: 
                   12869: =item *
                   12870: 
1.243     albertel 12871: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 12872: 
                   12873: =item *
                   12874: 
1.243     albertel 12875: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   12876: a random seed, all arguments are optional, if they aren't sent it uses the
                   12877: environment to derive them. Note: if symb isn't sent and it can't get one
                   12878: from &symbread it will use the current time as its return value
1.191     harris41 12879: 
                   12880: =item *
                   12881: 
1.243     albertel 12882: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   12883: unfakeable, receipt
1.191     harris41 12884: 
                   12885: =item *
                   12886: 
1.620     albertel 12887: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 12888: 
                   12889: =item *
                   12890: 
1.243     albertel 12891: countacc($url) : count the number of accesses to a given URL
1.191     harris41 12892: 
                   12893: =item *
                   12894: 
1.243     albertel 12895: 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 12896: 
                   12897: =item *
                   12898: 
1.243     albertel 12899: 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 12900: 
                   12901: =item *
                   12902: 
1.243     albertel 12903: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 12904: 
                   12905: =item *
                   12906: 
1.243     albertel 12907: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   12908: forcing spreadsheet to reevaluate the resource scores next time.
                   12909: 
1.1172.2.13  raeburn  12910: =item *
                   12911: 
                   12912: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   12913: when viewing in course context.
                   12914: 
                   12915:  input: six args -- filename (decluttered), course number, course domain,
                   12916:                     url, symb (if registered) and group (if this is a
                   12917:                     group item -- e.g., bulletin board, group page etc.).
                   12918: 
                   12919:  output: array of five scalars --
                   12920:          $cfile -- url for file editing if editable on current server
                   12921:          $home -- homeserver of resource (i.e., for author if published,
                   12922:                                           or course if uploaded.).
                   12923:          $switchserver --  1 if server switch will be needed.
                   12924:          $forceedit -- 1 if icon/link should be to go to edit mode
                   12925:          $forceview -- 1 if icon/link should be to go to view mode
                   12926: 
                   12927: =item *
                   12928: 
                   12929: is_course_upload($file,$cnum,$cdom)
                   12930: 
                   12931: Used in course context to determine if current file was uploaded to
                   12932: the course (i.e., would be found in /userfiles/docs on the course's
                   12933: homeserver.
                   12934: 
                   12935:   input: 3 args -- filename (decluttered), course number and course domain.
                   12936:   output: boolean -- 1 if file was uploaded.
                   12937: 
1.243     albertel 12938: =back
                   12939: 
                   12940: =head2 Storing/Retreiving Data
                   12941: 
                   12942: =over 4
1.191     harris41 12943: 
                   12944: =item *
                   12945: 
1.243     albertel 12946: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   12947: for this url; hashref needs to be given and should be a \%hashname; the
                   12948: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 12949: be derived from the env
1.191     harris41 12950: 
                   12951: =item *
                   12952: 
1.243     albertel 12953: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   12954: uses critical subroutine
1.191     harris41 12955: 
                   12956: =item *
                   12957: 
1.243     albertel 12958: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   12959: all args are optional
1.191     harris41 12960: 
                   12961: =item *
                   12962: 
1.717     albertel 12963: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   12964: dumps the complete (or key matching regexp) namespace into a hash
                   12965: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   12966: normally &store()ed into
                   12967: 
                   12968: $range should be either an integer '100' (give me the first 100
                   12969:                                            matching records)
                   12970:               or be  two integers sperated by a - with no spaces
                   12971:                  '30-50' (give me the 30th through the 50th matching
                   12972:                           records)
                   12973: 
                   12974: 
                   12975: =item *
                   12976: 
                   12977: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   12978: replaces a &store() version of data with a replacement set of data
                   12979: for a particular resource in a namespace passed in the $storehash hash 
                   12980: reference
                   12981: 
                   12982: =item *
                   12983: 
1.243     albertel 12984: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   12985: works very similar to store/cstore, but all data is stored in a
                   12986: temporary location and can be reset using tmpreset, $storehash should
                   12987: be a hash reference, returns nothing on success
1.191     harris41 12988: 
                   12989: =item *
                   12990: 
1.243     albertel 12991: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   12992: similar to restore, but all data is stored in a temporary location and
                   12993: can be reset using tmpreset. Returns a hash of values on success,
                   12994: error string otherwise.
1.191     harris41 12995: 
                   12996: =item *
                   12997: 
1.243     albertel 12998: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   12999: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 13000: 
                   13001: =item *
                   13002: 
1.243     albertel 13003: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13004: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 13005: 
                   13006: =item *
                   13007: 
1.243     albertel 13008: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   13009: namesp ($udom and $uname are optional)
1.191     harris41 13010: 
                   13011: =item *
                   13012: 
1.702     albertel 13013: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 13014: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 13015: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  13016: 
1.702     albertel 13017: $range should be either an integer '100' (give me the first 100
                   13018:                                            matching records)
                   13019:               or be  two integers sperated by a - with no spaces
                   13020:                  '30-50' (give me the 30th through the 50th matching
                   13021:                           records)
1.449     matthew  13022: =item *
                   13023: 
                   13024: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   13025: $store can be a scalar, an array reference, or if the amount to be 
                   13026: incremented is > 1, a hash reference.
                   13027: 
                   13028: ($udom and $uname are optional)
1.191     harris41 13029: 
                   13030: =item *
                   13031: 
1.243     albertel 13032: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   13033: ($udom and $uname are optional)
1.191     harris41 13034: 
                   13035: =item *
                   13036: 
1.243     albertel 13037: cput($namespace,$storehash,$udom,$uname) : critical put
                   13038: ($udom and $uname are optional)
1.191     harris41 13039: 
                   13040: =item *
                   13041: 
1.748     albertel 13042: newput($namespace,$storehash,$udom,$uname) :
                   13043: 
                   13044: Attempts to store the items in the $storehash, but only if they don't
                   13045: currently exist, if this succeeds you can be certain that you have 
                   13046: successfully created a new key value pair in the $namespace db.
                   13047: 
                   13048: 
                   13049: Args:
                   13050:  $namespace: name of database to store values to
                   13051:  $storehash: hashref to store to the db
                   13052:  $udom: (optional) domain of user containing the db
                   13053:  $uname: (optional) name of user caontaining the db
                   13054: 
                   13055: Returns:
                   13056:  'ok' -> succeeded in storing all keys of $storehash
                   13057:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   13058:                         least <key> already existed in the db (other
                   13059:                         requested keys may also already exist)
1.967     bisitz   13060:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 13061:  'con_lost' -> unable to contact request server
                   13062:  'refused' -> action was not allowed by remote machine
                   13063: 
                   13064: 
                   13065: =item *
                   13066: 
1.243     albertel 13067: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13068: reference filled in from namesp (encrypts the return communication)
                   13069: ($udom and $uname are optional)
1.191     harris41 13070: 
                   13071: =item *
                   13072: 
1.243     albertel 13073: log($udom,$name,$home,$message) : write to permanent log for user; use
                   13074: critical subroutine
                   13075: 
1.806     raeburn  13076: =item *
                   13077: 
1.860     raeburn  13078: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   13079: array reference filled in from namespace found in domain level on either
                   13080: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  13081: 
                   13082: =item *
                   13083: 
1.860     raeburn  13084: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   13085: domain level either on specified domain server ($uhome) or primary domain 
                   13086: server ($udom and $uhome are optional)
1.806     raeburn  13087: 
1.943     raeburn  13088: =item * 
                   13089: 
                   13090: get_domain_defaults($target_domain) : returns hash with defaults for
                   13091: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   13092: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   13093: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   13094: Values are retrieved from cache (if current), or from domain's configuration.db
                   13095: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   13096: or lonTabs/domain.tab. 
                   13097: 
                   13098: %domdefaults = &get_auth_defaults($target_domain);
                   13099: 
1.243     albertel 13100: =back
                   13101: 
                   13102: =head2 Network Status Functions
                   13103: 
                   13104: =over 4
1.191     harris41 13105: 
                   13106: =item *
                   13107: 
1.1137    raeburn  13108: dirlist() : return directory list based on URI (first arg).
                   13109: 
                   13110: Inputs: 1 required, 5 optional.
                   13111: 
                   13112: =over
                   13113: 
                   13114: =item 
                   13115: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   13116: 
                   13117: =item
                   13118: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   13119: 
                   13120: =item
                   13121: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   13122: 
                   13123: =item
                   13124: $getpropath - boolean: 1 if prepend path using &propath(). 
                   13125: 
                   13126: =item
                   13127: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   13128: 
                   13129: =item 
                   13130: $alternateRoot - path to prepend in place of path from $uri.
                   13131: 
                   13132: =back
                   13133: 
                   13134: Returns: Array of up to two items.
                   13135: 
                   13136: =over
                   13137: 
                   13138: a reference to an array of files/subdirectories
                   13139: 
                   13140: =over
                   13141: 
                   13142: Each element in the array of files/subdirectories is a & separated list of
                   13143: item name and the result of running stat on the item.  If dirlist was requested
                   13144: for a file instead of a directory, the item name will be ''. For a directory 
                   13145: listing, if the item is a metadata file, the element will end &N&M 
                   13146: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   13147: default copyright set (1).  
                   13148: 
                   13149: =back
                   13150: 
                   13151: a scalar containing error condition (if encountered).
                   13152: 
                   13153: =over
                   13154: 
                   13155: =item 
                   13156: no_host (no homeserver identified for $username:$domain).
                   13157: 
                   13158: =item 
                   13159: no_such_host (server contacted for listing not identified as valid host).
                   13160: 
                   13161: =item 
                   13162: con_lost (connection to remote server failed).
                   13163: 
                   13164: =item 
                   13165: refused (invalid $username:$domain received on lond side).
                   13166: 
                   13167: =item 
                   13168: no_such_dir (directory at specified path on lond side does not exist). 
                   13169: 
                   13170: =item 
                   13171: empty (directory at specified path on lond side is empty).
                   13172: 
                   13173: =over
                   13174: 
                   13175: This is currently not encountered because the &ls3, &ls2, 
                   13176: &ls (_handler) routines on the lond side do not filter out
                   13177: . and .. from a directory listing. 
                   13178: 
                   13179: =back
                   13180: 
                   13181: =back
                   13182: 
                   13183: =back
1.191     harris41 13184: 
                   13185: =item *
                   13186: 
1.243     albertel 13187: spareserver() : find server with least workload from spare.tab
                   13188: 
1.986     foxr     13189: 
                   13190: =item *
                   13191: 
                   13192: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   13193: if there is no corresponding loncapa host.
                   13194: 
1.243     albertel 13195: =back
                   13196: 
1.986     foxr     13197: 
1.243     albertel 13198: =head2 Apache Request
                   13199: 
                   13200: =over 4
1.191     harris41 13201: 
                   13202: =item *
                   13203: 
1.243     albertel 13204: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   13205: localhost, posts hash
                   13206: 
                   13207: =back
                   13208: 
                   13209: =head2 Data to String to Data
                   13210: 
                   13211: =over 4
1.191     harris41 13212: 
                   13213: =item *
                   13214: 
1.243     albertel 13215: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   13216: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 13217: 
                   13218: =item *
                   13219: 
1.243     albertel 13220: hashref2str($hashref) : convert a hashref into a string complete with
                   13221: escaping and '=' and '&' separators, supports elements that are
                   13222: arrayrefs and hashrefs
1.191     harris41 13223: 
                   13224: =item *
                   13225: 
1.243     albertel 13226: arrayref2str($arrayref) : convert an arrayref into a string complete
                   13227: with escaping and '&' separators, supports elements that are arrayrefs
                   13228: and hashrefs
1.191     harris41 13229: 
                   13230: =item *
                   13231: 
1.243     albertel 13232: str2hash($string) : convert string to hash using unescaping and
                   13233: splitting on '=' and '&', supports elements that are arrayrefs and
                   13234: hashrefs
1.191     harris41 13235: 
                   13236: =item *
                   13237: 
1.243     albertel 13238: str2array($string) : convert string to hash using unescaping and
                   13239: splitting on '&', supports elements that are arrayrefs and hashrefs
                   13240: 
                   13241: =back
                   13242: 
                   13243: =head2 Logging Routines
                   13244: 
                   13245: 
                   13246: These routines allow one to make log messages in the lonnet.log and
                   13247: lonnet.perm logfiles.
1.191     harris41 13248: 
1.1119    foxr     13249: =over 4
                   13250: 
1.191     harris41 13251: =item *
                   13252: 
1.243     albertel 13253: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 13254: 
                   13255: =item *
                   13256: 
1.243     albertel 13257: logthis() : append message to the normal lonnet.log file, it gets
                   13258: preiodically rolled over and deleted.
1.191     harris41 13259: 
                   13260: =item *
                   13261: 
1.243     albertel 13262: logperm() : append a permanent message to lonnet.perm.log, this log
                   13263: file never gets deleted by any automated portion of the system, only
                   13264: messages of critical importance should go in here.
                   13265: 
1.1119    foxr     13266: 
1.243     albertel 13267: =back
                   13268: 
                   13269: =head2 General File Helper Routines
                   13270: 
                   13271: =over 4
1.191     harris41 13272: 
                   13273: =item *
                   13274: 
1.481     raeburn  13275: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   13276: (a) files in /uploaded
                   13277:   (i) If a local copy of the file exists - 
                   13278:       compares modification date of local copy with last-modified date for 
                   13279:       definitive version stored on home server for course. If local copy is 
                   13280:       stale, requests a new version from the home server and stores it. 
                   13281:       If the original has been removed from the home server, then local copy 
                   13282:       is unlinked.
                   13283:   (ii) If local copy does not exist -
                   13284:       requests the file from the home server and stores it. 
                   13285:   
                   13286:   If $caller is 'uploadrep':  
                   13287:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   13288:     for request for files originally uploaded via DOCS. 
                   13289:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   13290:   
                   13291:   Otherwise:
                   13292:      This indicates a call from the content generation phase of the request.
                   13293:      -  returns the entire contents of the file or -1.
                   13294:      
                   13295: (b) files in /res
                   13296:    - returns the entire contents of a file or -1; 
                   13297:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 13298: 
1.712     albertel 13299: 
                   13300: =item *
                   13301: 
                   13302: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   13303:                   reference
                   13304: 
                   13305: returns either a stat() list of data about the file or an empty list
                   13306: if the file doesn't exist or couldn't find out about it (connection
                   13307: problems or user unknown)
                   13308: 
1.191     harris41 13309: =item *
                   13310: 
1.243     albertel 13311: filelocation($dir,$file) : returns file system location of a file
                   13312: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   13313: directory that relative $file lookups are to looked in ($dir of /a/dir
                   13314: and a file of ../bob will become /a/bob)
1.191     harris41 13315: 
                   13316: =item *
                   13317: 
                   13318: hreflocation($dir,$file) : returns file system location or a URL; same as
                   13319: filelocation except for hrefs
                   13320: 
                   13321: =item *
                   13322: 
                   13323: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   13324: 
1.243     albertel 13325: =back
                   13326: 
1.608     albertel 13327: =head2 Usererfile file routines (/uploaded*)
                   13328: 
                   13329: =over 4
                   13330: 
                   13331: =item *
                   13332: 
                   13333: userfileupload(): main rotine for putting a file in a user or course's
                   13334:                   filespace, arguments are,
                   13335: 
1.620     albertel 13336:  formname - required - this is the name of the element in $env where the
1.608     albertel 13337:            filename, and the contents of the file to create/modifed exist
1.620     albertel 13338:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   13339:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  13340:  context - if coursedoc, store the file in the course of the active role
                   13341:              of the current user; 
                   13342:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   13343:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 13344:  subdir - required - subdirectory to put the file in under ../userfiles/
                   13345:          if undefined, it will be placed in "unknown"
                   13346: 
                   13347:  (This routine calls clean_filename() to remove any dangerous
                   13348:  characters from the filename, and then calls finuserfileupload() to
                   13349:  complete the transaction)
                   13350: 
                   13351:  returns either the url of the uploaded file (/uploaded/....) if successful
                   13352:  and /adm/notfound.html if unsuccessful
                   13353: 
                   13354: =item *
                   13355: 
                   13356: clean_filename(): routine for cleaing a filename up for storage in
                   13357:                  userfile space, argument is:
                   13358: 
                   13359:  filename - proposed filename
                   13360: 
                   13361: returns: the new clean filename
                   13362: 
                   13363: =item *
                   13364: 
1.1090    raeburn  13365: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 13366: userspace, probably shouldn't be called directly
                   13367: 
                   13368:   docuname: username or courseid of destination for the file
                   13369:   docudom: domain of user/course of destination for the file
                   13370:   formname: same as for userfileupload()
1.1090    raeburn  13371:   fname: filename (including subdirectories) for the file
                   13372:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   13373:   allfiles: reference to hash used to store objects found by parser
                   13374:   codebase: reference to hash used for codebases of java objects found by parser
                   13375:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   13376:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   13377:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   13378:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   13379:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   13380:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  13381:   mimetype: reference to scalar to accommodate mime type determined
                   13382:             from File::MMagic if $parser = parse.
1.608     albertel 13383: 
                   13384:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  13385:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   13386:  was 'overwrite').
                   13387:  
1.608     albertel 13388: 
                   13389: =item *
                   13390: 
                   13391: renameuserfile(): renames an existing userfile to a new name
                   13392: 
                   13393:   Args:
                   13394:    docuname: username or courseid of destination for the file
                   13395:    docudom: domain of user/course of destination for the file
                   13396:    old: current file name (including any subdirs under userfiles)
                   13397:    new: desired file name (including any subdirs under userfiles)
                   13398: 
                   13399: =item *
                   13400: 
                   13401: mkdiruserfile(): creates a directory is a userfiles dir
                   13402: 
                   13403:   Args:
                   13404:    docuname: username or courseid of destination for the file
                   13405:    docudom: domain of user/course of destination for the file
                   13406:    dir: dir to create (including any subdirs under userfiles)
                   13407: 
                   13408: =item *
                   13409: 
                   13410: removeuserfile(): removes a file that exists in userfiles
                   13411: 
                   13412:   Args:
                   13413:    docuname: username or courseid of destination for the file
                   13414:    docudom: domain of user/course of destination for the file
                   13415:    fname: filname to delete (including any subdirs under userfiles)
                   13416: 
                   13417: =item *
                   13418: 
                   13419: removeuploadedurl(): convience function for removeuserfile()
                   13420: 
                   13421:   Args:
                   13422:    url:  a full /uploaded/... url to delete
                   13423: 
1.747     albertel 13424: =item * 
                   13425: 
                   13426: get_portfile_permissions():
                   13427:   Args:
                   13428:     domain: domain of user or course contain the portfolio files
                   13429:     user: name of user or num of course contain the portfolio files
                   13430:   Returns:
                   13431:     hashref of a dump of the proper file_permissions.db
                   13432:    
                   13433: 
                   13434: =item * 
                   13435: 
                   13436: get_access_controls():
                   13437: 
                   13438: Args:
                   13439:   current_permissions: the hash ref returned from get_portfile_permissions()
                   13440:   group: (optional) the group you want the files associated with
                   13441:   file: (optional) the file you want access info on
                   13442: 
                   13443: Returns:
1.749     raeburn  13444:     a hash (keys are file names) of hashes containing
                   13445:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   13446:         values are XML containing access control settings (see below) 
1.747     albertel 13447: 
                   13448: Internal notes:
                   13449: 
1.749     raeburn  13450:  access controls are stored in file_permissions.db as key=value pairs.
                   13451:     key -> path to file/file_name\0uniqueID:scope_end_start
                   13452:         where scope -> public,guest,course,group,domains or users.
                   13453:               end -> UNIX time for end of access (0 -> no end date)
                   13454:               start -> UNIX time for start of access
                   13455: 
                   13456:     value -> XML description of access control
                   13457:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   13458:             <start></start>
                   13459:             <end></end>
                   13460: 
                   13461:             <password></password>  for scope type = guest
                   13462: 
                   13463:             <domain></domain>     for scope type = course or group
                   13464:             <number></number>
                   13465:             <roles id="">
                   13466:              <role></role>
                   13467:              <access></access>
                   13468:              <section></section>
                   13469:              <group></group>
                   13470:             </roles>
                   13471: 
                   13472:             <dom></dom>         for scope type = domains
                   13473: 
                   13474:             <users>             for scope type = users
                   13475:              <user>
                   13476:               <uname></uname>
                   13477:               <udom></udom>
                   13478:              </user>
                   13479:             </users>
                   13480:            </scope> 
                   13481:               
                   13482:  Access data is also aggregated for each file in an additional key=value pair:
                   13483:  key -> path to file/file_name\0accesscontrol 
                   13484:  value -> reference to hash
                   13485:           hash contains key = value pairs
                   13486:           where key = uniqueID:scope_end_start
                   13487:                 value = UNIX time record was last updated
                   13488: 
                   13489:           Used to improve speed of look-ups of access controls for each file.  
                   13490:  
                   13491:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   13492: 
1.1172.2.13  raeburn  13493: =item *
                   13494: 
1.749     raeburn  13495: modify_access_controls():
                   13496: 
                   13497: Modifies access controls for a portfolio file
                   13498: Args
                   13499: 1. file name
                   13500: 2. reference to hash of required changes,
                   13501: 3. domain
                   13502: 4. username
                   13503:   where domain,username are the domain of the portfolio owner 
                   13504:   (either a user or a course) 
                   13505: 
                   13506: Returns:
                   13507: 1. result of additions or updates ('ok' or 'error', with error message). 
                   13508: 2. result of deletions ('ok' or 'error', with error message).
                   13509: 3. reference to hash of any new or updated access controls.
                   13510: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   13511:    key = integer (inbound ID)
1.1172.2.13  raeburn  13512:    value = uniqueID
                   13513: 
                   13514: =item *
                   13515: 
                   13516: get_timebased_id():
                   13517: 
                   13518: Attempts to get a unique timestamp-based suffix for use with items added to a
                   13519: course via the Course Editor (e.g., folders, composite pages,
                   13520: group bulletin boards).
                   13521: 
                   13522: Args: (first three required; six others optional)
                   13523: 
                   13524: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   13525:    docssequence, or name of group
                   13526: 
                   13527: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   13528:    e.g., num, boardids
                   13529: 
                   13530: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   13531:    file will be named nohist_namespace.db
                   13532: 
                   13533: 4. cdom: domain of course; default is current course domain from %env
                   13534: 
                   13535: 5. cnum: course number; default is current course number from %env
                   13536: 
                   13537: 6. idtype: set to concat if an additional digit is to be appended to the
                   13538:    unix timestamp to form the suffix, if the plain timestamp is already
                   13539:    in use.  Default is to not do this, but simply increment the unix
                   13540:    timestamp by 1 until a unique key is obtained.
                   13541: 
                   13542: 7. who: holder of locking key; defaults to user:domain for user.
                   13543: 
                   13544: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   13545:    retrying); default is 3.
                   13546: 
                   13547: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   13548: 
                   13549: Returns:
                   13550: 
                   13551: 1. suffix obtained (numeric)
                   13552: 
                   13553: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   13554: 
                   13555: 3. error: contains (localized) error message if an error occurred.
                   13556: 
1.747     albertel 13557: 
1.608     albertel 13558: =back
                   13559: 
1.243     albertel 13560: =head2 HTTP Helper Routines
                   13561: 
                   13562: =over 4
                   13563: 
1.191     harris41 13564: =item *
                   13565: 
                   13566: escape() : unpack non-word characters into CGI-compatible hex codes
                   13567: 
                   13568: =item *
                   13569: 
                   13570: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   13571: 
1.243     albertel 13572: =back
                   13573: 
                   13574: =head1 PRIVATE SUBROUTINES
                   13575: 
                   13576: =head2 Underlying communication routines (Shouldn't call)
                   13577: 
                   13578: =over 4
                   13579: 
                   13580: =item *
                   13581: 
                   13582: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   13583: 
                   13584: =item *
                   13585: 
                   13586: reply() : uses subreply to send a message to remote machine, logs all failures
                   13587: 
                   13588: =item *
                   13589: 
                   13590: critical() : passes a critical message to another server; if cannot
                   13591: get through then place message in connection buffer directory and
                   13592: returns con_delayed, if incapable of saving message, returns
                   13593: con_failed
                   13594: 
                   13595: =item *
                   13596: 
                   13597: reconlonc() : tries to reconnect lonc client processes.
                   13598: 
                   13599: =back
                   13600: 
                   13601: =head2 Resource Access Logging
                   13602: 
                   13603: =over 4
                   13604: 
                   13605: =item *
                   13606: 
                   13607: flushcourselogs() : flush (save) buffer logs and access logs
                   13608: 
                   13609: =item *
                   13610: 
                   13611: courselog($what) : save message for course in hash
                   13612: 
                   13613: =item *
                   13614: 
                   13615: courseacclog($what) : save message for course using &courselog().  Perform
                   13616: special processing for specific resource types (problems, exams, quizzes, etc).
                   13617: 
1.191     harris41 13618: =item *
                   13619: 
                   13620: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   13621: as a PerlChildExitHandler
1.243     albertel 13622: 
                   13623: =back
                   13624: 
                   13625: =head2 Other
                   13626: 
                   13627: =over 4
                   13628: 
                   13629: =item *
                   13630: 
                   13631: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 13632: 
                   13633: =back
                   13634: 
                   13635: =cut
1.877     foxr     13636: 

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