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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.32! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.31 2013/08/08 02:09:10 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.1172.2.30  raeburn  1579: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1580: 
                   1581: sub iddel {
                   1582:     my ($udom,$idshashref,$uhome)=@_;
                   1583:     my %result=();
                   1584:     unless (ref($idshashref) eq 'HASH') {
                   1585:         return %result;
                   1586:     }
                   1587:     my %servers=();
                   1588:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1589:         my $uhom;
                   1590:         if ($uhome) {
                   1591:             $uhom = $uhome;
                   1592:         } else {
                   1593:             $uhom=&homeserver($uname,$udom);
                   1594:         }
                   1595:         if ($uhom ne 'no_host') {
                   1596:             if ($servers{$uhom}) {
                   1597:                 $servers{$uhom}.='&'.&escape($id);
                   1598:             } else {
                   1599:                 $servers{$uhom}=&escape($id);
                   1600:             }
                   1601:         }
                   1602:     }
                   1603:     foreach my $server (keys(%servers)) {
                   1604:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1605:     }
                   1606:     return %result;
                   1607: }
                   1608: 
1.1023    raeburn  1609: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1610: sub dump_dom {
1.1165    droeschl 1611:     my ($namespace, $udom, $regexp) = @_;
                   1612: 
                   1613:     $udom ||= $env{'user.domain'};
                   1614: 
                   1615:     return () unless $udom;
                   1616: 
                   1617:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1618: }
                   1619: 
1.1023    raeburn  1620: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1621: 
                   1622: sub get_dom {
1.860     raeburn  1623:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1624:     my $items='';
                   1625:     foreach my $item (@$storearr) {
                   1626:         $items.=&escape($item).'&';
                   1627:     }
                   1628:     $items=~s/\&$//;
1.860     raeburn  1629:     if (!$udom) {
                   1630:         $udom=$env{'user.domain'};
                   1631:         if (defined(&domain($udom,'primary'))) {
                   1632:             $uhome=&domain($udom,'primary');
                   1633:         } else {
1.874     albertel 1634:             undef($uhome);
1.860     raeburn  1635:         }
                   1636:     } else {
                   1637:         if (!$uhome) {
                   1638:             if (defined(&domain($udom,'primary'))) {
                   1639:                 $uhome=&domain($udom,'primary');
                   1640:             }
                   1641:         }
                   1642:     }
                   1643:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1644:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1645:         my %returnhash;
1.875     albertel 1646:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1647:             return %returnhash;
                   1648:         }
1.806     raeburn  1649:         my @pairs=split(/\&/,$rep);
                   1650:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1651:             return @pairs;
                   1652:         }
                   1653:         my $i=0;
                   1654:         foreach my $item (@$storearr) {
                   1655:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1656:             $i++;
                   1657:         }
                   1658:         return %returnhash;
                   1659:     } else {
1.880     banghart 1660:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1661:     }
                   1662: }
                   1663: 
                   1664: # -------------------------------------------- put items in domain db files 
                   1665: 
                   1666: sub put_dom {
1.860     raeburn  1667:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1668:     if (!$udom) {
                   1669:         $udom=$env{'user.domain'};
                   1670:         if (defined(&domain($udom,'primary'))) {
                   1671:             $uhome=&domain($udom,'primary');
                   1672:         } else {
1.874     albertel 1673:             undef($uhome);
1.860     raeburn  1674:         }
                   1675:     } else {
                   1676:         if (!$uhome) {
                   1677:             if (defined(&domain($udom,'primary'))) {
                   1678:                 $uhome=&domain($udom,'primary');
                   1679:             }
                   1680:         }
                   1681:     } 
                   1682:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1683:         my $items='';
                   1684:         foreach my $item (keys(%$storehash)) {
                   1685:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1686:         }
                   1687:         $items=~s/\&$//;
                   1688:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1689:     } else {
1.860     raeburn  1690:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1691:     }
                   1692: }
                   1693: 
1.1023    raeburn  1694: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1695: sub newput_dom {
1.1023    raeburn  1696:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1697:     my $result;
                   1698:     if (!$udom) {
                   1699:         $udom=$env{'user.domain'};
                   1700:     }
1.1023    raeburn  1701:     if ($udom) {
                   1702:         my $uname = &get_domainconfiguser($udom);
                   1703:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1704:     }
                   1705:     return $result;
                   1706: }
                   1707: 
1.1023    raeburn  1708: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1709: sub del_dom {
1.1023    raeburn  1710:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1711:     if (ref($storearr) eq 'ARRAY') {
                   1712:         if (!$udom) {
                   1713:             $udom=$env{'user.domain'};
                   1714:         }
1.1023    raeburn  1715:         if ($udom) {
                   1716:             my $uname = &get_domainconfiguser($udom); 
                   1717:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1718:         }
                   1719:     }
                   1720: }
                   1721: 
1.1023    raeburn  1722: # ----------------------------------construct domainconfig user for a domain 
                   1723: sub get_domainconfiguser {
                   1724:     my ($udom) = @_;
                   1725:     return $udom.'-domainconfig';
                   1726: }
                   1727: 
1.837     raeburn  1728: sub retrieve_inst_usertypes {
                   1729:     my ($udom) = @_;
                   1730:     my (%returnhash,@order);
1.989     raeburn  1731:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1732:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1733:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1734:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1735:         @order = @{$domdefs{'inststatusorder'}};
                   1736:     } else {
                   1737:         if (defined(&domain($udom,'primary'))) {
                   1738:             my $uhome=&domain($udom,'primary');
                   1739:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1740:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1741:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1742:                 return (\%returnhash,\@order);
                   1743:             }
                   1744:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1745:             my @pairs=split(/\&/,$hashitems);
                   1746:             foreach my $item (@pairs) {
                   1747:                 my ($key,$value)=split(/=/,$item,2);
                   1748:                 $key = &unescape($key);
                   1749:                 next if ($key =~ /^error: 2 /);
                   1750:                 $returnhash{$key}=&thaw_unescape($value);
                   1751:             }
                   1752:             my @esc_order = split(/\&/,$orderitems);
                   1753:             foreach my $item (@esc_order) {
                   1754:                 push(@order,&unescape($item));
                   1755:             }
                   1756:         } else {
                   1757:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1758:         }
                   1759:     }
                   1760:     return (\%returnhash,\@order);
                   1761: }
                   1762: 
1.868     raeburn  1763: sub is_domainimage {
                   1764:     my ($url) = @_;
                   1765:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1766:         if (&domain($1) ne '') {
                   1767:             return '1';
                   1768:         }
                   1769:     }
                   1770:     return;
                   1771: }
                   1772: 
1.899     raeburn  1773: sub inst_directory_query {
                   1774:     my ($srch) = @_;
                   1775:     my $udom = $srch->{'srchdomain'};
                   1776:     my %results;
                   1777:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1778:     my $outcome;
1.899     raeburn  1779:     if ($homeserver ne '') {
1.904     albertel 1780: 	my $queryid=&reply("querysend:instdirsearch:".
                   1781: 			   &escape($srch->{'srchby'}).':'.
                   1782: 			   &escape($srch->{'srchterm'}).':'.
                   1783: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1784: 	my $host=&hostname($homeserver);
                   1785: 	if ($queryid !~/^\Q$host\E\_/) {
                   1786: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1787: 	    return;
                   1788: 	}
                   1789: 	my $response = &get_query_reply($queryid);
                   1790: 	my $maxtries = 5;
                   1791: 	my $tries = 1;
                   1792: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1793: 	    $response = &get_query_reply($queryid);
                   1794: 	    $tries ++;
                   1795: 	}
                   1796: 
                   1797:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1798:             if ($response eq 'unavailable') {
                   1799:                 $outcome = $response;
                   1800:             } else {
                   1801:                 $outcome = 'ok';
                   1802:                 my @matches = split(/\n/,$response);
                   1803:                 foreach my $match (@matches) {
                   1804:                     my ($key,$value) = split(/=/,$match);
                   1805:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1806:                 }
1.899     raeburn  1807:             }
                   1808:         }
                   1809:     }
1.909     raeburn  1810:     return ($outcome,%results);
1.899     raeburn  1811: }
                   1812: 
                   1813: sub usersearch {
                   1814:     my ($srch) = @_;
                   1815:     my $dom = $srch->{'srchdomain'};
                   1816:     my %results;
                   1817:     my %libserv = &all_library();
                   1818:     my $query = 'usersearch';
                   1819:     foreach my $tryserver (keys(%libserv)) {
                   1820:         if (&host_domain($tryserver) eq $dom) {
                   1821:             my $host=&hostname($tryserver);
                   1822:             my $queryid=
1.911     raeburn  1823:                 &reply("querysend:".&escape($query).':'.
                   1824:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1825:                        &escape($srch->{'srchtype'}).':'.
                   1826:                        &escape($srch->{'srchterm'}),$tryserver);
                   1827:             if ($queryid !~/^\Q$host\E\_/) {
                   1828:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1829:                 next;
1.899     raeburn  1830:             }
                   1831:             my $reply = &get_query_reply($queryid);
                   1832:             my $maxtries = 1;
                   1833:             my $tries = 1;
                   1834:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1835:                 $reply = &get_query_reply($queryid);
                   1836:                 $tries ++;
                   1837:             }
                   1838:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1839:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1840:             } else {
1.911     raeburn  1841:                 my @matches;
                   1842:                 if ($reply =~ /\n/) {
                   1843:                     @matches = split(/\n/,$reply);
                   1844:                 } else {
                   1845:                     @matches = split(/\&/,$reply);
                   1846:                 }
1.899     raeburn  1847:                 foreach my $match (@matches) {
                   1848:                     my ($uname,$udom,%userhash);
1.911     raeburn  1849:                     foreach my $entry (split(/:/,$match)) {
                   1850:                         my ($key,$value) =
                   1851:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1852:                         $userhash{$key} = $value;
                   1853:                         if ($key eq 'username') {
                   1854:                             $uname = $value;
                   1855:                         } elsif ($key eq 'domain') {
                   1856:                             $udom = $value;
1.911     raeburn  1857:                         }
1.899     raeburn  1858:                     }
                   1859:                     $results{$uname.':'.$udom} = \%userhash;
                   1860:                 }
                   1861:             }
                   1862:         }
                   1863:     }
                   1864:     return %results;
                   1865: }
                   1866: 
1.912     raeburn  1867: sub get_instuser {
                   1868:     my ($udom,$uname,$id) = @_;
                   1869:     my $homeserver = &domain($udom,'primary');
                   1870:     my ($outcome,%results);
                   1871:     if ($homeserver ne '') {
                   1872:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1873:                            &escape($id).':'.&escape($udom),$homeserver);
                   1874:         my $host=&hostname($homeserver);
                   1875:         if ($queryid !~/^\Q$host\E\_/) {
                   1876:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1877:             return;
                   1878:         }
                   1879:         my $response = &get_query_reply($queryid);
                   1880:         my $maxtries = 5;
                   1881:         my $tries = 1;
                   1882:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1883:             $response = &get_query_reply($queryid);
                   1884:             $tries ++;
                   1885:         }
                   1886:         if (!&error($response) && $response ne 'refused') {
                   1887:             if ($response eq 'unavailable') {
                   1888:                 $outcome = $response;
                   1889:             } else {
                   1890:                 $outcome = 'ok';
                   1891:                 my @matches = split(/\n/,$response);
                   1892:                 foreach my $match (@matches) {
                   1893:                     my ($key,$value) = split(/=/,$match);
                   1894:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1895:                 }
                   1896:             }
                   1897:         }
                   1898:     }
                   1899:     my %userinfo;
                   1900:     if (ref($results{$uname}) eq 'HASH') {
                   1901:         %userinfo = %{$results{$uname}};
                   1902:     } 
                   1903:     return ($outcome,%userinfo);
                   1904: }
                   1905: 
                   1906: sub inst_rulecheck {
1.923     raeburn  1907:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1908:     my %returnhash;
                   1909:     if ($udom ne '') {
                   1910:         if (ref($rules) eq 'ARRAY') {
                   1911:             @{$rules} = map {&escape($_);} (@{$rules});
                   1912:             my $rulestr = join(':',@{$rules});
                   1913:             my $homeserver=&domain($udom,'primary');
                   1914:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1915:                 my $response;
                   1916:                 if ($item eq 'username') {                
                   1917:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1918:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1919:                                               $homeserver));
1.923     raeburn  1920:                 } elsif ($item eq 'id') {
                   1921:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1922:                                               ':'.&escape($id).':'.$rulestr,
                   1923:                                               $homeserver));
1.945     raeburn  1924:                 } elsif ($item eq 'selfcreate') {
                   1925:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1926:                                                &escape($udom).':'.&escape($uname).
                   1927:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1928:                 }
1.912     raeburn  1929:                 if ($response ne 'refused') {
                   1930:                     my @pairs=split(/\&/,$response);
                   1931:                     foreach my $item (@pairs) {
                   1932:                         my ($key,$value)=split(/=/,$item,2);
                   1933:                         $key = &unescape($key);
                   1934:                         next if ($key =~ /^error: 2 /);
                   1935:                         $returnhash{$key}=&thaw_unescape($value);
                   1936:                     }
                   1937:                 }
                   1938:             }
                   1939:         }
                   1940:     }
                   1941:     return %returnhash;
                   1942: }
                   1943: 
                   1944: sub inst_userrules {
1.923     raeburn  1945:     my ($udom,$check) = @_;
1.912     raeburn  1946:     my (%ruleshash,@ruleorder);
                   1947:     if ($udom ne '') {
                   1948:         my $homeserver=&domain($udom,'primary');
                   1949:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1950:             my $response;
                   1951:             if ($check eq 'id') {
                   1952:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1953:                                  $homeserver);
1.943     raeburn  1954:             } elsif ($check eq 'email') {
                   1955:                 $response=&reply('instemailrules:'.&escape($udom),
                   1956:                                  $homeserver);
1.923     raeburn  1957:             } else {
                   1958:                 $response=&reply('instuserrules:'.&escape($udom),
                   1959:                                  $homeserver);
                   1960:             }
1.912     raeburn  1961:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1962:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1963:                 ($response ne 'no_such_host')) {
                   1964:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1965:                 my @pairs=split(/\&/,$hashitems);
                   1966:                 foreach my $item (@pairs) {
                   1967:                     my ($key,$value)=split(/=/,$item,2);
                   1968:                     $key = &unescape($key);
                   1969:                     next if ($key =~ /^error: 2 /);
                   1970:                     $ruleshash{$key}=&thaw_unescape($value);
                   1971:                 }
                   1972:                 my @esc_order = split(/\&/,$orderitems);
                   1973:                 foreach my $item (@esc_order) {
                   1974:                     push(@ruleorder,&unescape($item));
                   1975:                 }
                   1976:             }
                   1977:         }
                   1978:     }
                   1979:     return (\%ruleshash,\@ruleorder);
                   1980: }
                   1981: 
1.976     raeburn  1982: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1983: 
                   1984: sub get_domain_defaults {
                   1985:     my ($domain) = @_;
                   1986:     my $cachetime = 60*60*24;
                   1987:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1988:     if (defined($cached)) {
                   1989:         if (ref($result) eq 'HASH') {
                   1990:             return %{$result};
                   1991:         }
                   1992:     }
                   1993:     my %domdefaults;
                   1994:     my %domconfig =
1.989     raeburn  1995:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1996:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  1997:                                   'coursedefaults','usersessions',
                   1998:                                   'requestauthor'],$domain);
1.943     raeburn  1999:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2000:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2001:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2002:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2003:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2004:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2005:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  2006:     } else {
                   2007:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2008:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2009:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2010:     }
1.976     raeburn  2011:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2012:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2013:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2014:         } else {
                   2015:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2016:         }
1.1172.2.6  raeburn  2017:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2018:         foreach my $item (@usertools) {
                   2019:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2020:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2021:             }
                   2022:         }
1.1172.2.29  raeburn  2023:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2024:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2025:         }
1.976     raeburn  2026:     }
1.985     raeburn  2027:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  2028:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  2029:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2030:         }
                   2031:     }
1.1172.2.9  raeburn  2032:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2033:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2034:     }
1.989     raeburn  2035:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   2036:         foreach my $item ('inststatustypes','inststatusorder') {
                   2037:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2038:         }
                   2039:     }
1.1047    raeburn  2040:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.19  raeburn  2041:         if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2042:             $domdefaults{'officialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'official'};
                   2043:             $domdefaults{'unofficialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'unofficial'};
1.1047    raeburn  2044:         }
1.1172.2.30  raeburn  2045:         if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2046:             $domdefaults{'officialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'official'};
                   2047:             $domdefaults{'unofficialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'unofficial'};
                   2048:             $domdefaults{'communityquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'community'};
                   2049:         }
1.1047    raeburn  2050:     }
1.1073    raeburn  2051:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2052:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2053:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2054:         }
                   2055:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2056:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2057:         }
                   2058:     }
1.1172.2.23  raeburn  2059:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2060:     return %domdefaults;
                   2061: }
                   2062: 
1.344     www      2063: # --------------------------------------------------- Assign a key to a student
                   2064: 
                   2065: sub assign_access_key {
1.364     www      2066: #
                   2067: # a valid key looks like uname:udom#comments
                   2068: # comments are being appended
                   2069: #
1.498     www      2070:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2071:     $kdom=
1.620     albertel 2072:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2073:     $knum=
1.620     albertel 2074:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2075:     $cdom=
1.620     albertel 2076:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2077:     $cnum=
1.620     albertel 2078:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2079:     $udom=$env{'user.name'} unless (defined($udom));
                   2080:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2081:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2082:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2083:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2084:                                                   # assigned to this person
                   2085:                                                   # - this should not happen,
1.345     www      2086:                                                   # unless something went wrong
                   2087:                                                   # the first time around
                   2088: # ready to assign
1.364     www      2089:         $logentry=$1.'; '.$logentry;
1.496     www      2090:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2091:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2092: # key now belongs to user
1.346     www      2093: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2094:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2095:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2096:                 return 'ok';
                   2097:             } else {
                   2098:                 return 
                   2099:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2100: 	    }
                   2101:         } else {
                   2102:             return 'error: Could not assign key, try again later.';
                   2103:         }
1.364     www      2104:     } elsif (!$existing{$ckey}) {
1.345     www      2105: # the key does not exist
                   2106: 	return 'error: The key does not exist';
                   2107:     } else {
                   2108: # the key is somebody else's
                   2109: 	return 'error: The key is already in use';
                   2110:     }
1.344     www      2111: }
                   2112: 
1.364     www      2113: # ------------------------------------------ put an additional comment on a key
                   2114: 
                   2115: sub comment_access_key {
                   2116: #
                   2117: # a valid key looks like uname:udom#comments
                   2118: # comments are being appended
                   2119: #
                   2120:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2121:     $cdom=
1.620     albertel 2122:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2123:     $cnum=
1.620     albertel 2124:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2125:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2126:     if ($existing{$ckey}) {
                   2127:         $existing{$ckey}.='; '.$logentry;
                   2128: # ready to assign
1.367     www      2129:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2130:                                                  $cdom,$cnum) eq 'ok') {
                   2131: 	    return 'ok';
                   2132:         } else {
                   2133: 	    return 'error: Count not store comment.';
                   2134:         }
                   2135:     } else {
                   2136: # the key does not exist
                   2137: 	return 'error: The key does not exist';
                   2138:     }
                   2139: }
                   2140: 
1.344     www      2141: # ------------------------------------------------------ Generate a set of keys
                   2142: 
                   2143: sub generate_access_keys {
1.364     www      2144:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2145:     $cdom=
1.620     albertel 2146:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2147:     $cnum=
1.620     albertel 2148:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2149:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2150:     unless (($cdom) && ($cnum)) { return 0; }
                   2151:     if ($number>10000) { return 0; }
                   2152:     sleep(2); # make sure don't get same seed twice
                   2153:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2154:     my $total=0;
                   2155:     for (my $i=1;$i<=$number;$i++) {
                   2156:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2157:                   sprintf("%lx",int(100000*rand)).'-'.
                   2158:                   sprintf("%lx",int(100000*rand));
                   2159:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2160:        $newkey=~s/0/h/g; # and also 0 and O
                   2161:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2162:        if ($existing{$newkey}) {
                   2163:            $i--;
                   2164:        } else {
1.364     www      2165: 	  if (&put('accesskeys',
                   2166:               { $newkey => '# generated '.localtime().
1.620     albertel 2167:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2168:                            '; '.$logentry },
                   2169: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2170:               $total++;
                   2171: 	  }
                   2172:        }
                   2173:     }
1.620     albertel 2174:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2175:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2176:     return $total;
                   2177: }
                   2178: 
                   2179: # ------------------------------------------------------- Validate an accesskey
                   2180: 
                   2181: sub validate_access_key {
                   2182:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2183:     $cdom=
1.620     albertel 2184:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2185:     $cnum=
1.620     albertel 2186:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2187:     $udom=$env{'user.domain'} unless (defined($udom));
                   2188:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2189:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2190:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2191: }
                   2192: 
                   2193: # ------------------------------------- Find the section of student in a course
1.652     albertel 2194: sub devalidate_getsection_cache {
                   2195:     my ($udom,$unam,$courseid)=@_;
                   2196:     my $hashid="$udom:$unam:$courseid";
                   2197:     &devalidate_cache_new('getsection',$hashid);
                   2198: }
1.298     matthew  2199: 
1.815     albertel 2200: sub courseid_to_courseurl {
                   2201:     my ($courseid) = @_;
                   2202:     #already url style courseid
                   2203:     return $courseid if ($courseid =~ m{^/});
                   2204: 
                   2205:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2206: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2207: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2208: 	return "/$cdom/$cnum";
                   2209:     }
                   2210: 
                   2211:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2212:     if (exists($courseinfo{'num'})) {
                   2213: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2214:     }
                   2215: 
                   2216:     return undef;
                   2217: }
                   2218: 
1.298     matthew  2219: sub getsection {
                   2220:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2221:     my $cachetime=1800;
1.551     albertel 2222: 
                   2223:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2224:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2225:     if (defined($cached)) { return $result; }
                   2226: 
1.298     matthew  2227:     my %Pending; 
                   2228:     my %Expired;
                   2229:     #
                   2230:     # Each role can either have not started yet (pending), be active, 
                   2231:     #    or have expired.
                   2232:     #
                   2233:     # If there is an active role, we are done.
                   2234:     #
                   2235:     # If there is more than one role which has not started yet, 
                   2236:     #     choose the one which will start sooner
                   2237:     # If there is one role which has not started yet, return it.
                   2238:     #
                   2239:     # If there is more than one expired role, choose the one which ended last.
                   2240:     # If there is a role which has expired, return it.
                   2241:     #
1.815     albertel 2242:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2243:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2244:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2245:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2246:         my $section=$1;
                   2247:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2248:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2249:         my $now=time;
1.548     albertel 2250:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2251:             $Expired{$end}=$section;
                   2252:             next;
                   2253:         }
1.548     albertel 2254:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2255:             $Pending{$start}=$section;
                   2256:             next;
                   2257:         }
1.599     albertel 2258:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2259:     }
                   2260:     #
                   2261:     # Presumedly there will be few matching roles from the above
                   2262:     # loop and the sorting time will be negligible.
                   2263:     if (scalar(keys(%Pending))) {
                   2264:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2265:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2266:     } 
                   2267:     if (scalar(keys(%Expired))) {
                   2268:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2269:         my $time = pop(@sorted);
1.599     albertel 2270:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2271:     }
1.599     albertel 2272:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2273: }
1.70      www      2274: 
1.599     albertel 2275: sub save_cache {
                   2276:     &purge_remembered();
1.722     albertel 2277:     #&Apache::loncommon::validate_page();
1.620     albertel 2278:     undef(%env);
1.780     albertel 2279:     undef($env_loaded);
1.599     albertel 2280: }
1.452     albertel 2281: 
1.599     albertel 2282: my $to_remember=-1;
                   2283: my %remembered;
                   2284: my %accessed;
                   2285: my $kicks=0;
                   2286: my $hits=0;
1.849     albertel 2287: sub make_key {
                   2288:     my ($name,$id) = @_;
1.872     albertel 2289:     if (length($id) > 65 
                   2290: 	&& length(&escape($id)) > 200) {
                   2291: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2292:     }
1.849     albertel 2293:     return &escape($name.':'.$id);
                   2294: }
                   2295: 
1.599     albertel 2296: sub devalidate_cache_new {
                   2297:     my ($name,$id,$debug) = @_;
                   2298:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2299:     $id=&make_key($name,$id);
1.599     albertel 2300:     $memcache->delete($id);
                   2301:     delete($remembered{$id});
                   2302:     delete($accessed{$id});
                   2303: }
                   2304: 
                   2305: sub is_cached_new {
                   2306:     my ($name,$id,$debug) = @_;
1.849     albertel 2307:     $id=&make_key($name,$id);
1.599     albertel 2308:     if (exists($remembered{$id})) {
1.1133    foxr     2309: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2310: 	$accessed{$id}=[&gettimeofday()];
                   2311: 	$hits++;
                   2312: 	return ($remembered{$id},1);
                   2313:     }
                   2314:     my $value = $memcache->get($id);
                   2315:     if (!(defined($value))) {
                   2316: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2317: 	return (undef,undef);
1.416     albertel 2318:     }
1.599     albertel 2319:     if ($value eq '__undef__') {
                   2320: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2321: 	$value=undef;
                   2322:     }
                   2323:     &make_room($id,$value,$debug);
                   2324:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2325:     return ($value,1);
                   2326: }
                   2327: 
                   2328: sub do_cache_new {
                   2329:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2330:     $id=&make_key($name,$id);
1.599     albertel 2331:     my $setvalue=$value;
                   2332:     if (!defined($setvalue)) {
                   2333: 	$setvalue='__undef__';
                   2334:     }
1.623     albertel 2335:     if (!defined($time) ) {
                   2336: 	$time=600;
                   2337:     }
1.599     albertel 2338:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2339:     my $result = $memcache->set($id,$setvalue,$time);
                   2340:     if (! $result) {
1.872     albertel 2341: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2342: 	$memcache->disconnect_all();
1.872     albertel 2343:     }
1.600     albertel 2344:     # need to make a copy of $value
1.919     albertel 2345:     &make_room($id,$value,$debug);
1.599     albertel 2346:     return $value;
                   2347: }
                   2348: 
                   2349: sub make_room {
                   2350:     my ($id,$value,$debug)=@_;
1.919     albertel 2351: 
                   2352:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2353:                                     : $value;
1.599     albertel 2354:     if ($to_remember<0) { return; }
                   2355:     $accessed{$id}=[&gettimeofday()];
                   2356:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2357:     my $to_kick;
                   2358:     my $max_time=0;
                   2359:     foreach my $other (keys(%accessed)) {
                   2360: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2361: 	    $to_kick=$other;
                   2362: 	    $max_time=&tv_interval($accessed{$other});
                   2363: 	}
                   2364:     }
                   2365:     delete($remembered{$to_kick});
                   2366:     delete($accessed{$to_kick});
                   2367:     $kicks++;
                   2368:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2369:     return;
                   2370: }
                   2371: 
1.599     albertel 2372: sub purge_remembered {
1.604     albertel 2373:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2374:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2375:     undef(%remembered);
                   2376:     undef(%accessed);
1.428     albertel 2377: }
1.70      www      2378: # ------------------------------------- Read an entry from a user's environment
                   2379: 
                   2380: sub userenvironment {
                   2381:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2382:     my $items;
                   2383:     foreach my $item (@what) {
                   2384:         $items.=&escape($item).'&';
                   2385:     }
                   2386:     $items=~s/\&$//;
1.70      www      2387:     my %returnhash=();
1.1009    raeburn  2388:     my $uhome = &homeserver($unam,$udom);
                   2389:     unless ($uhome eq 'no_host') {
                   2390:         my @answer=split(/\&/, 
                   2391:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2392:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2393:             return %returnhash;
                   2394:         }
1.1009    raeburn  2395:         my $i;
                   2396:         for ($i=0;$i<=$#what;$i++) {
                   2397: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2398:         }
1.70      www      2399:     }
                   2400:     return %returnhash;
1.1       albertel 2401: }
                   2402: 
1.617     albertel 2403: # ---------------------------------------------------------- Get a studentphoto
                   2404: sub studentphoto {
                   2405:     my ($udom,$unam,$ext) = @_;
                   2406:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2407:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2408:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2409:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2410:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2411:             } else {
                   2412:                 my ($result,$perm_reqd)=
1.707     albertel 2413: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2414:                 if ($result eq 'ok') {
                   2415:                     if (!($perm_reqd eq 'yes')) {
                   2416:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2417:                     }
                   2418:                 }
                   2419:             }
                   2420:         }
                   2421:     } else {
                   2422:         my ($result,$perm_reqd) = 
1.707     albertel 2423: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2424:         if ($result eq 'ok') {
                   2425:             if (!($perm_reqd eq 'yes')) {
                   2426:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2427:             }
                   2428:         }
                   2429:     }
                   2430:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2431: }
                   2432: 
                   2433: sub retrievestudentphoto {
                   2434:     my ($udom,$unam,$ext,$type) = @_;
                   2435:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2436:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2437:     if ($ret eq 'ok') {
                   2438:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2439:         if ($type eq 'thumbnail') {
                   2440:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2441:         }
                   2442:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2443:         return $tokenurl;
                   2444:     } else {
                   2445:         if ($type eq 'thumbnail') {
                   2446:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2447:         } else { 
                   2448:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2449:         }
1.617     albertel 2450:     }
                   2451: }
                   2452: 
1.263     www      2453: # -------------------------------------------------------------------- New chat
                   2454: 
                   2455: sub chatsend {
1.724     raeburn  2456:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2457:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2458:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2459:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2460:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2461: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2462: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2463: }
                   2464: 
                   2465: # ------------------------------------------ Find current version of a resource
                   2466: 
                   2467: sub getversion {
                   2468:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2469:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2470:     return &currentversion(&filelocation('',$fname));
                   2471: }
                   2472: 
                   2473: sub currentversion {
                   2474:     my $fname=shift;
                   2475:     my $author=$fname;
                   2476:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2477:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2478:     my $home=&homeserver($uname,$udom);
1.292     www      2479:     if ($home eq 'no_host') { 
                   2480:         return -1; 
                   2481:     }
1.1112    www      2482:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2483:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2484: 	return -1;
                   2485:     }
1.1112    www      2486:     return $answer;
1.263     www      2487: }
                   2488: 
1.1111    www      2489: #
                   2490: # Return special version number of resource if set by override, empty otherwise
                   2491: #
                   2492: sub usedversion {
                   2493:     my $fname=shift;
                   2494:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2495:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2496:     if ($urlversion) { return $urlversion; }
                   2497:     return '';
                   2498: }
                   2499: 
1.1       albertel 2500: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2501: 
1.1       albertel 2502: sub subscribe {
                   2503:     my $fname=shift;
1.761     raeburn  2504:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2505:     $fname=~s/[\n\r]//g;
1.1       albertel 2506:     my $author=$fname;
                   2507:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2508:     my ($udom,$uname)=split(/\//,$author);
                   2509:     my $home=homeserver($uname,$udom);
1.335     albertel 2510:     if ($home eq 'no_host') {
                   2511:         return 'not_found';
1.1       albertel 2512:     }
                   2513:     my $answer=reply("sub:$fname",$home);
1.64      www      2514:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2515: 	$answer.=' by '.$home;
                   2516:     }
1.1       albertel 2517:     return $answer;
                   2518: }
                   2519:     
1.8       www      2520: # -------------------------------------------------------------- Replicate file
                   2521: 
                   2522: sub repcopy {
                   2523:     my $filename=shift;
1.23      www      2524:     $filename=~s/\/+/\//g;
1.1142    raeburn  2525:     my $londocroot = $perlvar{'lonDocRoot'};
                   2526:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2527:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2528:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2529: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2530: 	return &repcopy_userfile($filename);
                   2531:     }
1.532     albertel 2532:     $filename=~s/[\n\r]//g;
1.8       www      2533:     my $transname="$filename.in.transfer";
1.828     www      2534: # FIXME: this should flock
1.607     raeburn  2535:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2536:     my $remoteurl=subscribe($filename);
1.64      www      2537:     if ($remoteurl =~ /^con_lost by/) {
                   2538: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2539:            return 'unavailable';
1.8       www      2540:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2541: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2542: 	   return 'not_found';
1.64      www      2543:     } elsif ($remoteurl =~ /^rejected by/) {
                   2544: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2545:            return 'forbidden';
1.20      www      2546:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2547:            return 'ok';
1.8       www      2548:     } else {
1.290     www      2549:         my $author=$filename;
                   2550:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2551:         my ($udom,$uname)=split(/\//,$author);
                   2552:         my $home=homeserver($uname,$udom);
                   2553:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2554:            my @parts=split(/\//,$filename);
                   2555:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2556:            if ($path ne "$londocroot/res") {
1.8       www      2557:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2558: 	       return 'bad_request';
1.8       www      2559:            }
                   2560:            my $count;
                   2561:            for ($count=5;$count<$#parts;$count++) {
                   2562:                $path.="/$parts[$count]";
                   2563:                if ((-e $path)!=1) {
                   2564: 		   mkdir($path,0777);
                   2565:                }
                   2566:            }
                   2567:            my $ua=new LWP::UserAgent;
                   2568:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2569:            my $response=$ua->request($request,$transname);
                   2570:            if ($response->is_error()) {
                   2571: 	       unlink($transname);
                   2572:                my $message=$response->status_line;
1.672     albertel 2573:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2574:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2575:                return 'unavailable';
1.8       www      2576:            } else {
1.16      www      2577: 	       if ($remoteurl!~/\.meta$/) {
                   2578:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2579:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2580:                   if ($mresponse->is_error()) {
                   2581: 		      unlink($filename.'.meta');
                   2582:                       &logthis(
1.672     albertel 2583:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2584:                   }
                   2585: 	       }
1.8       www      2586:                rename($transname,$filename);
1.607     raeburn  2587:                return 'ok';
1.8       www      2588:            }
1.290     www      2589:        }
1.8       www      2590:     }
1.330     www      2591: }
                   2592: 
                   2593: # ------------------------------------------------ Get server side include body
                   2594: sub ssi_body {
1.381     albertel 2595:     my ($filelink,%form)=@_;
1.606     matthew  2596:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2597:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2598:     }
1.953     www      2599:     my $output='';
                   2600:     my $response;
1.980     raeburn  2601:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2602:        ($output,$response)=&externalssi($filelink);
1.953     www      2603:     } else {
1.1004    droeschl 2604:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2605:        $filelink .= 'inhibitmenu=yes';
1.953     www      2606:        ($output,$response)=&ssi($filelink,%form);
                   2607:     }
1.778     albertel 2608:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2609:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2610:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2611:     if (wantarray) {
                   2612:         return ($output, $response);
                   2613:     } else {
                   2614:         return $output;
                   2615:     }
1.8       www      2616: }
                   2617: 
1.15      www      2618: # --------------------------------------------------------- Server Side Include
                   2619: 
1.782     albertel 2620: sub absolute_url {
                   2621:     my ($host_name) = @_;
                   2622:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2623:     if ($host_name eq '') {
                   2624: 	$host_name = $ENV{'SERVER_NAME'};
                   2625:     }
                   2626:     return $protocol.$host_name;
                   2627: }
                   2628: 
1.942     foxr     2629: #
                   2630: #   Server side include.
                   2631: # Parameters:
                   2632: #  fn     Possibly encrypted resource name/id.
                   2633: #  form   Hash that describes how the rendering should be done
                   2634: #         and other things.
1.944     foxr     2635: # Returns:
1.950     raeburn  2636: #   Scalar context: The content of the response.
                   2637: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2638: #     
1.15      www      2639: sub ssi {
                   2640: 
1.944     foxr     2641:     my ($fn,%form)=@_;
1.15      www      2642:     my $ua=new LWP::UserAgent;
1.23      www      2643:     my $request;
1.711     albertel 2644: 
                   2645:     $form{'no_update_last_known'}=1;
1.895     albertel 2646:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2647:     if (%form) {
1.782     albertel 2648:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2649:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2650:     } else {
1.782     albertel 2651:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2652:     }
                   2653: 
1.15      www      2654:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2  raeburn  2655:     my $response= $ua->request($request);
1.944     foxr     2656:     if (wantarray) {
1.1172.2.3  raeburn  2657: 	return ($response->content, $response);
1.944     foxr     2658:     } else {
1.1172.2.3  raeburn  2659: 	return $response->content;
1.942     foxr     2660:     }
1.324     www      2661: }
                   2662: 
                   2663: sub externalssi {
                   2664:     my ($url)=@_;
                   2665:     my $ua=new LWP::UserAgent;
                   2666:     my $request=new HTTP::Request('GET',$url);
                   2667:     my $response=$ua->request($request);
1.954     raeburn  2668:     if (wantarray) {
                   2669:         return ($response->content, $response);
                   2670:     } else {
                   2671:         return $response->content;
                   2672:     }
1.15      www      2673: }
1.254     www      2674: 
1.492     albertel 2675: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2676: 
                   2677: sub allowuploaded {
                   2678:     my ($srcurl,$url)=@_;
                   2679:     $url=&clutter(&declutter($url));
                   2680:     my $dir=$url;
                   2681:     $dir=~s/\/[^\/]+$//;
                   2682:     my %httpref=();
                   2683:     my $httpurl=&hreflocation('',$url);
                   2684:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2685:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2686: }
1.477     raeburn  2687: 
1.1172.2.13  raeburn  2688: #
                   2689: # Determine if the current user should be able to edit a particular resource,
                   2690: # when viewing in course context.
                   2691: # (a) When viewing resource used to determine if "Edit" item is included in
                   2692: #     Functions.
                   2693: # (b) When displaying folder contents in course editor, used to determine if
                   2694: #     "Edit" link will be displayed alongside resource.
                   2695: #
                   2696: #  input: six args -- filename (decluttered), course number, course domain,
                   2697: #                   url, symb (if registered) and group (if this is a group
                   2698: #                   item -- e.g., bulletin board, group page etc.).
                   2699: #  output: array of five scalars --
                   2700: #          $cfile -- url for file editing if editable on current server
                   2701: #          $home -- homeserver of resource (i.e., for author if published,
                   2702: #                                           or course if uploaded.).
                   2703: #          $switchserver --  1 if server switch will be needed.
                   2704: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   2705: #          $forceview -- 1 if icon/link should be to go to view mode
                   2706: #
                   2707: 
                   2708: sub can_edit_resource {
                   2709:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   2710:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   2711: #
                   2712: # For aboutme pages user can only edit his/her own.
                   2713: #
                   2714:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   2715:         my ($sdom,$sname) = ($1,$2);
                   2716:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   2717:             $home = $env{'user.home'};
                   2718:             $cfile = $resurl;
                   2719:             if ($env{'form.forceedit'}) {
                   2720:                 $forceview = 1;
                   2721:             } else {
                   2722:                 $forceedit = 1;
                   2723:             }
                   2724:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2725:         } else {
                   2726:             return;
                   2727:         }
                   2728:     }
                   2729: 
                   2730:     if ($env{'request.course.id'}) {
                   2731:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   2732:         if ($group ne '') {
                   2733: # if this is a group homepage or group bulletin board, check group privs
                   2734:             my $allowed = 0;
                   2735:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   2736:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   2737:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2738:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2739:                     $allowed = 1;
                   2740:                 }
                   2741:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   2742:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2743:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2744:                     $allowed = 1;
                   2745:                 }
                   2746:             }
                   2747:             if ($allowed) {
                   2748:                 $home=&homeserver($cnum,$cdom);
                   2749:                 if ($env{'form.forceedit'}) {
                   2750:                     $forceview = 1;
                   2751:                 } else {
                   2752:                     $forceedit = 1;
                   2753:                 }
                   2754:                 $cfile = $resurl;
                   2755:             } else {
                   2756:                 return;
                   2757:             }
                   2758:         } else {
1.1172.2.15  raeburn  2759:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2760:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   2761:                     return;
                   2762:                 }
                   2763:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  2764: #
                   2765: # No edit allowed where CC has switched to student role.
                   2766: #
                   2767:                 return;
                   2768:             }
                   2769:         }
                   2770:     }
                   2771: 
                   2772:     if ($file ne '') {
                   2773:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   2774:             if (&is_course_upload($file,$cnum,$cdom)) {
                   2775:                 $uploaded = 1;
                   2776:                 $incourse = 1;
                   2777:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   2778:                     $cfile = &hreflocation('',$file);
                   2779:                     if ($env{'form.forceedit'}) {
                   2780:                         $forceview = 1;
                   2781:                     } else {
                   2782:                         $forceedit = 1;
                   2783:                     }
                   2784:                 }
                   2785:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   2786:                 $incourse = 1;
                   2787:                 if ($env{'form.forceedit'}) {
                   2788:                     $forceview = 1;
                   2789:                 } else {
                   2790:                     $forceedit = 1;
                   2791:                 }
                   2792:                 $cfile = $resurl;
                   2793:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   2794:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   2795:                     $incourse = 1;
                   2796:                     if ($env{'form.forceedit'}) {
                   2797:                         $forceview = 1;
                   2798:                     } else {
                   2799:                         $forceedit = 1;
                   2800:                     }
                   2801:                     $cfile = $resurl;
                   2802:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   2803:                     $incourse = 1;
                   2804:                     $cfile = $resurl.'/smpedit';
                   2805:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   2806:                     $incourse = 1;
                   2807:                     if ($env{'form.forceedit'}) {
                   2808:                         $forceview = 1;
                   2809:                     } else {
                   2810:                         $forceedit = 1;
                   2811:                     }
                   2812:                     $cfile = $resurl;
1.1172.2.15  raeburn  2813:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2814:                     $incourse = 1;
                   2815:                     if ($env{'form.forceedit'}) {
                   2816:                         $forceview = 1;
                   2817:                     } else {
                   2818:                         $forceedit = 1;
                   2819:                     }
                   2820:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  2821:                 }
                   2822:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   2823:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   2824:                 if (&is_on_map($template)) {
                   2825:                     $incourse = 1;
                   2826:                     $forceview = 1;
                   2827:                     $cfile = $template;
                   2828:                 }
                   2829:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   2830:                     $incourse = 1;
                   2831:                     if ($env{'form.forceedit'}) {
                   2832:                         $forceview = 1;
                   2833:                     } else {
                   2834:                         $forceedit = 1;
                   2835:                     }
                   2836:                     $cfile = $resurl;
                   2837:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   2838:                 $incourse = 1;
                   2839:                 $forceview = 1;
                   2840:                 if ($symb) {
                   2841:                     my ($map,$id,$res)=&decode_symb($symb);
                   2842:                     $env{'request.symb'} = $symb;
                   2843:                     $cfile = &clutter($res);
                   2844:                 } else {
                   2845:                     $cfile = $env{'form.suppurl'};
                   2846:                     $cfile =~ s{^http://}{};
                   2847:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   2848:                 }
1.1172.2.31  raeburn  2849:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2850:                 if ($env{'form.forceedit'}) {
                   2851:                     $forceview = 1;
                   2852:                 } else {
                   2853:                     $forceedit = 1;
                   2854:                 }
                   2855:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  2856:             }
                   2857:         }
                   2858:         if ($uploaded || $incourse) {
                   2859:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  2860:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  2861:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   2862:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   2863:             # Check that the user has permission to edit this resource
                   2864:             my $setpriv = 1;
                   2865:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   2866:             if (defined($cfudom)) {
                   2867:                 $home=&homeserver($cfuname,$cfudom);
                   2868:                 $cfile=$file;
                   2869:             }
                   2870:         }
                   2871:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   2872:             (($home ne '') && ($home ne 'no_host'))) {
                   2873:             my @ids=&current_machine_ids();
                   2874:             unless (grep(/^\Q$home\E$/,@ids)) {
                   2875:                 $switchserver=1;
                   2876:             }
                   2877:         }
                   2878:     }
                   2879:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2880: }
                   2881: 
                   2882: sub is_course_upload {
                   2883:     my ($file,$cnum,$cdom) = @_;
                   2884:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   2885:     $uploadpath =~ s{^\/}{};
                   2886:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   2887:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   2888:         return 1;
                   2889:     }
                   2890:     return;
                   2891: }
                   2892: 
                   2893: sub in_course {
                   2894:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   2895:     if ($hideprivileged) {
                   2896:         my $skipuser;
1.1172.2.23  raeburn  2897:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   2898:         my @possdoms = ($cdom);
                   2899:         if ($coursehash{'checkforpriv'}) {
                   2900:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   2901:         }
                   2902:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  2903:             $skipuser = 1;
                   2904:             if ($coursehash{'nothideprivileged'}) {
                   2905:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2906:                     my $user;
                   2907:                     if ($item =~ /:/) {
                   2908:                         $user = $item;
                   2909:                     } else {
                   2910:                         $user = join(':',split(/[\@]/,$item));
                   2911:                     }
                   2912:                     if ($user eq $uname.':'.$udom) {
                   2913:                         undef($skipuser);
                   2914:                         last;
                   2915:                     }
                   2916:                 }
                   2917:             }
                   2918:             if ($skipuser) {
                   2919:                 return 0;
                   2920:             }
                   2921:         }
                   2922:     }
                   2923:     $type ||= 'any';
                   2924:     if (!defined($cdom) || !defined($cnum)) {
                   2925:         my $cid  = $env{'request.course.id'};
                   2926:         $cdom = $env{'course.'.$cid.'.domain'};
                   2927:         $cnum = $env{'course.'.$cid.'.num'};
                   2928:     }
                   2929:     my $typesref;
                   2930:     if (($type eq 'any') || ($type eq 'all')) {
                   2931:         $typesref = ['active','previous','future'];
                   2932:     } elsif ($type eq 'previous' || $type eq 'future') {
                   2933:         $typesref = [$type];
                   2934:     }
                   2935:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   2936:                               $typesref,undef,[$cdom]);
                   2937:     my ($tmp) = keys(%roles);
                   2938:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   2939:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   2940:     if (@course_roles > 0) {
                   2941:         return 1;
                   2942:     }
                   2943:     return 0;
                   2944: }
                   2945: 
1.478     albertel 2946: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2947: # input: action, courseID, current domain, intended
1.637     raeburn  2948: #        path to file, source of file, instruction to parse file for objects,
                   2949: #        ref to hash for embedded objects,
                   2950: #        ref to hash for codebase of java objects.
1.1095    raeburn  2951: #        reference to scalar to accommodate mime type determined
                   2952: #          from File::MMagic if $parser = parse.
1.637     raeburn  2953: #
1.485     raeburn  2954: # output: url to file (if action was uploaddoc), 
                   2955: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2956: #
1.478     albertel 2957: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2958: # course.
1.477     raeburn  2959: #
1.478     albertel 2960: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2961: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2962: #          course's home server.
1.477     raeburn  2963: #
1.478     albertel 2964: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2965: #          be copied from $source (current location) to 
                   2966: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2967: #         and will then be copied to
                   2968: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2969: #         course's home server.
1.485     raeburn  2970: #
1.481     raeburn  2971: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2972: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2973: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2974: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2975: #         in course's home server.
1.637     raeburn  2976: #
1.477     raeburn  2977: 
                   2978: sub process_coursefile {
1.1095    raeburn  2979:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2980:         $mimetype)=@_;
1.477     raeburn  2981:     my $fetchresult;
1.638     albertel 2982:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2983:     if ($action eq 'propagate') {
1.638     albertel 2984:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2985: 			     $home);
1.481     raeburn  2986:     } else {
1.477     raeburn  2987:         my $fpath = '';
                   2988:         my $fname = $file;
1.478     albertel 2989:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2990:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2991:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2992:         if ($action eq 'copy') {
                   2993:             if ($source eq '') {
                   2994:                 $fetchresult = 'no source file';
                   2995:                 return $fetchresult;
                   2996:             } else {
                   2997:                 my $destination = $filepath.'/'.$fname;
                   2998:                 rename($source,$destination);
                   2999:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3000:                                  $home);
1.481     raeburn  3001:             }
                   3002:         } elsif ($action eq 'uploaddoc') {
                   3003:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 3004:             print $fh $env{'form.'.$source};
1.481     raeburn  3005:             close($fh);
1.637     raeburn  3006:             if ($parser eq 'parse') {
1.1024    raeburn  3007:                 my $mm = new File::MMagic;
1.1095    raeburn  3008:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3009:                 if ($type eq 'text/html') {
1.1024    raeburn  3010:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3011:                     unless ($parse_result eq 'ok') {
                   3012:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3013:                     }
1.637     raeburn  3014:                 }
1.1095    raeburn  3015:                 if (ref($mimetype)) {
                   3016:                     $$mimetype = $type;
                   3017:                 } 
1.637     raeburn  3018:             }
1.477     raeburn  3019:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3020:                                  $home);
1.481     raeburn  3021:             if ($fetchresult eq 'ok') {
                   3022:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3023:             } else {
                   3024:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3025:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3026:                 return '/adm/notfound.html';
                   3027:             }
1.477     raeburn  3028:         }
                   3029:     }
1.485     raeburn  3030:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3031:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3032:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3033:     }
                   3034:     return $fetchresult;
                   3035: }
                   3036: 
1.637     raeburn  3037: sub build_filepath {
                   3038:     my ($fpath) = @_;
                   3039:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3040:     unless ($fpath eq '') {
                   3041:         my @parts=split('/',$fpath);
                   3042:         foreach my $part (@parts) {
                   3043:             $filepath.= '/'.$part;
                   3044:             if ((-e $filepath)!=1) {
                   3045:                 mkdir($filepath,0777);
                   3046:             }
                   3047:         }
                   3048:     }
                   3049:     return $filepath;
                   3050: }
                   3051: 
                   3052: sub store_edited_file {
1.638     albertel 3053:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3054:     my $file = $primary_url;
                   3055:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3056:     my $fpath = '';
                   3057:     my $fname = $file;
                   3058:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3059:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3060:     my $filepath = &build_filepath($fpath);
                   3061:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3062:     print $fh $content;
                   3063:     close($fh);
1.638     albertel 3064:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3065:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3066: 			  $home);
1.637     raeburn  3067:     if ($$fetchresult eq 'ok') {
                   3068:         return '/uploaded/'.$fpath.'/'.$fname;
                   3069:     } else {
1.638     albertel 3070:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3071: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3072:         return '/adm/notfound.html';
                   3073:     }
                   3074: }
                   3075: 
1.531     albertel 3076: sub clean_filename {
1.831     albertel 3077:     my ($fname,$args)=@_;
1.315     www      3078: # Replace Windows backslashes by forward slashes
1.257     www      3079:     $fname=~s/\\/\//g;
1.831     albertel 3080:     if (!$args->{'keep_path'}) {
                   3081:         # Get rid of everything but the actual filename
                   3082: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3083:     }
1.315     www      3084: # Replace spaces by underscores
                   3085:     $fname=~s/\s+/\_/g;
                   3086: # Replace all other weird characters by nothing
1.831     albertel 3087:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3088: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3089: # numbers
                   3090:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3091:     return $fname;
                   3092: }
1.1051    raeburn  3093: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3094: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3095: # image with the same aspect ratio as the original, but with dimensions which do 
                   3096: # not exceed $resizewidth and $resizeheight.
                   3097:  
1.984     neumanie 3098: sub resizeImage {
1.1051    raeburn  3099:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3100:     my $ima = Image::Magick->new;
                   3101:     my $resized;
                   3102:     if (-e $img_path) {
                   3103:         $ima->Read($img_path);
                   3104:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3105:             my $width = $ima->Get('width');
                   3106:             my $height = $ima->Get('height');
                   3107:             if ($width > $resizewidth) {
                   3108: 	        my $factor = $width/$resizewidth;
                   3109:                 my $newheight = $height/$factor;
                   3110:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3111:                 $resized = 1;
                   3112:             }
                   3113:         }
                   3114:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3115:             my $width = $ima->Get('width');
                   3116:             my $height = $ima->Get('height');
                   3117:             if ($height > $resizeheight) {
                   3118:                 my $factor = $height/$resizeheight;
                   3119:                 my $newwidth = $width/$factor;
                   3120:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3121:                 $resized = 1;
                   3122:             }
                   3123:         }
                   3124:         if ($resized) {
                   3125:             $ima->Write($img_path);
                   3126:         }
                   3127:     }
                   3128:     return;
1.977     amueller 3129: }
                   3130: 
1.608     albertel 3131: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3132: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3133: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3134: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3135: #                                    canceloverwrite, or ''. 
                   3136: #                   if 'coursedoc': upload to the current course
                   3137: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3138: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3139: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3140: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3141: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3142: #        $allfiles - reference to hash for embedded objects
                   3143: #        $codebase - reference to hash for codebase of java objects
                   3144: #        $desuname - username for permanent storage of uploaded file
                   3145: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3146: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3147: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3148: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3149: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3150: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3151: #                    from File::MMagic.
1.858     raeburn  3152: # 
1.686     albertel 3153: # output: url of file in userspace, or error: <message> 
                   3154: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3155: 
1.531     albertel 3156: sub userfileupload {
1.1090    raeburn  3157:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3158:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3159:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3160:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3161:     $fname=&clean_filename($fname);
1.1090    raeburn  3162:     # See if there is anything left
1.257     www      3163:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3164:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3165:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3166:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3167:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3168:         my $now = time;
1.1090    raeburn  3169:         my $filepath;
1.1095    raeburn  3170:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3171:              $filepath = 'tmp/helprequests/'.$now;
                   3172:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3173:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3174:                          '_'.$env{'user.domain'}.'/pending';
                   3175:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3176:             my ($docuname,$docudom);
                   3177:             if ($destudom) {
                   3178:                 $docudom = $destudom;
                   3179:             } else {
                   3180:                 $docudom = $env{'user.domain'};
                   3181:             }
                   3182:             if ($destuname) {
                   3183:                 $docuname = $destuname;
                   3184:             } else {
                   3185:                 $docuname = $env{'user.name'};
                   3186:             }
                   3187:             if (exists($env{'form.group'})) {
                   3188:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3189:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3190:             }
                   3191:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3192:             if ($context eq 'canceloverwrite') {
                   3193:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3194:                 if (-e  $tempfile) {
                   3195:                     my @info = stat($tempfile);
                   3196:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3197:                         unlink($tempfile);
                   3198:                     }
                   3199:                 }
                   3200:                 return;
1.523     raeburn  3201:             }
                   3202:         }
1.1090    raeburn  3203:         # Create the directory if not present
1.741     raeburn  3204:         my @parts=split(/\//,$filepath);
                   3205:         my $fullpath = $perlvar{'lonDaemons'};
                   3206:         for (my $i=0;$i<@parts;$i++) {
                   3207:             $fullpath .= '/'.$parts[$i];
                   3208:             if ((-e $fullpath)!=1) {
                   3209:                 mkdir($fullpath,0777);
                   3210:             }
                   3211:         }
                   3212:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3213:         print $fh $env{'form.'.$formname};
                   3214:         close($fh);
1.1090    raeburn  3215:         if ($context eq 'existingfile') {
                   3216:             my @info = stat($fullpath.'/'.$fname);
                   3217:             return ($fullpath.'/'.$fname,$info[9]);
                   3218:         } else {
                   3219:             return $fullpath.'/'.$fname;
                   3220:         }
1.523     raeburn  3221:     }
1.995     raeburn  3222:     if ($subdir eq 'scantron') {
                   3223:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3224:     } else {
1.995     raeburn  3225:         $fname="$subdir/$fname";
                   3226:     }
1.1090    raeburn  3227:     if ($context eq 'coursedoc') {
1.638     albertel 3228: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3229: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3230:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3231:             return &finishuserfileupload($docuname,$docudom,
                   3232: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3233: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3234:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3235:         } else {
1.1172.2.21  raeburn  3236:             if ($env{'form.folder'}) {
                   3237:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3238:             }
1.638     albertel 3239:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3240: 				       $fname,$formname,$parser,
1.1095    raeburn  3241: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3242:         }
1.719     banghart 3243:     } elsif (defined($destuname)) {
                   3244:         my $docuname=$destuname;
                   3245:         my $docudom=$destudom;
1.860     raeburn  3246: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3247: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3248:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3249:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3250:     } else {
1.638     albertel 3251:         my $docuname=$env{'user.name'};
                   3252:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3253:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3254:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3255:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3256:         }
1.860     raeburn  3257: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3258: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3259:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3260:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3261:     }
1.271     www      3262: }
                   3263: 
                   3264: sub finishuserfileupload {
1.860     raeburn  3265:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3266:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3267:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3268:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3269:   
1.860     raeburn  3270:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3271:     $file=$fname;
                   3272:     if ($fname=~m|/|) {
                   3273:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3274: 	$path.=$fnamepath.'/';
                   3275:     }
1.259     www      3276:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3277:     my $count;
                   3278:     for ($count=4;$count<=$#parts;$count++) {
                   3279:         $filepath.="/$parts[$count]";
                   3280:         if ((-e $filepath)!=1) {
                   3281: 	    mkdir($filepath,0777);
                   3282:         }
                   3283:     }
1.984     neumanie 3284: 
1.258     www      3285: # Save the file
                   3286:     {
1.701     albertel 3287: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3288: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3289: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3290: 	    return '/adm/notfound.html';
                   3291: 	}
1.1090    raeburn  3292:         if ($context eq 'overwrite') {
1.1117    foxr     3293:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3294:             my $target = $filepath.'/'.$file;
                   3295:             if (-e $source) {
                   3296:                 my @info = stat($source);
                   3297:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3298:                     unless (&File::Copy::move($source,$target)) {
                   3299:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3300:                         return "Moving from $source failed";
                   3301:                     }
                   3302:                 } else {
                   3303:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3304:                 }
                   3305:             } else {
                   3306:                 return "Temporary file: $source missing";
                   3307:             }
                   3308:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3309: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3310: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3311: 	    return '/adm/notfound.html';
                   3312: 	}
1.570     albertel 3313: 	close(FH);
1.1051    raeburn  3314:         if ($resizewidth && $resizeheight) {
                   3315:             my $mm = new File::MMagic;
                   3316:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3317:             if ($mime_type =~ m{^image/}) {
                   3318: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3319:             }  
1.977     amueller 3320: 	}
1.258     www      3321:     }
1.1152    raeburn  3322:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3323:         if (ref($mimetype)) {
                   3324:             if ($$mimetype eq '') {
                   3325:                 my $mm = new File::MMagic;
                   3326:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3327:                 $$mimetype = $type;
                   3328:             }
                   3329:         }
                   3330:     }
1.637     raeburn  3331:     if ($parser eq 'parse') {
1.1152    raeburn  3332:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3333:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3334:                                                        $allfiles,$codebase);
                   3335:             unless ($parse_result eq 'ok') {
                   3336:                 &logthis('Failed to parse '.$filepath.$file.
                   3337: 	   	         ' for embedded media: '.$parse_result); 
                   3338:             }
1.637     raeburn  3339:         }
                   3340:     }
1.860     raeburn  3341:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3342:         my $input = $filepath.'/'.$file;
                   3343:         my $output = $filepath.'/'.'tn-'.$file;
                   3344:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3345:         system("convert -sample $thumbsize $input $output");
                   3346:         if (-e $filepath.'/'.'tn-'.$file) {
                   3347:             $fetchthumb  = 1; 
                   3348:         }
                   3349:     }
1.858     raeburn  3350:  
1.259     www      3351: # Notify homeserver to grep it
                   3352: #
1.984     neumanie 3353:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3354:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3355:     if ($fetchresult eq 'ok') {
1.860     raeburn  3356:         if ($fetchthumb) {
                   3357:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3358:             if ($thumbresult ne 'ok') {
                   3359:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3360:                          $docuhome.': '.$thumbresult);
                   3361:             }
                   3362:         }
1.259     www      3363: #
1.258     www      3364: # Return the URL to it
1.494     albertel 3365:         return '/uploaded/'.$path.$file;
1.263     www      3366:     } else {
1.494     albertel 3367:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3368: 		 ': '.$fetchresult);
1.263     www      3369:         return '/adm/notfound.html';
1.858     raeburn  3370:     }
1.493     albertel 3371: }
                   3372: 
1.637     raeburn  3373: sub extract_embedded_items {
1.961     raeburn  3374:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3375:     my @state = ();
1.1164    raeburn  3376:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3377:     my %javafiles = (
                   3378:                       codebase => '',
                   3379:                       code => '',
                   3380:                       archive => ''
                   3381:                     );
                   3382:     my %mediafiles = (
                   3383:                       src => '',
                   3384:                       movie => '',
                   3385:                      );
1.648     raeburn  3386:     my $p;
                   3387:     if ($content) {
                   3388:         $p = HTML::LCParser->new($content);
                   3389:     } else {
1.961     raeburn  3390:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3391:     }
1.641     albertel 3392:     while (my $t=$p->get_token()) {
1.640     albertel 3393: 	if ($t->[0] eq 'S') {
                   3394: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3395: 	    push(@state, $tagname);
1.648     raeburn  3396:             if (lc($tagname) eq 'allow') {
                   3397:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3398:             }
1.640     albertel 3399: 	    if (lc($tagname) eq 'img') {
                   3400: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3401: 	    }
1.886     albertel 3402: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  3403:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   3404: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   3405:                 }
1.886     albertel 3406: 	    }
1.645     raeburn  3407:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3408:                 my $src;
1.645     raeburn  3409:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3410:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3411:                 } else {
1.1164    raeburn  3412:                     if ($attr->{'src'} ne '') {
                   3413:                         $src = $attr->{'src'};
                   3414:                         &add_filetype($allfiles,$src,'src');
                   3415:                     }
                   3416:                 }
                   3417:                 my $text = $p->get_trimmed_text();
                   3418:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3419:                     my @swfargs = split(/,/,$1);
                   3420:                     foreach my $item (@swfargs) {
                   3421:                         $item =~ s/["']//g;
                   3422:                         $item =~ s/^\s+//;
                   3423:                         $item =~ s/\s+$//;
                   3424:                     }
                   3425:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3426:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3427:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3428:                         } else {
                   3429:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3430:                         }
                   3431:                     }
1.645     raeburn  3432:                 }
                   3433:             }
                   3434:             if (lc($tagname) eq 'link') {
                   3435:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3436:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3437:                 }
                   3438:             }
1.640     albertel 3439: 	    if (lc($tagname) eq 'object' ||
                   3440: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3441: 		foreach my $item (keys(%javafiles)) {
                   3442: 		    $javafiles{$item} = '';
                   3443: 		}
1.1164    raeburn  3444:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3445:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3446:                 }
1.640     albertel 3447: 	    }
                   3448: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3449: 		my $name = lc($attr->{'name'});
                   3450: 		foreach my $item (keys(%javafiles)) {
                   3451: 		    if ($name eq $item) {
                   3452: 			$javafiles{$item} = $attr->{'value'};
                   3453: 			last;
                   3454: 		    }
                   3455: 		}
1.1164    raeburn  3456:                 my $pathfrom;
1.640     albertel 3457: 		foreach my $item (keys(%mediafiles)) {
                   3458: 		    if ($name eq $item) {
1.1164    raeburn  3459:                         $pathfrom = $attr->{'value'};
                   3460:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3461: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3462: 			last;
                   3463: 		    }
                   3464: 		}
1.1164    raeburn  3465:                 if ($name eq 'flashvars') {
                   3466:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3467:                 }
                   3468:                 if ($pathfrom ne '') {
                   3469:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3470:                                          $pathfrom);
                   3471:                 }
1.640     albertel 3472: 	    }
                   3473: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3474: 		foreach my $item (keys(%javafiles)) {
                   3475: 		    if ($attr->{$item}) {
                   3476: 			$javafiles{$item} = $attr->{$item};
                   3477: 			last;
                   3478: 		    }
                   3479: 		}
                   3480: 		foreach my $item (keys(%mediafiles)) {
                   3481: 		    if ($attr->{$item}) {
                   3482: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3483: 			last;
                   3484: 		    }
                   3485: 		}
1.1164    raeburn  3486:                 if (lc($tagname) eq 'embed') {
                   3487:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3488:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3489:                                              $attr->{'src'});
                   3490:                     }
                   3491:                 }
1.640     albertel 3492: 	    }
1.1164    raeburn  3493:             if ($t->[4] =~ m{/>$}) {
                   3494:                 pop(@state);  
                   3495:             }
1.640     albertel 3496: 	} elsif ($t->[0] eq 'E') {
                   3497: 	    my ($tagname) = ($t->[1]);
                   3498: 	    if ($javafiles{'codebase'} ne '') {
                   3499: 		$javafiles{'codebase'} .= '/';
                   3500: 	    }  
                   3501: 	    if (lc($tagname) eq 'applet' ||
                   3502: 		lc($tagname) eq 'object' ||
                   3503: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3504: 		) {
                   3505: 		foreach my $item (keys(%javafiles)) {
                   3506: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3507: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3508: 			&add_filetype($allfiles,$file,$item);
                   3509: 		    }
                   3510: 		}
                   3511: 	    } 
                   3512: 	    pop @state;
                   3513: 	}
                   3514:     }
1.1164    raeburn  3515:     foreach my $id (sort(keys(%flashvars))) {
                   3516:         if ($shockwave{$id} ne '') {
                   3517:             my @pairs = split(/\&/,$flashvars{$id});
                   3518:             foreach my $pair (@pairs) {
                   3519:                 my ($key,$value) = split(/\=/,$pair);
                   3520:                 if ($key eq 'thumb') {
                   3521:                     &add_filetype($allfiles,$value,$key);
                   3522:                 } elsif ($key eq 'content') {
                   3523:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3524:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3525:                     if ($ext ne '') {
                   3526:                         &add_filetype($allfiles,$path.$value,$ext);
                   3527:                     }
                   3528:                 }
                   3529:             }
                   3530:         }
                   3531:     }
1.637     raeburn  3532:     return 'ok';
                   3533: }
                   3534: 
1.639     albertel 3535: sub add_filetype {
                   3536:     my ($allfiles,$file,$type)=@_;
                   3537:     if (exists($allfiles->{$file})) {
                   3538: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3539: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3540: 	}
                   3541:     } else {
                   3542: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3543:     }
                   3544: }
                   3545: 
1.1164    raeburn  3546: sub embedded_dependency {
                   3547:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3548:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3549:         if (($identifier ne '') &&
                   3550:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3551:             ($pathfrom ne '')) {
                   3552:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3553:             foreach my $dep (@{$related->{$identifier}}) {
                   3554:                 &add_filetype($allfiles,$path.$dep,'object');
                   3555:             }
                   3556:         }
                   3557:     }
                   3558:     return;
                   3559: }
                   3560: 
1.493     albertel 3561: sub removeuploadedurl {
1.984     neumanie 3562:     my ($url)=@_;	
                   3563:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3564:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3565: }
                   3566: 
                   3567: sub removeuserfile {
                   3568:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3569:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3570:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3571:     if ($result eq 'ok') {	
1.798     raeburn  3572:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3573:             my $metafile = $fname.'.meta';
                   3574:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3575: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3576:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3577:             my $sqlresult = 
1.823     albertel 3578:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3579:                                         'portfolio_metadata',$group,
                   3580:                                         'delete');
1.798     raeburn  3581:         }
                   3582:     }
                   3583:     return $result;
1.257     www      3584: }
1.15      www      3585: 
1.530     albertel 3586: sub mkdiruserfile {
                   3587:     my ($docuname,$docudom,$dir)=@_;
                   3588:     my $home=&homeserver($docuname,$docudom);
                   3589:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3590: }
                   3591: 
1.531     albertel 3592: sub renameuserfile {
                   3593:     my ($docuname,$docudom,$old,$new)=@_;
                   3594:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3595:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3596:                         &escape("$old").':'.&escape("$new"),$home);
                   3597:     if ($result eq 'ok') {
                   3598:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3599:             my $oldmeta = $old.'.meta';
                   3600:             my $newmeta = $new.'.meta';
                   3601:             my $metaresult = 
                   3602:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3603: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3604:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3605:             my $sqlresult = 
1.823     albertel 3606:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3607:                                         'portfolio_metadata',$group,
                   3608:                                         'delete');
1.798     raeburn  3609:         }
                   3610:     }
                   3611:     return $result;
1.531     albertel 3612: }
                   3613: 
1.14      www      3614: # ------------------------------------------------------------------------- Log
                   3615: 
                   3616: sub log {
                   3617:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3618:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3619: }
                   3620: 
                   3621: # ------------------------------------------------------------------ Course Log
1.352     www      3622: #
                   3623: # This routine flushes several buffers of non-mission-critical nature
                   3624: #
1.157     www      3625: 
                   3626: sub flushcourselogs {
1.352     www      3627:     &logthis('Flushing log buffers');
                   3628: #
                   3629: # course logs
                   3630: # This is a log of all transactions in a course, which can be used
                   3631: # for data mining purposes
                   3632: #
                   3633: # It also collects the courseid database, which lists last transaction
                   3634: # times and course titles for all courseids
                   3635: #
                   3636:     my %courseidbuffer=();
1.921     raeburn  3637:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3638:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3639: 		          &escape($courselogs{$crsid}),
                   3640: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3641: 	    delete $courselogs{$crsid};
                   3642:         } else {
                   3643:             &logthis('Failed to flush log buffer for '.$crsid);
                   3644:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3645:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3646:                         " exceeded maximum size, deleting.</font>");
                   3647:                delete $courselogs{$crsid};
                   3648:             }
1.352     www      3649:         }
1.920     raeburn  3650:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3651:             'description' => $coursedescrbuf{$crsid},
                   3652:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3653:             'type'        => $coursetypebuf{$crsid},
                   3654:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3655:         };
1.191     harris41 3656:     }
1.352     www      3657: #
                   3658: # Write course id database (reverse lookup) to homeserver of courses 
                   3659: # Is used in pickcourse
                   3660: #
1.840     albertel 3661:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3662:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3663:                                     $courseidbuffer{$crs_home},
                   3664:                                     $crs_home,'timeonly');
1.352     www      3665:     }
                   3666: #
                   3667: # File accesses
                   3668: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3669: #
1.449     matthew  3670:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3671:         if ($entry =~ /___count$/) {
                   3672:             my ($dom,$name);
1.807     albertel 3673:             ($dom,$name,undef)=
1.811     albertel 3674: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3675:             if (! defined($dom) || $dom eq '' || 
                   3676:                 ! defined($name) || $name eq '') {
1.620     albertel 3677:                 my $cid = $env{'request.course.id'};
                   3678:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3679:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3680:             }
1.450     matthew  3681:             my $value = $accesshash{$entry};
                   3682:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3683:             my %temphash=($url => $value);
1.449     matthew  3684:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3685:             if ($result eq 'ok') {
                   3686:                 delete $accesshash{$entry};
                   3687:             }
                   3688:         } else {
1.811     albertel 3689:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3690:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3691:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3692:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3693:                 delete $accesshash{$entry};
                   3694:             }
1.185     www      3695:         }
1.191     harris41 3696:     }
1.352     www      3697: #
                   3698: # Roles
                   3699: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3700: #
1.800     albertel 3701:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3702:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3703: 	    split(/\:/,$entry);
                   3704:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3705:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3706:                 $rudom,$runame) eq 'ok') {
                   3707: 	    delete $userrolehash{$entry};
                   3708:         }
                   3709:     }
1.662     raeburn  3710: #
                   3711: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3712: #
                   3713:     my %domrolebuffer = ();
1.1000    raeburn  3714:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3715:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3716:         if ($domrolebuffer{$rudom}) {
                   3717:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3718:                       '='.&escape($domainrolehash{$entry});
                   3719:         } else {
                   3720:             $domrolebuffer{$rudom}.=&escape($entry).
                   3721:                       '='.&escape($domainrolehash{$entry});
                   3722:         }
                   3723:         delete $domainrolehash{$entry};
                   3724:     }
                   3725:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3726: 	my %servers = &get_servers($dom,'library');
                   3727: 	foreach my $tryserver (keys(%servers)) {
                   3728: 	    unless (&reply('domroleput:'.$dom.':'.
                   3729: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3730: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3731: 	    }
1.662     raeburn  3732:         }
                   3733:     }
1.186     www      3734:     $dumpcount++;
1.157     www      3735: }
                   3736: 
                   3737: sub courselog {
                   3738:     my $what=shift;
1.158     www      3739:     $what=time.':'.$what;
1.620     albertel 3740:     unless ($env{'request.course.id'}) { return ''; }
                   3741:     $coursedombuf{$env{'request.course.id'}}=
                   3742:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3743:     $coursenumbuf{$env{'request.course.id'}}=
                   3744:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3745:     $coursehombuf{$env{'request.course.id'}}=
                   3746:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3747:     $coursedescrbuf{$env{'request.course.id'}}=
                   3748:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3749:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3750:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3751:     $courseownerbuf{$env{'request.course.id'}}=
                   3752:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3753:     $coursetypebuf{$env{'request.course.id'}}=
                   3754:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3755:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3756: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3757:     } else {
1.620     albertel 3758: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3759:     }
1.620     albertel 3760:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3761: 	&flushcourselogs();
                   3762:     }
1.158     www      3763: }
                   3764: 
                   3765: sub courseacclog {
                   3766:     my $fnsymb=shift;
1.620     albertel 3767:     unless ($env{'request.course.id'}) { return ''; }
                   3768:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3769:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3770:         $what.=':POST';
1.583     matthew  3771:         # FIXME: Probably ought to escape things....
1.800     albertel 3772: 	foreach my $key (keys(%env)) {
                   3773:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3774:                 my $formitem = $1;
                   3775:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3776:                     $what.=':'.$formitem.'='.$env{$key};
                   3777:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3778:                     $what.=':'.$formitem.'='.$env{$key};
                   3779:                 }
1.158     www      3780:             }
1.191     harris41 3781:         }
1.583     matthew  3782:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3783:         # FIXME: We should not be depending on a form parameter that someone
                   3784:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3785:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3786:             $what.= ':POST';
                   3787:             # FIXME: Probably ought to escape things....
                   3788:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3789:                                  'crsdiscuss') {
1.620     albertel 3790:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3791:             }
                   3792:         }
1.158     www      3793:     }
                   3794:     &courselog($what);
1.149     www      3795: }
                   3796: 
1.185     www      3797: sub countacc {
                   3798:     my $url=&declutter(shift);
1.458     matthew  3799:     return if (! defined($url) || $url eq '');
1.620     albertel 3800:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3801: #
                   3802: # Mark that this url was used in this course
                   3803: #
1.620     albertel 3804:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3805: #
                   3806: # Increase the access count for this resource in this child process
                   3807: #
1.281     www      3808:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3809:     $accesshash{$key}++;
1.185     www      3810: }
1.349     www      3811: 
1.361     www      3812: sub linklog {
                   3813:     my ($from,$to)=@_;
                   3814:     $from=&declutter($from);
                   3815:     $to=&declutter($to);
                   3816:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3817:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3818: }
1.1160    www      3819: 
                   3820: sub statslog {
                   3821:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   3822:     if ($users<2) { return; }
                   3823:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   3824:             'course'       => $env{'request.course.id'},
                   3825:             'sections'     => '"all"',
                   3826:             'num_students' => $users,
                   3827:             'part'         => $part,
                   3828:             'symb'         => $symb,
                   3829:             'mean_tries'   => $av_attempts,
                   3830:             'deg_of_diff'  => $degdiff});
                   3831:     foreach my $key (keys(%dynstore)) {
                   3832:         $accesshash{$key}=$dynstore{$key};
                   3833:     }
                   3834: }
1.361     www      3835:   
1.349     www      3836: sub userrolelog {
                   3837:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 3838:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      3839:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3840:        $userrolehash
                   3841:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3842:                     =$tend.':'.$tstart;
1.662     raeburn  3843:     }
1.1169    droeschl 3844:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 3845:        $userrolehash
                   3846:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3847:                     =$tend.':'.$tstart;
                   3848:     }
1.1169    droeschl 3849:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  3850:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3851:        $domainrolehash
                   3852:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3853:                     = $tend.':'.$tstart;
                   3854:     }
1.351     www      3855: }
                   3856: 
1.957     raeburn  3857: sub courserolelog {
                   3858:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  3859:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3860:         my $cdom = $1;
                   3861:         my $cnum = $2;
                   3862:         my $sec = $3;
                   3863:         my $namespace = 'rolelog';
                   3864:         my %storehash = (
                   3865:                            role    => $trole,
                   3866:                            start   => $tstart,
                   3867:                            end     => $tend,
                   3868:                            selfenroll => $selfenroll,
                   3869:                            context    => $context,
                   3870:                         );
                   3871:         if ($trole eq 'gr') {
                   3872:             $namespace = 'groupslog';
                   3873:             $storehash{'group'} = $sec;
                   3874:         } else {
                   3875:             $storehash{'section'} = $sec;
                   3876:         }
                   3877:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   3878:                    $domain,$cnum,$cdom);
                   3879:         if (($trole ne 'st') || ($sec ne '')) {
                   3880:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  3881:         }
                   3882:     }
                   3883:     return;
                   3884: }
                   3885: 
1.1172.2.9  raeburn  3886: sub domainrolelog {
                   3887:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3888:     if ($area =~ m{^/($match_domain)/$}) {
                   3889:         my $cdom = $1;
                   3890:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   3891:         my $namespace = 'rolelog';
                   3892:         my %storehash = (
                   3893:                            role    => $trole,
                   3894:                            start   => $tstart,
                   3895:                            end     => $tend,
                   3896:                            context => $context,
                   3897:                         );
                   3898:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   3899:                    $domain,$domconfiguser,$cdom);
                   3900:     }
                   3901:     return;
                   3902: 
                   3903: }
                   3904: 
                   3905: sub coauthorrolelog {
                   3906:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3907:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   3908:         my $audom = $1;
                   3909:         my $auname = $2;
                   3910:         my $namespace = 'rolelog';
                   3911:         my %storehash = (
                   3912:                            role    => $trole,
                   3913:                            start   => $tstart,
                   3914:                            end     => $tend,
                   3915:                            context => $context,
                   3916:                         );
                   3917:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   3918:                    $domain,$auname,$audom);
                   3919:     }
                   3920:     return;
                   3921: }
                   3922: 
1.351     www      3923: sub get_course_adv_roles {
1.948     raeburn  3924:     my ($cid,$codes) = @_;
1.620     albertel 3925:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3926:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3927:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3928:     my %nothide=();
1.800     albertel 3929:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3930:         if ($user !~ /:/) {
                   3931: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3932:         } else {
                   3933:             $nothide{$user}=1;
                   3934:         }
1.470     www      3935:     }
1.1172.2.23  raeburn  3936:     my @possdoms = ($coursehash{'domain'});
                   3937:     if ($coursehash{'checkforpriv'}) {
                   3938:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3939:     }
1.351     www      3940:     my %returnhash=();
                   3941:     my %dumphash=
                   3942:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3943:     my $now=time;
1.997     raeburn  3944:     my %privileged;
1.1000    raeburn  3945:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3946: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3947:         if (($tstart) && ($tstart<0)) { next; }
                   3948:         if (($tend) && ($tend<$now)) { next; }
                   3949:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3950:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3951: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  3952:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  3953:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3954: 	if ($role eq 'cr') { next; }
1.948     raeburn  3955:         if ($codes) {
                   3956:             if ($section) { $role .= ':'.$section; }
                   3957:             if ($returnhash{$role}) {
                   3958:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3959:             } else {
                   3960:                 $returnhash{$role}=$username.':'.$domain;
                   3961:             }
1.351     www      3962:         } else {
1.988     raeburn  3963:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3964:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3965:             if ($returnhash{$key}) {
                   3966: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3967:             } else {
                   3968:                 $returnhash{$key}=$username.':'.$domain;
                   3969:             }
1.351     www      3970:         }
1.948     raeburn  3971:     }
1.400     www      3972:     return %returnhash;
                   3973: }
                   3974: 
                   3975: sub get_my_roles {
1.937     raeburn  3976:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3977:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3978:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3979:     my (%dumphash,%nothide);
1.1086    raeburn  3980:     if ($context eq 'userroles') {
1.1166    raeburn  3981:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  3982:     } else {
1.1172.2.23  raeburn  3983:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3984:         if ($hidepriv) {
                   3985:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3986:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3987:                 if ($user !~ /:/) {
                   3988:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3989:                 } else {
                   3990:                     $nothide{$user} = 1;
                   3991:                 }
                   3992:             }
                   3993:         }
1.858     raeburn  3994:     }
1.400     www      3995:     my %returnhash=();
                   3996:     my $now=time;
1.999     raeburn  3997:     my %privileged;
1.800     albertel 3998:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3999:         my ($role,$tend,$tstart);
                   4000:         if ($context eq 'userroles') {
1.1149    raeburn  4001:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4002: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4003:         } else {
                   4004:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4005:         }
1.400     www      4006:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4007:         my $status = 'active';
1.939     raeburn  4008:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4009:             $status = 'previous';
                   4010:         } 
                   4011:         if (($tstart) && ($now<$tstart)) {
                   4012:             $status = 'future';
                   4013:         }
                   4014:         if (ref($types) eq 'ARRAY') {
                   4015:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4016:                 next;
                   4017:             } 
                   4018:         } else {
                   4019:             if ($status ne 'active') {
                   4020:                 next;
                   4021:             }
                   4022:         }
1.867     raeburn  4023:         my ($rolecode,$username,$domain,$section,$area);
                   4024:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  4025:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4026:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4027:         } else {
                   4028:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4029:         }
1.832     raeburn  4030:         if (ref($roledoms) eq 'ARRAY') {
                   4031:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4032:                 next;
                   4033:             }
                   4034:         }
                   4035:         if (ref($roles) eq 'ARRAY') {
                   4036:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4037:                 if ($role =~ /^cr\//) {
                   4038:                     if (!grep(/^cr$/,@{$roles})) {
                   4039:                         next;
                   4040:                     }
1.1104    raeburn  4041:                 } elsif ($role =~ /^gr\//) {
                   4042:                     if (!grep(/^gr$/,@{$roles})) {
                   4043:                         next;
                   4044:                     }
1.922     raeburn  4045:                 } else {
                   4046:                     next;
                   4047:                 }
1.832     raeburn  4048:             }
1.867     raeburn  4049:         }
1.937     raeburn  4050:         if ($hidepriv) {
1.1172.2.23  raeburn  4051:             my @privroles = ('dc','su');
1.999     raeburn  4052:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  4053:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4054:             } else {
1.1172.2.23  raeburn  4055:                 my $possdoms = [$domain];
                   4056:                 if (ref($roledoms) eq 'ARRAY') {
                   4057:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  4058:                 }
1.1172.2.23  raeburn  4059:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4060:                     if (!$nothide{$username.':'.$domain}) {
                   4061:                         next;
                   4062:                     }
                   4063:                 }
1.937     raeburn  4064:             }
                   4065:         }
1.933     raeburn  4066:         if ($withsec) {
                   4067:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4068:                 $tstart.':'.$tend;
                   4069:         } else {
                   4070:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4071:         }
1.832     raeburn  4072:     }
1.373     www      4073:     return %returnhash;
1.399     www      4074: }
                   4075: 
                   4076: # ----------------------------------------------------- Frontpage Announcements
                   4077: #
                   4078: #
                   4079: 
                   4080: sub postannounce {
                   4081:     my ($server,$text)=@_;
1.844     albertel 4082:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4083:     unless ($text=~/\w/) { $text=''; }
                   4084:     return &reply('setannounce:'.&escape($text),$server);
                   4085: }
                   4086: 
                   4087: sub getannounce {
1.448     albertel 4088: 
                   4089:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4090: 	my $announcement='';
1.800     albertel 4091: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4092: 	close($fh);
1.399     www      4093: 	if ($announcement=~/\w/) { 
                   4094: 	    return 
                   4095:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4096:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4097: 	} else {
                   4098: 	    return '';
                   4099: 	}
                   4100:     } else {
                   4101: 	return '';
                   4102:     }
1.351     www      4103: }
1.353     www      4104: 
                   4105: # ---------------------------------------------------------- Course ID routines
                   4106: # Deal with domain's nohist_courseid.db files
                   4107: #
                   4108: 
                   4109: sub courseidput {
1.921     raeburn  4110:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4111:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4112:     my $outcome;
                   4113:     if ($caller eq 'timeonly') {
                   4114:         my $cids = '';
                   4115:         foreach my $item (keys(%$storehash)) {
                   4116:             $cids.=&escape($item).'&';
                   4117:         }
                   4118:         $cids=~s/\&$//;
                   4119:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4120:                           $coursehome);       
                   4121:     } else {
                   4122:         my $items = '';
                   4123:         foreach my $item (keys(%$storehash)) {
                   4124:             $items.= &escape($item).'='.
                   4125:                      &freeze_escape($$storehash{$item}).'&';
                   4126:         }
                   4127:         $items=~s/\&$//;
                   4128:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4129:                           $coursehome);
1.918     raeburn  4130:     }
                   4131:     if ($outcome eq 'unknown_cmd') {
                   4132:         my $what;
                   4133:         foreach my $cid (keys(%$storehash)) {
                   4134:             $what .= &escape($cid).'=';
1.921     raeburn  4135:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4136:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4137:             }
                   4138:             $what =~ s/\:$/&/;
                   4139:         }
                   4140:         $what =~ s/\&$//;  
                   4141:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4142:     } else {
                   4143:         return $outcome;
                   4144:     }
1.353     www      4145: }
                   4146: 
                   4147: sub courseiddump {
1.921     raeburn  4148:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4149:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4150:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  4151:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  4152:     my $as_hash = 1;
                   4153:     my %returnhash;
                   4154:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4155:     my %libserv = &all_library();
                   4156:     foreach my $tryserver (keys(%libserv)) {
                   4157:         if ( (  $hostidflag == 1 
                   4158: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4159: 	     || (!defined($hostidflag)) ) {
                   4160: 
1.918     raeburn  4161: 	    if (($domfilter eq '') ||
                   4162: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  4163:                 my $rep;
                   4164:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   4165:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   4166:                         join(":", (&host_domain($tryserver), $sincefilter,
                   4167:                                 &escape($descfilter), &escape($instcodefilter),
                   4168:                                 &escape($ownerfilter), &escape($coursefilter),
                   4169:                                 &escape($typefilter), &escape($regexp_ok),
                   4170:                                 $as_hash, &escape($selfenrollonly),
                   4171:                                 &escape($catfilter), $showhidden, $caller,
                   4172:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   4173:                                 &escape($createdbefore), &escape($createdafter),
                   4174:                                 &escape($creationcontext), $domcloner)));
                   4175:                 } else {
                   4176:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4177:                              $sincefilter.':'.&escape($descfilter).':'.
                   4178:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4179:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4180:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4181:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4182:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4183:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4184:                              &escape($createdbefore).':'.&escape($createdafter).':'.
                   4185:                              &escape($creationcontext).':'.$domcloner,
                   4186:                              $tryserver);
                   4187:                 }
                   4188: 
1.918     raeburn  4189:                 my @pairs=split(/\&/,$rep);
                   4190:                 foreach my $item (@pairs) {
                   4191:                     my ($key,$value)=split(/\=/,$item,2);
                   4192:                     $key = &unescape($key);
                   4193:                     next if ($key =~ /^error: 2 /);
                   4194:                     my $result = &thaw_unescape($value);
                   4195:                     if (ref($result) eq 'HASH') {
                   4196:                         $returnhash{$key}=$result;
                   4197:                     } else {
1.921     raeburn  4198:                         my @responses = split(/:/,$value);
                   4199:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4200:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4201:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4202:                         }
1.1008    raeburn  4203:                     }
1.353     www      4204:                 }
                   4205:             }
                   4206:         }
                   4207:     }
                   4208:     return %returnhash;
                   4209: }
                   4210: 
1.1055    raeburn  4211: sub courselastaccess {
                   4212:     my ($cdom,$cnum,$hostidref) = @_;
                   4213:     my %returnhash;
                   4214:     if ($cdom && $cnum) {
                   4215:         my $chome = &homeserver($cnum,$cdom);
                   4216:         if ($chome ne 'no_host') {
                   4217:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4218:             &extract_lastaccess(\%returnhash,$rep);
                   4219:         }
                   4220:     } else {
                   4221:         if (!$cdom) { $cdom=''; }
                   4222:         my %libserv = &all_library();
                   4223:         foreach my $tryserver (keys(%libserv)) {
                   4224:             if (ref($hostidref) eq 'ARRAY') {
                   4225:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4226:             } 
                   4227:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4228:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4229:                 &extract_lastaccess(\%returnhash,$rep);
                   4230:             }
                   4231:         }
                   4232:     }
                   4233:     return %returnhash;
                   4234: }
                   4235: 
                   4236: sub extract_lastaccess {
                   4237:     my ($returnhash,$rep) = @_;
                   4238:     if (ref($returnhash) eq 'HASH') {
                   4239:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4240:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4241:                  $rep eq '') {
                   4242:             my @pairs=split(/\&/,$rep);
                   4243:             foreach my $item (@pairs) {
                   4244:                 my ($key,$value)=split(/\=/,$item,2);
                   4245:                 $key = &unescape($key);
                   4246:                 next if ($key =~ /^error: 2 /);
                   4247:                 $returnhash->{$key} = &thaw_unescape($value);
                   4248:             }
                   4249:         }
                   4250:     }
                   4251:     return;
                   4252: }
                   4253: 
1.658     raeburn  4254: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4255: 
                   4256: sub dcmailput {
1.685     raeburn  4257:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4258:     my $status = &Apache::lonnet::critical(
1.740     www      4259:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4260:        &escape($message),$server);
1.662     raeburn  4261:     return $status;
                   4262: }
                   4263: 
1.658     raeburn  4264: sub dcmaildump {
                   4265:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4266:     my %returnhash=();
1.846     albertel 4267: 
                   4268:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4269:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4270:                                                          &escape($enddate).':';
                   4271: 	my @esc_senders=map { &escape($_)} @$senders;
                   4272: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4273: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4274:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4275:             if (($key) && ($value)) {
                   4276:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4277:             }
                   4278:         }
                   4279:     }
                   4280:     return %returnhash;
                   4281: }
1.662     raeburn  4282: # ---------------------------------------------------------- Domain roles
                   4283: 
                   4284: sub get_domain_roles {
                   4285:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4286:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4287:         $startdate = '.';
                   4288:     }
1.1018    raeburn  4289:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4290:         $enddate = '.';
                   4291:     }
1.922     raeburn  4292:     my $rolelist;
                   4293:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  4294:         $rolelist = join('&',@{$roles});
1.922     raeburn  4295:     }
1.662     raeburn  4296:     my %personnel = ();
1.841     albertel 4297: 
                   4298:     my %servers = &get_servers($dom,'library');
                   4299:     foreach my $tryserver (keys(%servers)) {
                   4300: 	%{$personnel{$tryserver}}=();
                   4301: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4302: 					    &escape($startdate).':'.
                   4303: 					    &escape($enddate).':'.
                   4304: 					    &escape($rolelist), $tryserver))) {
                   4305: 	    my ($key,$value) = split(/\=/,$line,2);
                   4306: 	    if (($key) && ($value)) {
                   4307: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4308: 	    }
                   4309: 	}
1.662     raeburn  4310:     }
                   4311:     return %personnel;
                   4312: }
1.658     raeburn  4313: 
1.1057    www      4314: # ----------------------------------------------------------- Interval timing 
1.149     www      4315: 
1.1153    www      4316: {
                   4317: # Caches needed for speedup of navmaps
                   4318: # We don't want to cache this for very long at all (5 seconds at most)
                   4319: # 
                   4320: # The user for whom we cache
                   4321: my $cachedkey='';
                   4322: # The cached times for this user
                   4323: my %cachedtimes=();
                   4324: # When this was last done
                   4325: my $cachedtime=();
                   4326: 
                   4327: sub load_all_first_access {
1.1154    raeburn  4328:     my ($uname,$udom)=@_;
1.1156    www      4329:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  4330:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4331:         return;
                   4332:     }
                   4333:     $cachedtime=time;
                   4334:     $cachedkey=$uname.':'.$udom;
                   4335:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4336: }
                   4337: 
1.504     albertel 4338: sub get_first_access {
1.1162    raeburn  4339:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4340:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4341:     if ($argsymb) { $symb=$argsymb; }
                   4342:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4343:     if ($argmap) { $map = $argmap; }
1.926     albertel 4344:     if ($type eq 'course') {
                   4345: 	$res='course';
                   4346:     } elsif ($type eq 'map') {
1.588     albertel 4347: 	$res=&symbread($map);
                   4348:     } else {
                   4349: 	$res=$symb;
                   4350:     }
1.1153    www      4351:     &load_all_first_access($uname,$udom);
                   4352:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4353: }
                   4354: 
                   4355: sub set_first_access {
1.1162    raeburn  4356:     my ($type,$interval)=@_;
1.790     albertel 4357:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4358:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4359:     if ($type eq 'course') {
                   4360: 	$res='course';
                   4361:     } elsif ($type eq 'map') {
1.588     albertel 4362: 	$res=&symbread($map);
                   4363:     } else {
                   4364: 	$res=$symb;
                   4365:     }
1.1153    www      4366:     $cachedkey='';
1.1162    raeburn  4367:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4368:     if (!$firstaccess) {
1.1162    raeburn  4369:         my $start = time;
                   4370: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4371:                           $udom,$uname);
                   4372:         if ($putres eq 'ok') {
                   4373:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4374:                  $udom,$uname); 
                   4375:             &appenv(
                   4376:                      {
                   4377:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4378:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4379:                      }
                   4380:                   );
                   4381:         }
                   4382:         return $putres;
1.505     albertel 4383:     }
                   4384:     return 'already_set';
1.504     albertel 4385: }
1.1153    www      4386: }
1.1172.2.32! raeburn  4387: 
        !          4388: sub checkout {
        !          4389:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
        !          4390:     my $now=time;
        !          4391:     my $lonhost=$perlvar{'lonHostID'};
        !          4392:     my $infostr=&escape(
        !          4393:                  'CHECKOUTTOKEN&'.
        !          4394:                  $tuname.'&'.
        !          4395:                  $tudom.'&'.
        !          4396:                  $tcrsid.'&'.
        !          4397:                  $symb.'&'.
        !          4398:                  $now.'&'.$ENV{'REMOTE_ADDR'});
        !          4399:     my $token=&reply('tmpput:'.$infostr,$lonhost);
        !          4400:     if ($token=~/^error\:/) {
        !          4401:         &logthis("<font color=\"blue\">WARNING: ".
        !          4402:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
        !          4403:                  "</font>");
        !          4404:         return '';
        !          4405:     }
        !          4406: 
        !          4407:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
        !          4408:     $token=~tr/a-z/A-Z/;
        !          4409: 
        !          4410:     my %infohash=('resource.0.outtoken' => $token,
        !          4411:                   'resource.0.checkouttime' => $now,
        !          4412:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
        !          4413: 
        !          4414:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
        !          4415:        return '';
        !          4416:     } else {
        !          4417:         &logthis("<font color=\"blue\">WARNING: ".
        !          4418:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
        !          4419:                  "</font>");
        !          4420:     }
        !          4421: 
        !          4422:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
        !          4423:                          &escape('Checkout '.$infostr.' - '.
        !          4424:                                                  $token)) ne 'ok') {
        !          4425:         return '';
        !          4426:     } else {
        !          4427:         &logthis("<font color=\"blue\">WARNING: ".
        !          4428:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
        !          4429:                  "</font>");
        !          4430:     }
        !          4431:     return $token;
        !          4432: }
        !          4433: 
        !          4434: # ------------------------------------------------------------ Check in an item
        !          4435: 
        !          4436: sub checkin {
        !          4437:     my $token=shift;
        !          4438:     my $now=time;
        !          4439:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
        !          4440:     $lonhost=~tr/A-Z/a-z/;
        !          4441:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
        !          4442:     $dtoken=~s/\W/\_/g;
        !          4443:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
        !          4444:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
        !          4445: 
        !          4446:     unless (($tuname) && ($tudom)) {
        !          4447:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
        !          4448:         return '';
        !          4449:     }
        !          4450: 
        !          4451:     unless (&allowed('mgr',$tcrsid)) {
        !          4452:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
        !          4453:                  $env{'user.name'}.' - '.$env{'user.domain'});
        !          4454:         return '';
        !          4455:     }
        !          4456: 
        !          4457:     my %infohash=('resource.0.intoken' => $token,
        !          4458:                   'resource.0.checkintime' => $now,
        !          4459:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
        !          4460: 
        !          4461:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
        !          4462:        return '';
        !          4463:     }
        !          4464: 
        !          4465:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
        !          4466:                          &escape('Checkin - '.$token)) ne 'ok') {
        !          4467:         return '';
        !          4468:     }
        !          4469: 
        !          4470:     return ($symb,$tuname,$tudom,$tcrsid);
        !          4471: }
        !          4472: 
1.110     www      4473: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4474: 
                   4475: sub expirespread {
                   4476:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4477:     my $cid=$env{'request.course.id'}; 
1.110     www      4478:     if ($cid) {
                   4479:        my $now=time;
                   4480:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4481:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4482:                             $env{'course.'.$cid.'.num'}.
1.110     www      4483: 	        	    ':nohist_expirationdates:'.
                   4484:                             &escape($key).'='.$now,
1.620     albertel 4485:                             $env{'course.'.$cid.'.home'})
1.110     www      4486:     }
                   4487:     return 'ok';
1.14      www      4488: }
                   4489: 
1.109     www      4490: # ----------------------------------------------------- Devalidate Spreadsheets
                   4491: 
                   4492: sub devalidate {
1.325     www      4493:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4494:     my $cid=$env{'request.course.id'}; 
1.109     www      4495:     if ($cid) {
1.391     matthew  4496:         # delete the stored spreadsheets for
                   4497:         # - the student level sheet of this user in course's homespace
                   4498:         # - the assessment level sheet for this resource 
                   4499:         #   for this user in user's homespace
1.553     albertel 4500: 	# - current conditional state info
1.325     www      4501: 	my $key=$uname.':'.$udom.':';
1.109     www      4502:         my $status=
1.299     matthew  4503: 	    &del('nohist_calculatedsheets',
1.391     matthew  4504: 		 [$key.'studentcalc:'],
1.620     albertel 4505: 		 $env{'course.'.$cid.'.domain'},
                   4506: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4507: 		.' '.
                   4508: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4509: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4510:         unless ($status eq 'ok ok') {
                   4511:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4512:                     $uname.' at '.$udom.' for '.
1.109     www      4513: 		    $symb.': '.$status);
1.133     albertel 4514:         }
1.553     albertel 4515: 	&delenv('user.state.'.$cid);
1.109     www      4516:     }
                   4517: }
                   4518: 
1.265     albertel 4519: sub get_scalar {
                   4520:     my ($string,$end) = @_;
                   4521:     my $value;
                   4522:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4523: 	$value = $1;
                   4524:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4525: 	$value = $1;
                   4526:     }
                   4527:     return &unescape($value);
                   4528: }
                   4529: 
                   4530: sub array2str {
                   4531:   my (@array) = @_;
                   4532:   my $result=&arrayref2str(\@array);
                   4533:   $result=~s/^__ARRAY_REF__//;
                   4534:   $result=~s/__END_ARRAY_REF__$//;
                   4535:   return $result;
                   4536: }
                   4537: 
1.204     albertel 4538: sub arrayref2str {
                   4539:   my ($arrayref) = @_;
1.265     albertel 4540:   my $result='__ARRAY_REF__';
1.204     albertel 4541:   foreach my $elem (@$arrayref) {
1.265     albertel 4542:     if(ref($elem) eq 'ARRAY') {
                   4543:       $result.=&arrayref2str($elem).'&';
                   4544:     } elsif(ref($elem) eq 'HASH') {
                   4545:       $result.=&hashref2str($elem).'&';
                   4546:     } elsif(ref($elem)) {
                   4547:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4548:     } else {
                   4549:       $result.=&escape($elem).'&';
                   4550:     }
                   4551:   }
                   4552:   $result=~s/\&$//;
1.265     albertel 4553:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4554:   return $result;
                   4555: }
                   4556: 
1.168     albertel 4557: sub hash2str {
1.204     albertel 4558:   my (%hash) = @_;
                   4559:   my $result=&hashref2str(\%hash);
1.265     albertel 4560:   $result=~s/^__HASH_REF__//;
                   4561:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4562:   return $result;
                   4563: }
                   4564: 
                   4565: sub hashref2str {
                   4566:   my ($hashref)=@_;
1.265     albertel 4567:   my $result='__HASH_REF__';
1.800     albertel 4568:   foreach my $key (sort(keys(%$hashref))) {
                   4569:     if (ref($key) eq 'ARRAY') {
                   4570:       $result.=&arrayref2str($key).'=';
                   4571:     } elsif (ref($key) eq 'HASH') {
                   4572:       $result.=&hashref2str($key).'=';
                   4573:     } elsif (ref($key)) {
1.265     albertel 4574:       $result.='=';
1.800     albertel 4575:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4576:     } else {
1.1132    raeburn  4577: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4578:     }
                   4579: 
1.800     albertel 4580:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4581:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4582:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4583:       $result.=&hashref2str($hashref->{$key}).'&';
                   4584:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4585:        $result.='&';
1.800     albertel 4586:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4587:     } else {
1.800     albertel 4588:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4589:     }
                   4590:   }
1.168     albertel 4591:   $result=~s/\&$//;
1.265     albertel 4592:   $result .= '__END_HASH_REF__';
1.168     albertel 4593:   return $result;
                   4594: }
                   4595: 
                   4596: sub str2hash {
1.265     albertel 4597:     my ($string)=@_;
                   4598:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4599:     return %$hash;
                   4600: }
                   4601: 
                   4602: sub str2hashref {
1.168     albertel 4603:   my ($string) = @_;
1.265     albertel 4604: 
                   4605:   my %hash;
                   4606: 
                   4607:   if($string !~ /^__HASH_REF__/) {
                   4608:       if (! ($string eq '' || !defined($string))) {
                   4609: 	  $hash{'error'}='Not hash reference';
                   4610:       }
                   4611:       return (\%hash, $string);
                   4612:   }
                   4613: 
                   4614:   $string =~ s/^__HASH_REF__//;
                   4615: 
                   4616:   while($string !~ /^__END_HASH_REF__/) {
                   4617:       #key
                   4618:       my $key='';
                   4619:       if($string =~ /^__HASH_REF__/) {
                   4620:           ($key, $string)=&str2hashref($string);
                   4621:           if(defined($key->{'error'})) {
                   4622:               $hash{'error'}='Bad data';
                   4623:               return (\%hash, $string);
                   4624:           }
                   4625:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4626:           ($key, $string)=&str2arrayref($string);
                   4627:           if($key->[0] eq 'Array reference error') {
                   4628:               $hash{'error'}='Bad data';
                   4629:               return (\%hash, $string);
                   4630:           }
                   4631:       } else {
                   4632:           $string =~ s/^(.*?)=//;
1.267     albertel 4633: 	  $key=&unescape($1);
1.265     albertel 4634:       }
                   4635:       $string =~ s/^=//;
                   4636: 
                   4637:       #value
                   4638:       my $value='';
                   4639:       if($string =~ /^__HASH_REF__/) {
                   4640:           ($value, $string)=&str2hashref($string);
                   4641:           if(defined($value->{'error'})) {
                   4642:               $hash{'error'}='Bad data';
                   4643:               return (\%hash, $string);
                   4644:           }
                   4645:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4646:           ($value, $string)=&str2arrayref($string);
                   4647:           if($value->[0] eq 'Array reference error') {
                   4648:               $hash{'error'}='Bad data';
                   4649:               return (\%hash, $string);
                   4650:           }
                   4651:       } else {
                   4652: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4653:       }
                   4654:       $string =~ s/^&//;
                   4655: 
                   4656:       $hash{$key}=$value;
1.204     albertel 4657:   }
1.265     albertel 4658: 
                   4659:   $string =~ s/^__END_HASH_REF__//;
                   4660: 
                   4661:   return (\%hash, $string);
1.204     albertel 4662: }
                   4663: 
                   4664: sub str2array {
1.265     albertel 4665:     my ($string)=@_;
                   4666:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4667:     return @$array;
                   4668: }
                   4669: 
                   4670: sub str2arrayref {
1.204     albertel 4671:   my ($string) = @_;
1.265     albertel 4672:   my @array;
                   4673: 
                   4674:   if($string !~ /^__ARRAY_REF__/) {
                   4675:       if (! ($string eq '' || !defined($string))) {
                   4676: 	  $array[0]='Array reference error';
                   4677:       }
                   4678:       return (\@array, $string);
                   4679:   }
                   4680: 
                   4681:   $string =~ s/^__ARRAY_REF__//;
                   4682: 
                   4683:   while($string !~ /^__END_ARRAY_REF__/) {
                   4684:       my $value='';
                   4685:       if($string =~ /^__HASH_REF__/) {
                   4686:           ($value, $string)=&str2hashref($string);
                   4687:           if(defined($value->{'error'})) {
                   4688:               $array[0] ='Array reference error';
                   4689:               return (\@array, $string);
                   4690:           }
                   4691:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4692:           ($value, $string)=&str2arrayref($string);
                   4693:           if($value->[0] eq 'Array reference error') {
                   4694:               $array[0] ='Array reference error';
                   4695:               return (\@array, $string);
                   4696:           }
                   4697:       } else {
                   4698: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4699:       }
                   4700:       $string =~ s/^&//;
                   4701: 
                   4702:       push(@array, $value);
1.191     harris41 4703:   }
1.265     albertel 4704: 
                   4705:   $string =~ s/^__END_ARRAY_REF__//;
                   4706: 
                   4707:   return (\@array, $string);
1.168     albertel 4708: }
                   4709: 
1.167     albertel 4710: # -------------------------------------------------------------------Temp Store
                   4711: 
1.168     albertel 4712: sub tmpreset {
                   4713:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4714:   if (!$symb) {
                   4715:     $symb=&symbread();
1.620     albertel 4716:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4717:   }
                   4718:   $symb=escape($symb);
                   4719: 
1.620     albertel 4720:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4721:   $namespace=~s/\//\_/g;
                   4722:   $namespace=~s/\W//g;
                   4723: 
1.620     albertel 4724:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4725:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4726:   if ($domain eq 'public' && $stuname eq 'public') {
                   4727:       $stuname=$ENV{'REMOTE_ADDR'};
                   4728:   }
1.1117    foxr     4729:   my $path=LONCAPA::tempdir();
1.168     albertel 4730:   my %hash;
                   4731:   if (tie(%hash,'GDBM_File',
                   4732: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4733: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4734:     foreach my $key (keys(%hash)) {
1.180     albertel 4735:       if ($key=~ /:$symb/) {
1.168     albertel 4736: 	delete($hash{$key});
                   4737:       }
                   4738:     }
                   4739:   }
                   4740: }
                   4741: 
1.167     albertel 4742: sub tmpstore {
1.168     albertel 4743:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4744: 
                   4745:   if (!$symb) {
                   4746:     $symb=&symbread();
1.620     albertel 4747:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4748:   }
                   4749:   $symb=escape($symb);
                   4750: 
                   4751:   if (!$namespace) {
                   4752:     # I don't think we would ever want to store this for a course.
                   4753:     # it seems this will only be used if we don't have a course.
1.620     albertel 4754:     #$namespace=$env{'request.course.id'};
1.168     albertel 4755:     #if (!$namespace) {
1.620     albertel 4756:       $namespace=$env{'request.state'};
1.168     albertel 4757:     #}
                   4758:   }
                   4759:   $namespace=~s/\//\_/g;
                   4760:   $namespace=~s/\W//g;
1.620     albertel 4761:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4762:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4763:   if ($domain eq 'public' && $stuname eq 'public') {
                   4764:       $stuname=$ENV{'REMOTE_ADDR'};
                   4765:   }
1.168     albertel 4766:   my $now=time;
                   4767:   my %hash;
1.1117    foxr     4768:   my $path=LONCAPA::tempdir();
1.168     albertel 4769:   if (tie(%hash,'GDBM_File',
                   4770: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4771: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4772:     $hash{"version:$symb"}++;
                   4773:     my $version=$hash{"version:$symb"};
                   4774:     my $allkeys=''; 
                   4775:     foreach my $key (keys(%$storehash)) {
                   4776:       $allkeys.=$key.':';
1.591     albertel 4777:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4778:     }
                   4779:     $hash{"$version:$symb:timestamp"}=$now;
                   4780:     $allkeys.='timestamp';
                   4781:     $hash{"$version:keys:$symb"}=$allkeys;
                   4782:     if (untie(%hash)) {
                   4783:       return 'ok';
                   4784:     } else {
                   4785:       return "error:$!";
                   4786:     }
                   4787:   } else {
                   4788:     return "error:$!";
                   4789:   }
                   4790: }
1.167     albertel 4791: 
1.168     albertel 4792: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4793: 
1.168     albertel 4794: sub tmprestore {
                   4795:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4796: 
1.168     albertel 4797:   if (!$symb) {
                   4798:     $symb=&symbread();
1.620     albertel 4799:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4800:   }
                   4801:   $symb=escape($symb);
                   4802: 
1.620     albertel 4803:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4804: 
1.620     albertel 4805:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4806:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4807:   if ($domain eq 'public' && $stuname eq 'public') {
                   4808:       $stuname=$ENV{'REMOTE_ADDR'};
                   4809:   }
1.168     albertel 4810:   my %returnhash;
                   4811:   $namespace=~s/\//\_/g;
                   4812:   $namespace=~s/\W//g;
                   4813:   my %hash;
1.1117    foxr     4814:   my $path=LONCAPA::tempdir();
1.168     albertel 4815:   if (tie(%hash,'GDBM_File',
                   4816: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4817: 	  &GDBM_READER(),0640)) {
1.168     albertel 4818:     my $version=$hash{"version:$symb"};
                   4819:     $returnhash{'version'}=$version;
                   4820:     my $scope;
                   4821:     for ($scope=1;$scope<=$version;$scope++) {
                   4822:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4823:       my @keys=split(/:/,$vkeys);
                   4824:       my $key;
                   4825:       $returnhash{"$scope:keys"}=$vkeys;
                   4826:       foreach $key (@keys) {
1.591     albertel 4827: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4828: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4829:       }
                   4830:     }
1.168     albertel 4831:     if (!(untie(%hash))) {
                   4832:       return "error:$!";
                   4833:     }
                   4834:   } else {
                   4835:     return "error:$!";
                   4836:   }
                   4837:   return %returnhash;
1.167     albertel 4838: }
                   4839: 
1.9       www      4840: # ----------------------------------------------------------------------- Store
                   4841: 
                   4842: sub store {
1.124     www      4843:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4844:     my $home='';
                   4845: 
1.168     albertel 4846:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4847: 
1.213     www      4848:     $symb=&symbclean($symb);
1.122     albertel 4849:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4850: 
1.620     albertel 4851:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4852:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4853: 
                   4854:     &devalidate($symb,$stuname,$domain);
1.109     www      4855: 
                   4856:     $symb=escape($symb);
1.187     www      4857:     if (!$namespace) { 
1.620     albertel 4858:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4859:           return ''; 
                   4860:        } 
                   4861:     }
1.620     albertel 4862:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4863: 
                   4864:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4865:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4866: 
1.12      www      4867:     my $namevalue='';
1.800     albertel 4868:     foreach my $key (keys(%$storehash)) {
                   4869:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4870:     }
1.12      www      4871:     $namevalue=~s/\&$//;
1.187     www      4872:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4873:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4874: }
                   4875: 
1.47      www      4876: # -------------------------------------------------------------- Critical Store
                   4877: 
                   4878: sub cstore {
1.124     www      4879:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4880:     my $home='';
                   4881: 
1.168     albertel 4882:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4883: 
1.213     www      4884:     $symb=&symbclean($symb);
1.122     albertel 4885:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4886: 
1.620     albertel 4887:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4888:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4889: 
                   4890:     &devalidate($symb,$stuname,$domain);
1.109     www      4891: 
                   4892:     $symb=escape($symb);
1.187     www      4893:     if (!$namespace) { 
1.620     albertel 4894:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4895:           return ''; 
                   4896:        } 
                   4897:     }
1.620     albertel 4898:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4899: 
                   4900:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4901:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4902: 
1.47      www      4903:     my $namevalue='';
1.800     albertel 4904:     foreach my $key (keys(%$storehash)) {
                   4905:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4906:     }
1.47      www      4907:     $namevalue=~s/\&$//;
1.187     www      4908:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4909:     return critical
                   4910:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4911: }
                   4912: 
1.9       www      4913: # --------------------------------------------------------------------- Restore
                   4914: 
                   4915: sub restore {
1.124     www      4916:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4917:     my $home='';
                   4918: 
1.168     albertel 4919:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4920: 
1.122     albertel 4921:     if (!$symb) {
1.1172.2.26  raeburn  4922:         return if ($namespace eq 'courserequests');
                   4923:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 4924:     } else {
1.1172.2.26  raeburn  4925:         unless ($namespace eq 'courserequests') {
                   4926:             $symb=&escape(&symbclean($symb));
                   4927:         }
1.122     albertel 4928:     }
1.188     www      4929:     if (!$namespace) { 
1.620     albertel 4930:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4931:           return ''; 
                   4932:        } 
                   4933:     }
1.620     albertel 4934:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4935:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4936:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4937:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4938: 
1.12      www      4939:     my %returnhash=();
1.800     albertel 4940:     foreach my $line (split(/\&/,$answer)) {
                   4941: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4942:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4943:     }
1.75      www      4944:     my $version;
                   4945:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4946:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4947:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4948:        }
1.75      www      4949:     }
1.13      www      4950:     return %returnhash;
1.34      www      4951: }
                   4952: 
                   4953: # ---------------------------------------------------------- Course Description
1.1118    foxr     4954: #
                   4955: #  
1.34      www      4956: 
                   4957: sub coursedescription {
1.731     albertel 4958:     my ($courseid,$args)=@_;
1.34      www      4959:     $courseid=~s/^\///;
1.49      www      4960:     $courseid=~s/\_/\//g;
1.34      www      4961:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4962:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4963:     my $normalid=$cdomain.'_'.$cnum;
                   4964:     # need to always cache even if we get errors otherwise we keep 
                   4965:     # trying and trying and trying to get the course description.
                   4966:     my %envhash=();
                   4967:     my %returnhash=();
1.731     albertel 4968:     
                   4969:     my $expiretime=600;
                   4970:     if ($env{'request.course.id'} eq $normalid) {
                   4971: 	$expiretime=120;
                   4972:     }
                   4973: 
                   4974:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4975:     if (!$args->{'freshen_cache'}
                   4976: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4977: 	foreach my $key (keys(%env)) {
                   4978: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4979: 	    my ($setting) = $1;
                   4980: 	    $returnhash{$setting} = $env{$key};
                   4981: 	}
                   4982: 	return %returnhash;
                   4983:     }
                   4984: 
1.1118    foxr     4985:     # get the data again
                   4986: 
1.731     albertel 4987:     if (!$args->{'one_time'}) {
                   4988: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4989:     }
1.811     albertel 4990: 
1.34      www      4991:     if ($chome ne 'no_host') {
1.302     albertel 4992:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4993:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4994: 	   my $username = $env{'user.name'}; # Defult username
                   4995: 	   if(defined $args->{'user'}) {
                   4996: 	       $username = $args->{'user'};
                   4997: 	   }
1.129     albertel 4998:            $returnhash{'home'}= $chome;
                   4999: 	   $returnhash{'domain'} = $cdomain;
                   5000: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5001:            if (!defined($returnhash{'type'})) {
                   5002:                $returnhash{'type'} = 'Course';
                   5003:            }
1.130     albertel 5004:            while (my ($name,$value) = each %returnhash) {
1.53      www      5005:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5006:            }
1.270     www      5007:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5008:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5009: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5010:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5011:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5012:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5013:        }
                   5014:     }
1.731     albertel 5015:     if (!$args->{'one_time'}) {
1.949     raeburn  5016: 	&appenv(\%envhash);
1.731     albertel 5017:     }
1.302     albertel 5018:     return %returnhash;
1.461     www      5019: }
                   5020: 
1.1080    raeburn  5021: sub update_released_required {
                   5022:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5023:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5024:         $cid = $env{'request.course.id'};
                   5025:         $cdom = $env{'course.'.$cid.'.domain'};
                   5026:         $cnum = $env{'course.'.$cid.'.num'};
                   5027:         $chome = $env{'course.'.$cid.'.home'};
                   5028:     }
                   5029:     if ($needsrelease) {
                   5030:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5031:         my $needsupdate;
                   5032:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5033:             $needsupdate = 1;
                   5034:         } else {
                   5035:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5036:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5037:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5038:                 $needsupdate = 1;
                   5039:             }
                   5040:         }
                   5041:         if ($needsupdate) {
                   5042:             my %needshash = (
                   5043:                              'internal.releaserequired' => $needsrelease,
                   5044:                             );
                   5045:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5046:             if ($putresult eq 'ok') {
                   5047:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5048:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5049:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5050:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5051:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5052:                 }
                   5053:             }
                   5054:         }
                   5055:     }
                   5056:     return;
                   5057: }
                   5058: 
1.461     www      5059: # -------------------------------------------------See if a user is privileged
                   5060: 
                   5061: sub privileged {
1.1172.2.23  raeburn  5062:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5063:     my $now = time;
1.1172.2.23  raeburn  5064:     my $roles;
                   5065:     if (ref($possroles) eq 'ARRAY') {
                   5066:         $roles = $possroles;
                   5067:     } else {
                   5068:         $roles = ['dc','su'];
                   5069:     }
                   5070:     if (ref($possdomains) eq 'ARRAY') {
                   5071:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5072:         foreach my $dom (@{$possdomains}) {
                   5073:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5074:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5075:                 foreach my $role (@{$roles}) {
                   5076:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5077:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5078:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5079:                             return 1 unless (($end && $end < $now) ||
                   5080:                                              ($start && $start > $now));
                   5081:                         }
                   5082:                     }
                   5083:                 }
                   5084:             }
                   5085:         }
                   5086:     } else {
                   5087:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5088:         my $now = time;
1.1170    droeschl 5089: 
1.1172.2.23  raeburn  5090:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
1.1170    droeschl 5091:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  5092:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   5093:                 return 1 unless ($tend && $tend < $now)
                   5094:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5095:             }
1.1172.2.23  raeburn  5096:         }
                   5097:     }
1.461     www      5098:     return 0;
1.9       www      5099: }
1.1       albertel 5100: 
1.1172.2.23  raeburn  5101: sub privileged_by_domain {
                   5102:     my ($domains,$roles) = @_;
                   5103:     my %privileged = ();
                   5104:     my $cachetime = 60*60*24;
                   5105:     my $now = time;
                   5106:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5107:         return %privileged;
                   5108:     }
                   5109:     foreach my $dom (@{$domains}) {
                   5110:         next if (ref($privileged{$dom}) eq 'HASH');
                   5111:         my $needroles;
                   5112:         foreach my $role (@{$roles}) {
                   5113:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5114:             if (defined($cached)) {
                   5115:                 if (ref($result) eq 'HASH') {
                   5116:                     $privileged{$dom}{$role} = $result;
                   5117:                 }
                   5118:             } else {
                   5119:                 $needroles = 1;
                   5120:             }
                   5121:         }
                   5122:         if ($needroles) {
                   5123:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5124:             $privileged{$dom} = {};
                   5125:             foreach my $server (keys(%dompersonnel)) {
                   5126:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5127:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5128:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5129:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5130:                         next if ($end && $end < $now);
                   5131:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   5132:                             $dompersonnel{$server}{$item};
                   5133:                     }
                   5134:                 }
                   5135:             }
                   5136:             if (ref($privileged{$dom}) eq 'HASH') {
                   5137:                 foreach my $role (@{$roles}) {
                   5138:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5139:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5140:                     } else {
                   5141:                         my %hash = ();
                   5142:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5143:                     }
                   5144:                 }
                   5145:             }
                   5146:         }
                   5147:     }
                   5148:     return %privileged;
                   5149: }
                   5150: 
1.103     harris41 5151: # -------------------------------------------------------- Get user privileges
1.11      www      5152: 
                   5153: sub rolesinit {
1.1169    droeschl 5154:     my ($domain, $username) = @_;
                   5155:     my %userroles = ('user.login.time' => time);
                   5156:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5157: 
                   5158:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5159:     # also, blocking can be triggered by an activating timer
                   5160:     # it's saved in the user's %env.
                   5161:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5162:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5163:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5164:         %timerintchk, %timerintenv);
                   5165: 
1.1162    raeburn  5166:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5167:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5168:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5169:     }
1.1169    droeschl 5170: 
1.1162    raeburn  5171:     foreach my $key (keys(%timerinterval)) {
                   5172:         my ($cid,$rest) = split(/\0/,$key);
                   5173:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5174:     }
1.1169    droeschl 5175: 
1.11      www      5176:     my %allroles=();
1.1162    raeburn  5177:     my %allgroups=();
1.11      www      5178: 
1.1169    droeschl 5179:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
                   5180:         my $role = $rolesdump{$area};
                   5181:         $area =~ s/\_\w\w$//;
                   5182: 
                   5183:         my ($trole, $tend, $tstart, $group_privs);
                   5184: 
                   5185:         if ($role =~ /^cr/) {
                   5186:         # Custom role, defined by a user 
                   5187:         # e.g., user.role.cr/msu/smith/mynewrole
                   5188:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5189:                 $trole = $1;
                   5190:                 ($tend, $tstart) = split('_', $2);
                   5191:             } else {
                   5192:                 $trole = $role;
                   5193:             }
                   5194:         } elsif ($role =~ m|^gr/|) {
                   5195:         # Role of member in a group, defined within a course/community
                   5196:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5197:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5198:             next if $tstart eq '-1';
                   5199:             ($trole, $group_privs) = split(/\//, $trole);
                   5200:             $group_privs = &unescape($group_privs);
                   5201:         } else {
                   5202:         # Just a normal role, defined in roles.tab
                   5203:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5204:         }
                   5205: 
                   5206:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5207:                  $username);
                   5208:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5209: 
                   5210:         # role expired or not available yet?
                   5211:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5212:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5213: 
                   5214:         next if $area eq '' or $trole eq '';
                   5215: 
                   5216:         my $spec = "$trole.$area";
                   5217:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5218: 
                   5219:         if ($trole =~ /^cr\//) {
                   5220:         # Custom role, defined by a user
                   5221:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5222:         } elsif ($trole eq 'gr') {
                   5223:         # Role of a member in a group, defined within a course/community
                   5224:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5225:             next;
                   5226:         } else {
                   5227:         # Normal role, defined in roles.tab
                   5228:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5229:         }
                   5230: 
                   5231:         my $cid = $tdomain.'_'.$trest;
                   5232:         unless ($firstaccchk{$cid}) {
                   5233:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5234:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5235:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5236:                         $coursetimerstarts{$cid}{$item}; 
                   5237:                 }
                   5238:             }
                   5239:             $firstaccchk{$cid} = 1;
                   5240:         }
                   5241:         unless ($timerintchk{$cid}) {
                   5242:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5243:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5244:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5245:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5246:                 }
1.12      www      5247:             }
1.1169    droeschl 5248:             $timerintchk{$cid} = 1;
1.191     harris41 5249:         }
1.11      www      5250:     }
1.1169    droeschl 5251: 
                   5252:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5253:         \%allroles, \%allgroups);
                   5254:     $env{'user.adv'} = $userroles{'user.adv'};
                   5255: 
1.1162    raeburn  5256:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5257: }
                   5258: 
1.567     raeburn  5259: sub set_arearole {
1.1172.2.19  raeburn  5260:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5261:     unless ($nolog) {
1.567     raeburn  5262: # log the associated role with the area
1.1172.2.19  raeburn  5263:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5264:     }
1.743     albertel 5265:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5266: }
                   5267: 
                   5268: sub custom_roleprivs {
                   5269:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5270:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   5271:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 5272:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5273:         my ($rdummy,$roledef)=
                   5274:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5275:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5276:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5277:             if (defined($syspriv)) {
1.1043    raeburn  5278:                 if ($trest =~ /^$match_community$/) {
                   5279:                     $syspriv =~ s/bre\&S//; 
                   5280:                 }
1.567     raeburn  5281:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5282:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5283:             }
                   5284:             if ($tdomain ne '') {
                   5285:                 if (defined($dompriv)) {
                   5286:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5287:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5288:                 }
                   5289:                 if (($trest ne '') && (defined($coursepriv))) {
                   5290:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5291:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5292:                 }
                   5293:             }
                   5294:         }
                   5295:     }
                   5296: }
                   5297: 
1.678     raeburn  5298: sub group_roleprivs {
                   5299:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5300:     my $access = 1;
                   5301:     my $now = time;
                   5302:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5303:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5304:     if ($access) {
1.811     albertel 5305:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5306:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5307:     }
                   5308: }
1.567     raeburn  5309: 
                   5310: sub standard_roleprivs {
                   5311:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5312:     if (defined($pr{$trole.':s'})) {
                   5313:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5314:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5315:     }
                   5316:     if ($tdomain ne '') {
                   5317:         if (defined($pr{$trole.':d'})) {
                   5318:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5319:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5320:         }
                   5321:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5322:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5323:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5324:         }
                   5325:     }
                   5326: }
                   5327: 
                   5328: sub set_userprivs {
1.1064    raeburn  5329:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5330:     my $author=0;
                   5331:     my $adv=0;
1.678     raeburn  5332:     my %grouproles = ();
                   5333:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5334:         my @groupkeys; 
1.1000    raeburn  5335:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5336:             push(@groupkeys,$role);
                   5337:         }
                   5338:         if (ref($groups_roles) eq 'HASH') {
                   5339:             foreach my $key (keys(%{$groups_roles})) {
                   5340:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5341:                     push(@groupkeys,$key);
                   5342:                 }
                   5343:             }
                   5344:         }
                   5345:         if (@groupkeys > 0) {
                   5346:             foreach my $role (@groupkeys) {
                   5347:                 my ($trole,$area,$sec,$extendedarea);
                   5348:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5349:                     $trole = $1;
                   5350:                     $area = $2;
                   5351:                     $sec = $3;
                   5352:                     $extendedarea = $area.$sec;
                   5353:                     if (exists($$allgroups{$area})) {
                   5354:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5355:                             my $spec = $trole.'.'.$extendedarea;
                   5356:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5357:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5358:                         }
1.678     raeburn  5359:                     }
                   5360:                 }
                   5361:             }
                   5362:         }
                   5363:     }
1.800     albertel 5364:     foreach my $group (keys(%grouproles)) {
                   5365:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5366:     }
1.800     albertel 5367:     foreach my $role (keys(%{$allroles})) {
                   5368:         my %thesepriv;
1.941     raeburn  5369:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5370:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5371:             if ($item ne '') {
                   5372:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5373:                 if ($restrictions eq '') {
                   5374:                     $thesepriv{$privilege}='F';
                   5375:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5376:                     $thesepriv{$privilege}.=$restrictions;
                   5377:                 }
                   5378:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5379:             }
                   5380:         }
                   5381:         my $thesestr='';
1.1104    raeburn  5382:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5383: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5384: 	}
                   5385:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5386:     }
                   5387:     return ($author,$adv);
                   5388: }
                   5389: 
1.994     raeburn  5390: sub role_status {
1.1104    raeburn  5391:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5392:     my @pwhere = ();
                   5393:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   5394:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   5395:         unless (!defined($$role) || $$role eq '') {
                   5396:             $$where=join('.',@pwhere);
                   5397:             $$trolecode=$$role.'.'.$$where;
                   5398:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5399:             $$tstatus='is';
1.1104    raeburn  5400:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5401:                 $$tstatus='future';
1.1034    raeburn  5402:                 if ($$tstart<$now) {
                   5403:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5404:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5405:                             my (%allroles,%allgroups,$group_privs,
                   5406:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5407:                             my %userroles = (
                   5408:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5409:                             );
1.1064    raeburn  5410:                             @rolecodes = ('cm'); 
1.1002    raeburn  5411:                             my $spec=$$role.'.'.$$where;
                   5412:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5413:                             if ($$role =~ /^cr\//) {
                   5414:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5415:                                 push(@rolecodes,'cr');
1.1002    raeburn  5416:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5417:                                 push(@rolecodes,$$role);
1.1002    raeburn  5418:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5419:                                                     $env{'user.name'});
1.1064    raeburn  5420:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5421:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5422:                                 $group_privs = &unescape($group_privs);
                   5423:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5424:                                 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  5425:                                 &get_groups_roles($tdomain,$trest,
                   5426:                                                   \%course_roles,\@rolecodes,
                   5427:                                                   \%groups_roles);
1.1002    raeburn  5428:                             } else {
1.1064    raeburn  5429:                                 push(@rolecodes,$$role);
1.1002    raeburn  5430:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5431:                             }
1.1064    raeburn  5432:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5433:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5434:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5435:                         }
                   5436:                     }
1.1034    raeburn  5437:                     $$tstatus = 'is';
1.1002    raeburn  5438:                 }
1.994     raeburn  5439:             }
                   5440:             if ($$tend) {
1.1104    raeburn  5441:                 if ($$tend<$update) {
1.994     raeburn  5442:                     $$tstatus='expired';
                   5443:                 } elsif ($$tend<$now) {
                   5444:                     $$tstatus='will_not';
                   5445:                 }
                   5446:             }
                   5447:         }
                   5448:     }
                   5449: }
                   5450: 
1.1104    raeburn  5451: sub get_groups_roles {
                   5452:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5453:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5454:                   (ref($rolecodes) eq 'ARRAY') && 
                   5455:                   (ref($groups_roles) eq 'HASH')); 
                   5456:     if (keys(%{$cdom_courseroles}) > 0) {
                   5457:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5458:         if ($cdom ne '' && $cnum ne '') {
                   5459:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5460:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5461:                     my $crsrole = $1;
                   5462:                     my $crssec = $2;
                   5463:                     if ($crsrole =~ /^cr/) {
                   5464:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5465:                             push(@{$rolecodes},'cr');
                   5466:                         }
                   5467:                     } else {
                   5468:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5469:                             push(@{$rolecodes},$crsrole);
                   5470:                         }
                   5471:                     }
                   5472:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5473:                     if ($crssec ne '') {
                   5474:                         $rolekey .= "/$crssec";
                   5475:                     }
                   5476:                     $rolekey .= './';
                   5477:                     $groups_roles->{$rolekey} = $rolecodes;
                   5478:                 }
                   5479:             }
                   5480:         }
                   5481:     }
                   5482:     return;
                   5483: }
                   5484: 
                   5485: sub delete_env_groupprivs {
                   5486:     my ($where,$courseroles,$possroles) = @_;
                   5487:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5488:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5489:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5490:         %{$courseroles->{$udom}} =
                   5491:             &get_my_roles('','','userroles',['active'],
                   5492:                           $possroles,[$udom],1);
                   5493:     }
                   5494:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5495:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5496:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5497:             my $area = '/'.$cdom.'/'.$cnum;
                   5498:             my $privkey = "user.priv.$crsrole.$area";
                   5499:             if ($crssec ne '') {
                   5500:                 $privkey .= '/'.$crssec;
                   5501:             }
                   5502:             $privkey .= ".$area/$group";
                   5503:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5504:         }
                   5505:     }
                   5506:     return;
                   5507: }
                   5508: 
1.994     raeburn  5509: sub check_adhoc_privs {
1.1104    raeburn  5510:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5511:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.9  raeburn  5512:     my $setprivs;
1.994     raeburn  5513:     if ($env{$cckey}) {
                   5514:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5515:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5516:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5517:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9  raeburn  5518:             $setprivs = 1;
1.994     raeburn  5519:         }
                   5520:     } else {
1.1088    raeburn  5521:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9  raeburn  5522:         $setprivs = 1;
1.994     raeburn  5523:     }
1.1172.2.9  raeburn  5524:     return $setprivs;
1.994     raeburn  5525: }
                   5526: 
                   5527: sub set_adhoc_privileges {
                   5528: # role can be cc or ca
1.1088    raeburn  5529:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5530:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5531:     my $spec = $role.'.'.$area;
                   5532:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  5533:                                   $env{'user.name'},1);
1.994     raeburn  5534:     my %ccrole = ();
                   5535:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5536:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5537:     &appenv(\%userroles,[$role,'cm']);
                   5538:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5539:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5540:         &appenv( {'request.role'        => $spec,
                   5541:                   'request.role.domain' => $dcdom,
                   5542:                   'request.course.sec'  => ''
                   5543:                  }
                   5544:                );
                   5545:         my $tadv=0;
                   5546:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5547:         &appenv({'request.role.adv'    => $tadv});
                   5548:     }
1.994     raeburn  5549: }
                   5550: 
1.12      www      5551: # --------------------------------------------------------------- get interface
                   5552: 
                   5553: sub get {
1.131     albertel 5554:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5555:    my $items='';
1.800     albertel 5556:    foreach my $item (@$storearr) {
                   5557:        $items.=&escape($item).'&';
1.191     harris41 5558:    }
1.12      www      5559:    $items=~s/\&$//;
1.620     albertel 5560:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5561:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5562:    my $uhome=&homeserver($uname,$udomain);
                   5563: 
1.133     albertel 5564:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5565:    my @pairs=split(/\&/,$rep);
1.273     albertel 5566:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5567:      return @pairs;
                   5568:    }
1.15      www      5569:    my %returnhash=();
1.42      www      5570:    my $i=0;
1.800     albertel 5571:    foreach my $item (@$storearr) {
                   5572:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5573:       $i++;
1.191     harris41 5574:    }
1.15      www      5575:    return %returnhash;
1.27      www      5576: }
                   5577: 
                   5578: # --------------------------------------------------------------- del interface
                   5579: 
                   5580: sub del {
1.133     albertel 5581:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5582:    my $items='';
1.800     albertel 5583:    foreach my $item (@$storearr) {
                   5584:        $items.=&escape($item).'&';
1.191     harris41 5585:    }
1.984     neumanie 5586: 
1.27      www      5587:    $items=~s/\&$//;
1.620     albertel 5588:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5589:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5590:    my $uhome=&homeserver($uname,$udomain);
                   5591:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5592: }
                   5593: 
                   5594: # -------------------------------------------------------------- dump interface
                   5595: 
1.1172.2.22  raeburn  5596: sub unserialize {
                   5597:     my ($rep, $escapedkeys) = @_;
                   5598: 
                   5599:     return {} if $rep =~ /^error/;
                   5600: 
                   5601:     my %returnhash=();
                   5602:     foreach my $item (split(/\&/,$rep)) {
                   5603:         my ($key, $value) = split(/=/, $item, 2);
                   5604:         $key = unescape($key) unless $escapedkeys;
                   5605:         next if $key =~ /^error: 2 /;
                   5606:         $returnhash{$key} = &thaw_unescape($value);
                   5607:     }
                   5608:     return \%returnhash;
                   5609: }
                   5610: 
                   5611: # see Lond::dump_with_regexp
                   5612: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5613: sub dump {
1.1172.2.22  raeburn  5614:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5615:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5616:     if (!$uname) { $uname=$env{'user.name'}; }
                   5617:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5618: 
1.1172.2.22  raeburn  5619:     my $reply;
                   5620:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   5621:         # user is hosted on this machine
                   5622:         $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  5623:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  5624:         return %{&unserialize($reply, $escapedkeys)};
                   5625:     }
1.755     albertel 5626:     if ($regexp) {
                   5627: 	$regexp=&escape($regexp);
                   5628:     } else {
                   5629: 	$regexp='.';
                   5630:     }
1.1166    raeburn  5631:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5632:     my @pairs=split(/\&/,$rep);
                   5633:     my %returnhash=();
1.1098    foxr     5634:     if (!($rep =~ /^error/ )) {
                   5635: 	foreach my $item (@pairs) {
                   5636: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  5637:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     5638: 	    next if ($key =~ /^error: 2 /);
                   5639: 	    $returnhash{$key}=&thaw_unescape($value);
                   5640: 	}
1.755     albertel 5641:     }
                   5642:     return %returnhash;
1.407     www      5643: }
                   5644: 
1.1098    foxr     5645: 
1.717     albertel 5646: # --------------------------------------------------------- dumpstore interface
                   5647: 
                   5648: sub dumpstore {
                   5649:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  5650:    # same as dump but keys must be escaped. They may contain colon separated
                   5651:    # lists of values that may themself contain colons (e.g. symbs).
                   5652:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5653: }
                   5654: 
1.407     www      5655: # -------------------------------------------------------------- keys interface
                   5656: 
                   5657: sub getkeys {
                   5658:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5659:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5660:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5661:    my $uhome=&homeserver($uname,$udomain);
                   5662:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5663:    my @keyarray=();
1.800     albertel 5664:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5665:       next if ($key =~ /^error: 2 /);
1.800     albertel 5666:       push(@keyarray,&unescape($key));
1.407     www      5667:    }
                   5668:    return @keyarray;
1.318     matthew  5669: }
                   5670: 
1.319     matthew  5671: # --------------------------------------------------------------- currentdump
                   5672: sub currentdump {
1.328     matthew  5673:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5674:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5675:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5676:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5677:    my $uhome = &homeserver($sname,$sdom);
                   5678:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  5679:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5680:    #
1.318     matthew  5681:    my %returnhash=();
1.319     matthew  5682:    #
                   5683:    if ($rep eq "unknown_cmd") { 
                   5684:        # an old lond will not know currentdump
                   5685:        # Do a dump and make it look like a currentdump
1.822     albertel 5686:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5687:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5688:        my %hash = @tmp;
                   5689:        @tmp=();
1.424     matthew  5690:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5691:    } else {
                   5692:        my @pairs=split(/\&/,$rep);
1.800     albertel 5693:        foreach my $pair (@pairs) {
                   5694:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5695:            my ($symb,$param) = split(/:/,$key);
                   5696:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5697:                                                         &thaw_unescape($value);
1.319     matthew  5698:        }
1.191     harris41 5699:    }
1.12      www      5700:    return %returnhash;
1.424     matthew  5701: }
                   5702: 
                   5703: sub convert_dump_to_currentdump{
                   5704:     my %hash = %{shift()};
                   5705:     my %returnhash;
                   5706:     # Code ripped from lond, essentially.  The only difference
                   5707:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5708:     # we might run in to problems with parameter names =~ /^v\./
                   5709:     while (my ($key,$value) = each(%hash)) {
                   5710:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5711: 	$symb  = &unescape($symb);
                   5712: 	$param = &unescape($param);
1.424     matthew  5713:         next if ($v eq 'version' || $symb eq 'keys');
                   5714:         next if (exists($returnhash{$symb}) &&
                   5715:                  exists($returnhash{$symb}->{$param}) &&
                   5716:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5717:         $returnhash{$symb}->{$param}=$value;
                   5718:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5719:     }
                   5720:     #
                   5721:     # Remove all of the keys in the hashes which keep track of
                   5722:     # the version of the parameter.
                   5723:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5724:         # use a foreach because we are going to delete from the hash.
                   5725:         foreach my $key (keys(%$param_hash)) {
                   5726:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5727:         }
                   5728:     }
                   5729:     return \%returnhash;
1.12      www      5730: }
                   5731: 
1.627     albertel 5732: # ------------------------------------------------------ critical inc interface
                   5733: 
                   5734: sub cinc {
                   5735:     return &inc(@_,'critical');
                   5736: }
                   5737: 
1.449     matthew  5738: # --------------------------------------------------------------- inc interface
                   5739: 
                   5740: sub inc {
1.627     albertel 5741:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5742:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5743:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5744:     my $uhome=&homeserver($uname,$udomain);
                   5745:     my $items='';
                   5746:     if (! ref($store)) {
                   5747:         # got a single value, so use that instead
                   5748:         $items = &escape($store).'=&';
                   5749:     } elsif (ref($store) eq 'SCALAR') {
                   5750:         $items = &escape($$store).'=&';        
                   5751:     } elsif (ref($store) eq 'ARRAY') {
                   5752:         $items = join('=&',map {&escape($_);} @{$store});
                   5753:     } elsif (ref($store) eq 'HASH') {
                   5754:         while (my($key,$value) = each(%{$store})) {
                   5755:             $items.= &escape($key).'='.&escape($value).'&';
                   5756:         }
                   5757:     }
                   5758:     $items=~s/\&$//;
1.627     albertel 5759:     if ($critical) {
                   5760: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5761:     } else {
                   5762: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5763:     }
1.449     matthew  5764: }
                   5765: 
1.12      www      5766: # --------------------------------------------------------------- put interface
                   5767: 
                   5768: sub put {
1.134     albertel 5769:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5770:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5771:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5772:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5773:    my $items='';
1.800     albertel 5774:    foreach my $item (keys(%$storehash)) {
                   5775:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5776:    }
1.12      www      5777:    $items=~s/\&$//;
1.134     albertel 5778:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5779: }
                   5780: 
1.631     albertel 5781: # ------------------------------------------------------------ newput interface
                   5782: 
                   5783: sub newput {
                   5784:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5785:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5786:    if (!$uname) { $uname=$env{'user.name'}; }
                   5787:    my $uhome=&homeserver($uname,$udomain);
                   5788:    my $items='';
                   5789:    foreach my $key (keys(%$storehash)) {
                   5790:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5791:    }
                   5792:    $items=~s/\&$//;
                   5793:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5794: }
                   5795: 
                   5796: # ---------------------------------------------------------  putstore interface
                   5797: 
1.524     raeburn  5798: sub putstore {
1.715     albertel 5799:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 5800:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5801:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5802:    my $uhome=&homeserver($uname,$udomain);
                   5803:    my $items='';
1.715     albertel 5804:    foreach my $key (keys(%$storehash)) {
                   5805:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5806:    }
1.715     albertel 5807:    $items=~s/\&$//;
1.716     albertel 5808:    my $esc_symb=&escape($symb);
                   5809:    my $esc_v=&escape($version);
1.715     albertel 5810:    my $reply =
1.716     albertel 5811:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5812: 	      $uhome);
                   5813:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5814:        # gfall back to way things use to be done
1.715     albertel 5815:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5816: 			    $uname);
1.524     raeburn  5817:    }
1.715     albertel 5818:    return $reply;
                   5819: }
                   5820: 
                   5821: sub old_putstore {
1.716     albertel 5822:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5823:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5824:     if (!$uname) { $uname=$env{'user.name'}; }
                   5825:     my $uhome=&homeserver($uname,$udomain);
                   5826:     my %newstorehash;
1.800     albertel 5827:     foreach my $item (keys(%$storehash)) {
                   5828: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5829: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5830:     }
                   5831:     my $items='';
                   5832:     my %allitems = ();
1.800     albertel 5833:     foreach my $item (keys(%newstorehash)) {
                   5834: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5835: 	    my $key = $1.':keys:'.$2;
                   5836: 	    $allitems{$key} .= $3.':';
                   5837: 	}
1.800     albertel 5838: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5839:     }
1.800     albertel 5840:     foreach my $item (keys(%allitems)) {
                   5841: 	$allitems{$item} =~ s/\:$//;
                   5842: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5843:     }
                   5844:     $items=~s/\&$//;
                   5845:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5846: }
                   5847: 
1.47      www      5848: # ------------------------------------------------------ critical put interface
                   5849: 
                   5850: sub cput {
1.134     albertel 5851:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5852:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5853:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5854:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5855:    my $items='';
1.800     albertel 5856:    foreach my $item (keys(%$storehash)) {
                   5857:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5858:    }
1.47      www      5859:    $items=~s/\&$//;
1.134     albertel 5860:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5861: }
                   5862: 
                   5863: # -------------------------------------------------------------- eget interface
                   5864: 
                   5865: sub eget {
1.133     albertel 5866:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5867:    my $items='';
1.800     albertel 5868:    foreach my $item (@$storearr) {
                   5869:        $items.=&escape($item).'&';
1.191     harris41 5870:    }
1.12      www      5871:    $items=~s/\&$//;
1.620     albertel 5872:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5873:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5874:    my $uhome=&homeserver($uname,$udomain);
                   5875:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5876:    my @pairs=split(/\&/,$rep);
                   5877:    my %returnhash=();
1.42      www      5878:    my $i=0;
1.800     albertel 5879:    foreach my $item (@$storearr) {
                   5880:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5881:       $i++;
1.191     harris41 5882:    }
1.12      www      5883:    return %returnhash;
                   5884: }
                   5885: 
1.667     albertel 5886: # ------------------------------------------------------------ tmpput interface
                   5887: sub tmpput {
1.802     raeburn  5888:     my ($storehash,$server,$context)=@_;
1.667     albertel 5889:     my $items='';
1.800     albertel 5890:     foreach my $item (keys(%$storehash)) {
                   5891: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5892:     }
                   5893:     $items=~s/\&$//;
1.802     raeburn  5894:     if (defined($context)) {
                   5895:         $items .= ':'.&escape($context);
                   5896:     }
1.667     albertel 5897:     return &reply("tmpput:$items",$server);
                   5898: }
                   5899: 
                   5900: # ------------------------------------------------------------ tmpget interface
                   5901: sub tmpget {
1.688     albertel 5902:     my ($token,$server)=@_;
                   5903:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5904:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5905:     my %returnhash;
                   5906:     foreach my $item (split(/\&/,$rep)) {
                   5907: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5908:         next if ($key =~ /^error: 2 /);
1.667     albertel 5909: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5910:     }
                   5911:     return %returnhash;
                   5912: }
                   5913: 
1.1113    raeburn  5914: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 5915: sub tmpdel {
                   5916:     my ($token,$server)=@_;
                   5917:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5918:     return &reply("tmpdel:$token",$server);
                   5919: }
                   5920: 
1.1172.2.13  raeburn  5921: # ------------------------------------------------------------ get_timebased_id
                   5922: 
                   5923: sub get_timebased_id {
                   5924:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   5925:         $maxtries) = @_;
                   5926:     my ($newid,$error,$dellock);
                   5927:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   5928:         return ('','ok','invalid call to get suffix');
                   5929:     }
                   5930: 
                   5931: # set defaults for any optional args for which values were not supplied
                   5932:     if ($who eq '') {
                   5933:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   5934:     }
                   5935:     if (!$locktries) {
                   5936:         $locktries = 3;
                   5937:     }
                   5938:     if (!$maxtries) {
                   5939:         $maxtries = 10;
                   5940:     }
                   5941: 
                   5942:     if (($cdom eq '') || ($cnum eq '')) {
                   5943:         if ($env{'request.course.id'}) {
                   5944:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5945:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5946:         }
                   5947:         if (($cdom eq '') || ($cnum eq '')) {
                   5948:             return ('','ok','call to get suffix not in course context');
                   5949:         }
                   5950:     }
                   5951: 
                   5952: # construct locking item
                   5953:     my $lockhash = {
                   5954:                       $prefix."\0".'locked_'.$keyid => $who,
                   5955:                    };
                   5956:     my $tries = 0;
                   5957: 
                   5958: # attempt to get lock on nohist_$namespace file
                   5959:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5960:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   5961:         $tries ++;
                   5962:         sleep 1;
                   5963:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5964:     }
                   5965: 
                   5966: # attempt to get unique identifier, based on current timestamp
                   5967:     if ($gotlock eq 'ok') {
                   5968:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   5969:         my $id = time;
                   5970:         $newid = $id;
                   5971:         my $idtries = 0;
                   5972:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   5973:             if ($idtype eq 'concat') {
                   5974:                 $newid = $id.$idtries;
                   5975:             } else {
                   5976:                 $newid ++;
                   5977:             }
                   5978:             $idtries ++;
                   5979:         }
                   5980:         if (!exists($inuse{$prefix."\0".$newid})) {
                   5981:             my %new_item =  (
                   5982:                               $prefix."\0".$newid => $who,
                   5983:                             );
                   5984:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   5985:                                                  $cdom,$cnum);
                   5986:             if ($putresult ne 'ok') {
                   5987:                 undef($newid);
                   5988:                 $error = 'error saving new item: '.$putresult;
                   5989:             }
                   5990:         } else {
                   5991:              $error = ('error: no unique suffix available for the new item ');
                   5992:         }
                   5993: #  remove lock
                   5994:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   5995:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   5996:     } else {
                   5997:         $error = "error: could not obtain lockfile\n";
                   5998:         $dellock = 'ok';
                   5999:     }
                   6000:     return ($newid,$dellock,$error);
                   6001: }
                   6002: 
1.765     albertel 6003: # -------------------------------------------------- portfolio access checking
                   6004: 
                   6005: sub portfolio_access {
1.766     albertel 6006:     my ($requrl) = @_;
1.765     albertel 6007:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   6008:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  6009:     if ($result) {
                   6010:         my %setters;
                   6011:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6012:             my ($startblock,$endblock) =
                   6013:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6014:             if ($startblock && $endblock) {
                   6015:                 return 'B';
                   6016:             }
                   6017:         } else {
                   6018:             my ($startblock,$endblock) =
                   6019:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6020:             if ($startblock && $endblock) {
                   6021:                 return 'B';
                   6022:             }
                   6023:         }
                   6024:     }
1.765     albertel 6025:     if ($result eq 'ok') {
1.766     albertel 6026:        return 'F';
1.765     albertel 6027:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6028:        return 'A';
1.765     albertel 6029:     }
1.766     albertel 6030:     return '';
1.765     albertel 6031: }
                   6032: 
                   6033: sub get_portfolio_access {
1.767     albertel 6034:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   6035: 
                   6036:     if (!ref($access_hash)) {
                   6037: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6038: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6039: 						   $file_name);
                   6040: 	$access_hash = $access_controls{$file_name};
                   6041:     }
                   6042: 
1.765     albertel 6043:     my ($public,$guest,@domains,@users,@courses,@groups);
                   6044:     my $now = time;
                   6045:     if (ref($access_hash) eq 'HASH') {
                   6046:         foreach my $key (keys(%{$access_hash})) {
                   6047:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6048:             if ($start > $now) {
                   6049:                 next;
                   6050:             }
                   6051:             if ($end && $end<$now) {
                   6052:                 next;
                   6053:             }
                   6054:             if ($scope eq 'public') {
                   6055:                 $public = $key;
                   6056:                 last;
                   6057:             } elsif ($scope eq 'guest') {
                   6058:                 $guest = $key;
                   6059:             } elsif ($scope eq 'domains') {
                   6060:                 push(@domains,$key);
                   6061:             } elsif ($scope eq 'users') {
                   6062:                 push(@users,$key);
                   6063:             } elsif ($scope eq 'course') {
                   6064:                 push(@courses,$key);
                   6065:             } elsif ($scope eq 'group') {
                   6066:                 push(@groups,$key);
                   6067:             }
                   6068:         }
                   6069:         if ($public) {
                   6070:             return 'ok';
                   6071:         }
                   6072:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6073:             if ($guest) {
                   6074:                 return $guest;
                   6075:             }
                   6076:         } else {
                   6077:             if (@domains > 0) {
                   6078:                 foreach my $domkey (@domains) {
                   6079:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6080:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6081:                             return 'ok';
                   6082:                         }
                   6083:                     }
                   6084:                 }
                   6085:             }
                   6086:             if (@users > 0) {
                   6087:                 foreach my $userkey (@users) {
1.865     raeburn  6088:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6089:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6090:                             if (ref($item) eq 'HASH') {
                   6091:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6092:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6093:                                     return 'ok';
                   6094:                                 }
                   6095:                             }
                   6096:                         }
                   6097:                     } 
1.765     albertel 6098:                 }
                   6099:             }
                   6100:             my %roleshash;
                   6101:             my @courses_and_groups = @courses;
                   6102:             push(@courses_and_groups,@groups); 
                   6103:             if (@courses_and_groups > 0) {
                   6104:                 my (%allgroups,%allroles); 
                   6105:                 my ($start,$end,$role,$sec,$group);
                   6106:                 foreach my $envkey (%env) {
1.1060    raeburn  6107:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6108:                         my $cid = $2.'_'.$3; 
                   6109:                         if ($1 eq 'gr') {
                   6110:                             $group = $4;
                   6111:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6112:                         } else {
                   6113:                             if ($4 eq '') {
                   6114:                                 $sec = 'none';
                   6115:                             } else {
                   6116:                                 $sec = $4;
                   6117:                             }
                   6118:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6119:                         }
1.811     albertel 6120:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6121:                         my $cid = $2.'_'.$3;
                   6122:                         if ($4 eq '') {
                   6123:                             $sec = 'none';
                   6124:                         } else {
                   6125:                             $sec = $4;
                   6126:                         }
                   6127:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6128:                     }
                   6129:                 }
                   6130:                 if (keys(%allroles) == 0) {
                   6131:                     return;
                   6132:                 }
                   6133:                 foreach my $key (@courses_and_groups) {
                   6134:                     my %content = %{$$access_hash{$key}};
                   6135:                     my $cnum = $content{'number'};
                   6136:                     my $cdom = $content{'domain'};
                   6137:                     my $cid = $cdom.'_'.$cnum;
                   6138:                     if (!exists($allroles{$cid})) {
                   6139:                         next;
                   6140:                     }    
                   6141:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6142:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6143:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6144:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6145:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6146:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6147:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6148:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6149:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6150:                                         if (grep/^all$/,@sections) {
                   6151:                                             return 'ok';
                   6152:                                         } else {
                   6153:                                             if (grep/^$sec$/,@sections) {
                   6154:                                                 return 'ok';
                   6155:                                             }
                   6156:                                         }
                   6157:                                     }
                   6158:                                 }
                   6159:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6160:                                     if (grep/^none$/,@groups) {
                   6161:                                         return 'ok';
                   6162:                                     }
                   6163:                                 } else {
                   6164:                                     if (grep/^all$/,@groups) {
                   6165:                                         return 'ok';
                   6166:                                     } 
                   6167:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6168:                                         if (grep/^$group$/,@groups) {
                   6169:                                             return 'ok';
                   6170:                                         }
                   6171:                                     }
                   6172:                                 } 
                   6173:                             }
                   6174:                         }
                   6175:                     }
                   6176:                 }
                   6177:             }
                   6178:             if ($guest) {
                   6179:                 return $guest;
                   6180:             }
                   6181:         }
                   6182:     }
                   6183:     return;
                   6184: }
                   6185: 
                   6186: sub course_group_datechecker {
                   6187:     my ($dates,$now,$status) = @_;
                   6188:     my ($start,$end) = split(/\./,$dates);
                   6189:     if (!$start && !$end) {
                   6190:         return 'ok';
                   6191:     }
                   6192:     if (grep/^active$/,@{$status}) {
                   6193:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6194:             return 'ok';
                   6195:         }
                   6196:     }
                   6197:     if (grep/^previous$/,@{$status}) {
                   6198:         if ($end > $now ) {
                   6199:             return 'ok';
                   6200:         }
                   6201:     }
                   6202:     if (grep/^future$/,@{$status}) {
                   6203:         if ($start > $now) {
                   6204:             return 'ok';
                   6205:         }
                   6206:     }
                   6207:     return; 
                   6208: }
                   6209: 
                   6210: sub parse_portfolio_url {
                   6211:     my ($url) = @_;
                   6212: 
                   6213:     my ($type,$udom,$unum,$group,$file_name);
                   6214:     
1.823     albertel 6215:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6216: 	$type = 1;
                   6217:         $udom = $1;
                   6218:         $unum = $2;
                   6219:         $file_name = $3;
1.823     albertel 6220:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6221: 	$type = 2;
                   6222:         $udom = $1;
                   6223:         $unum = $2;
                   6224:         $group = $3;
                   6225:         $file_name = $3.'/'.$4;
                   6226:     }
                   6227:     if (wantarray) {
                   6228: 	return ($type,$udom,$unum,$file_name,$group);
                   6229:     }
                   6230:     return $type;
                   6231: }
                   6232: 
                   6233: sub is_portfolio_url {
                   6234:     my ($url) = @_;
                   6235:     return scalar(&parse_portfolio_url($url));
                   6236: }
                   6237: 
1.798     raeburn  6238: sub is_portfolio_file {
                   6239:     my ($file) = @_;
1.820     raeburn  6240:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6241:         return 1;
                   6242:     }
                   6243:     return;
                   6244: }
                   6245: 
1.976     raeburn  6246: sub usertools_access {
1.1084    raeburn  6247:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6248:     my ($access,%tools);
                   6249:     if ($context eq '') {
                   6250:         $context = 'tools';
                   6251:     }
                   6252:     if ($context eq 'requestcourses') {
                   6253:         %tools = (
                   6254:                       official   => 1,
                   6255:                       unofficial => 1,
1.1006    raeburn  6256:                       community  => 1,
1.985     raeburn  6257:                  );
1.1172.2.9  raeburn  6258:     } elsif ($context eq 'requestauthor') {
                   6259:         %tools = (
                   6260:                       requestauthor => 1,
                   6261:                  );
1.985     raeburn  6262:     } else {
                   6263:         %tools = (
                   6264:                       aboutme   => 1,
                   6265:                       blog      => 1,
1.1172.2.6  raeburn  6266:                       webdav    => 1,
1.985     raeburn  6267:                       portfolio => 1,
                   6268:                  );
                   6269:     }
1.976     raeburn  6270:     return if (!defined($tools{$tool}));
                   6271: 
                   6272:     if ((!defined($udom)) || (!defined($uname))) {
                   6273:         $udom = $env{'user.domain'};
                   6274:         $uname = $env{'user.name'};
                   6275:     }
                   6276: 
1.978     raeburn  6277:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6278:         if ($action ne 'reload') {
1.985     raeburn  6279:             if ($context eq 'requestcourses') {
                   6280:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  6281:             } elsif ($context eq 'requestauthor') {
                   6282:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6283:             } else {
                   6284:                 return $env{'environment.availabletools.'.$tool};
                   6285:             }
                   6286:         }
1.976     raeburn  6287:     }
                   6288: 
1.1172.2.9  raeburn  6289:     my ($toolstatus,$inststatus,$envkey);
                   6290:     if ($context eq 'requestauthor') {
                   6291:         $envkey = $context;
                   6292:     } else {
                   6293:         $envkey = $context.'.'.$tool;
                   6294:     }
1.976     raeburn  6295: 
1.985     raeburn  6296:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6297:          ($action ne 'reload')) {
1.1172.2.9  raeburn  6298:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6299:         $inststatus = $env{'environment.inststatus'};
                   6300:     } else {
1.1084    raeburn  6301:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  6302:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6303:             $inststatus = $userenvref->{'inststatus'};
                   6304:         } else {
1.1172.2.9  raeburn  6305:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6306:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6307:             $inststatus = $userenv{'inststatus'};
                   6308:         }
1.976     raeburn  6309:     }
                   6310: 
                   6311:     if ($toolstatus ne '') {
                   6312:         if ($toolstatus) {
                   6313:             $access = 1;
                   6314:         } else {
                   6315:             $access = 0;
                   6316:         }
                   6317:         return $access;
                   6318:     }
                   6319: 
1.1084    raeburn  6320:     my ($is_adv,%domdef);
                   6321:     if (ref($is_advref) eq 'HASH') {
                   6322:         $is_adv = $is_advref->{'is_adv'};
                   6323:     } else {
                   6324:         $is_adv = &is_advanced_user($udom,$uname);
                   6325:     }
                   6326:     if (ref($domdefref) eq 'HASH') {
                   6327:         %domdef = %{$domdefref};
                   6328:     } else {
                   6329:         %domdef = &get_domain_defaults($udom);
                   6330:     }
1.976     raeburn  6331:     if (ref($domdef{$tool}) eq 'HASH') {
                   6332:         if ($is_adv) {
                   6333:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6334:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6335:                     $access = 1;
                   6336:                 } else {
                   6337:                     $access = 0;
                   6338:                 }
                   6339:                 return $access;
                   6340:             }
                   6341:         }
                   6342:         if ($inststatus ne '') {
                   6343:             my ($hasaccess,$hasnoaccess);
                   6344:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6345:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6346:                     if ($domdef{$tool}{$affiliation}) {
                   6347:                         $hasaccess = 1;
                   6348:                     } else {
                   6349:                         $hasnoaccess = 1;
                   6350:                     }
                   6351:                 }
                   6352:             }
                   6353:             if ($hasaccess || $hasnoaccess) {
                   6354:                 if ($hasaccess) {
                   6355:                     $access = 1;
                   6356:                 } elsif ($hasnoaccess) {
                   6357:                     $access = 0; 
                   6358:                 }
                   6359:                 return $access;
                   6360:             }
                   6361:         } else {
                   6362:             if ($domdef{$tool}{'default'} ne '') {
                   6363:                 if ($domdef{$tool}{'default'}) {
                   6364:                     $access = 1;
                   6365:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6366:                     $access = 0;
                   6367:                 }
                   6368:                 return $access;
                   6369:             }
                   6370:         }
                   6371:     } else {
1.1172.2.6  raeburn  6372:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6373:             $access = 1;
                   6374:         } else {
                   6375:             $access = 0;
                   6376:         }
1.976     raeburn  6377:         return $access;
                   6378:     }
                   6379: }
                   6380: 
1.1050    raeburn  6381: sub is_course_owner {
                   6382:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6383:     if (($udom eq '') || ($uname eq '')) {
                   6384:         $udom = $env{'user.domain'};
                   6385:         $uname = $env{'user.name'};
                   6386:     }
                   6387:     unless (($udom eq '') || ($uname eq '')) {
                   6388:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6389:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6390:                 return 1;
                   6391:             } else {
                   6392:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6393:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6394:                     return 1;
                   6395:                 }
                   6396:             }
                   6397:         }
                   6398:     }
                   6399:     return;
                   6400: }
                   6401: 
1.976     raeburn  6402: sub is_advanced_user {
                   6403:     my ($udom,$uname) = @_;
1.1085    raeburn  6404:     if ($udom ne '' && $uname ne '') {
                   6405:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6406:             if (wantarray) {
                   6407:                 return ($env{'user.adv'},$env{'user.author'});
                   6408:             } else {
                   6409:                 return $env{'user.adv'};
                   6410:             }
1.1085    raeburn  6411:         }
                   6412:     }
1.976     raeburn  6413:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6414:     my %allroles;
1.1128    raeburn  6415:     my ($is_adv,$is_author);
1.976     raeburn  6416:     foreach my $role (keys(%roleshash)) {
                   6417:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6418:         my $area = '/'.$tdomain.'/'.$trest;
                   6419:         if ($sec ne '') {
                   6420:             $area .= '/'.$sec;
                   6421:         }
                   6422:         if (($area ne '') && ($trole ne '')) {
                   6423:             my $spec=$trole.'.'.$area;
                   6424:             if ($trole =~ /^cr\//) {
                   6425:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6426:             } elsif ($trole ne 'gr') {
                   6427:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6428:             }
1.1128    raeburn  6429:             if ($trole eq 'au') {
                   6430:                 $is_author = 1;
                   6431:             }
1.976     raeburn  6432:         }
                   6433:     }
                   6434:     foreach my $role (keys(%allroles)) {
                   6435:         last if ($is_adv);
                   6436:         foreach my $item (split(/:/,$allroles{$role})) {
                   6437:             if ($item ne '') {
                   6438:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6439:                 if ($privilege eq 'adv') {
                   6440:                     $is_adv = 1;
                   6441:                     last;
                   6442:                 }
                   6443:             }
                   6444:         }
                   6445:     }
1.1128    raeburn  6446:     if (wantarray) {
                   6447:         return ($is_adv,$is_author);
                   6448:     }
1.976     raeburn  6449:     return $is_adv;
                   6450: }
1.798     raeburn  6451: 
1.1035    raeburn  6452: sub check_can_request {
1.1036    raeburn  6453:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6454:     my $canreq = 0;
                   6455:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6456:     my @options = ('approval','validate','autolimit');
                   6457:     my $optregex = join('|',@options);
                   6458:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6459:         foreach my $type (@{$types}) {
                   6460:             if (&usertools_access($env{'user.name'},
                   6461:                                   $env{'user.domain'},
                   6462:                                   $type,undef,'requestcourses')) {
                   6463:                 $canreq ++;
1.1036    raeburn  6464:                 if (ref($request_domains) eq 'HASH') {
                   6465:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6466:                 }
1.1035    raeburn  6467:                 if ($dom eq $env{'user.domain'}) {
                   6468:                     $can_request->{$type} = 1;
                   6469:                 }
                   6470:             }
                   6471:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6472:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6473:                 if (@curr > 0) {
1.1036    raeburn  6474:                     foreach my $item (@curr) {
                   6475:                         if (ref($request_domains) eq 'HASH') {
                   6476:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6477:                             if ($otherdom ne '') {
                   6478:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6479:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6480:                                         push(@{$request_domains->{$type}},$otherdom);
                   6481:                                     }
                   6482:                                 } else {
                   6483:                                     push(@{$request_domains->{$type}},$otherdom);
                   6484:                                 }
                   6485:                             }
                   6486:                         }
                   6487:                     }
                   6488:                     unless($dom eq $env{'user.domain'}) {
                   6489:                         $canreq ++;
1.1035    raeburn  6490:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6491:                             $can_request->{$type} = 1;
                   6492:                         }
                   6493:                     }
                   6494:                 }
                   6495:             }
                   6496:         }
                   6497:     }
                   6498:     return $canreq;
                   6499: }
                   6500: 
1.341     www      6501: # ---------------------------------------------- Custom access rule evaluation
                   6502: 
                   6503: sub customaccess {
                   6504:     my ($priv,$uri)=@_;
1.807     albertel 6505:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6506:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6507:     $udom = &LONCAPA::clean_domain($udom);
                   6508:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6509:     my $access=0;
1.800     albertel 6510:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6511: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6512: 	if ($type eq 'user') {
                   6513: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6514: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6515: 		if ($tdom) {
                   6516: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6517: 		}
1.896     albertel 6518: 		if ($tuname) {
                   6519: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6520: 		}
                   6521: 		$access=($effect eq 'allow');
                   6522: 		last;
                   6523: 	    }
                   6524: 	} else {
                   6525: 	    if ($role) {
                   6526: 		if ($role ne $urole) { next; }
                   6527: 	    }
                   6528: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6529: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6530: 		if ($tdom) {
                   6531: 		    if ($tdom ne $udom) { next; }
                   6532: 		}
                   6533: 		if ($tcrs) {
                   6534: 		    if ($tcrs ne $ucrs) { next; }
                   6535: 		}
                   6536: 		if ($tsec) {
                   6537: 		    if ($tsec ne $usec) { next; }
                   6538: 		}
                   6539: 		$access=($effect eq 'allow');
                   6540: 		last;
                   6541: 	    }
                   6542: 	    if ($realm eq '' && $role eq '') {
                   6543: 		$access=($effect eq 'allow');
                   6544: 	    }
1.402     bowersj2 6545: 	}
1.341     www      6546:     }
                   6547:     return $access;
                   6548: }
                   6549: 
1.103     harris41 6550: # ------------------------------------------------- Check for a user privilege
1.12      www      6551: 
                   6552: sub allowed {
1.810     raeburn  6553:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 6554:     my $ver_orguri=$uri;
1.439     www      6555:     $uri=&deversion($uri);
1.152     www      6556:     my $orguri=$uri;
1.52      www      6557:     $uri=&declutter($uri);
1.809     raeburn  6558: 
1.810     raeburn  6559:     if ($priv eq 'evb') {
                   6560: # Evade communication block restrictions for specified role in a course
                   6561:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6562:             return $1;
                   6563:         } else {
                   6564:             return;
                   6565:         }
                   6566:     }
                   6567: 
1.620     albertel 6568:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6569: # Free bre access to adm and meta resources
1.775     albertel 6570:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6571: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6572: 	&& ($priv eq 'bre')) {
1.14      www      6573: 	return 'F';
1.159     www      6574:     }
                   6575: 
1.545     banghart 6576: # Free bre access to user's own portfolio contents
1.714     raeburn  6577:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6578:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6579: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6580:         my %setters;
                   6581:         my ($startblock,$endblock) = 
                   6582:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6583:         if ($startblock && $endblock) {
                   6584:             return 'B';
                   6585:         } else {
                   6586:             return 'F';
                   6587:         }
1.545     banghart 6588:     }
                   6589: 
1.762     raeburn  6590: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6591:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6592:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6593:         if (exists($env{'request.course.id'})) {
                   6594:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6595:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6596:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6597:                 my $courseprivid=$env{'request.course.id'};
                   6598:                 $courseprivid=~s/\_/\//;
                   6599:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6600:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6601:                     return $1; 
1.762     raeburn  6602:                 } else {
                   6603:                     if ($env{'request.course.sec'}) {
                   6604:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6605:                     }
                   6606:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6607:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6608:                         return $2;
                   6609:                     }
1.714     raeburn  6610:                 }
                   6611:             }
                   6612:         }
                   6613:     }
                   6614: 
1.159     www      6615: # Free bre to public access
                   6616: 
                   6617:     if ($priv eq 'bre') {
1.238     www      6618:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6619: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6620:            return 'F'; 
                   6621:         }
1.238     www      6622:         if ($copyright eq 'priv') {
                   6623:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6624: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6625: 		return '';
                   6626:             }
                   6627:         }
                   6628:         if ($copyright eq 'domain') {
                   6629:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6630: 	    unless (($env{'user.domain'} eq $1) ||
                   6631:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6632: 		return '';
                   6633:             }
1.262     matthew  6634:         }
1.620     albertel 6635:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6636:             # Library role, so allow browsing of resources in this domain.
                   6637:             return 'F';
1.238     www      6638:         }
1.341     www      6639:         if ($copyright eq 'custom') {
                   6640: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6641:         }
1.14      www      6642:     }
1.264     matthew  6643:     # Domain coordinator is trying to create a course
1.620     albertel 6644:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6645:         # uri is the requested domain in this case.
                   6646:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6647:         # a role of dc for the domain in question.
1.620     albertel 6648:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6649:     }
1.29      www      6650: 
1.52      www      6651:     my $thisallowed='';
                   6652:     my $statecond=0;
                   6653:     my $courseprivid='';
                   6654: 
1.1039    raeburn  6655:     my $ownaccess;
1.1043    raeburn  6656:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6657:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6658:         if ($uri eq '') {
                   6659:             $ownaccess = 1;
                   6660:         } else {
                   6661:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6662:                 my $udom = $env{'user.domain'};
                   6663:                 my $uname = $env{'user.name'};
                   6664:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6665:                     $ownaccess = 1;
1.1040    raeburn  6666:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6667:                     unless ($uri =~ m{\.\./}) {
                   6668:                         $ownaccess = 1;
                   6669:                     }
                   6670:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6671:                     my $now = time;
                   6672:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6673:                         my $adom = $1;
                   6674:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6675:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6676:                                 my ($start,$end) = split('.',$env{$key});
                   6677:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6678:                                     $ownaccess = 1;
                   6679:                                     last;
                   6680:                                 }
                   6681:                             }
                   6682:                         }
                   6683:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6684:                         my $adom = $1;
                   6685:                         my $aname = $2;
1.1042    raeburn  6686:                         foreach my $role ('ca','aa') { 
                   6687:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6688:                                 my ($start,$end) =
                   6689:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6690:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6691:                                     $ownaccess = 1;
                   6692:                                     last;
                   6693:                                 }
1.1039    raeburn  6694:                             }
                   6695:                         }
                   6696:                     }
                   6697:                 }
                   6698:             }
                   6699:         }
                   6700:     }
                   6701: 
1.52      www      6702: # Course
                   6703: 
1.620     albertel 6704:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6705:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6706:             $thisallowed.=$1;
                   6707:         }
1.52      www      6708:     }
1.29      www      6709: 
1.52      www      6710: # Domain
                   6711: 
1.620     albertel 6712:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6713:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6714:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6715:             $thisallowed.=$1;
                   6716:         }
1.12      www      6717:     }
1.52      www      6718: 
1.1141    raeburn  6719: # User who is not author or co-author might still be able to edit
                   6720: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6721:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6722:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6723:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6724:             $thisallowed.=$1;
                   6725:         }
                   6726:     }
                   6727: 
1.52      www      6728: # Course: uri itself is a course
1.66      www      6729:     my $courseuri=$uri;
                   6730:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6731:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6732: 
1.620     albertel 6733:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6734:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6735:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6736:             $thisallowed.=$1;
                   6737:         }
1.12      www      6738:     }
1.29      www      6739: 
1.665     albertel 6740: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6741: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6742:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6743: 	$thisallowed='';
1.671     raeburn  6744:         my ($match)=&is_on_map($uri);
                   6745:         if ($match) {
                   6746:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6747:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6748:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6749:                 if (@blockers > 0) {
                   6750:                     $thisallowed = 'B';
                   6751:                 } else {
                   6752:                     $thisallowed.=$1;
                   6753:                 }
1.671     raeburn  6754:             }
                   6755:         } else {
1.705     albertel 6756:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6757:             if ($refuri) {
                   6758:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6759:                     $thisallowed='F';
1.671     raeburn  6760:                 } else {
                   6761:                     $refuri=&declutter($refuri);
                   6762:                     my ($match) = &is_on_map($refuri);
                   6763:                     if ($match) {
1.1162    raeburn  6764:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6765:                         if (@blockers > 0) {
                   6766:                             $thisallowed = 'B';
                   6767:                         } else {
                   6768:                             $thisallowed='F';
                   6769:                         }
1.671     raeburn  6770:                     }
1.669     raeburn  6771:                 }
1.671     raeburn  6772:             }
                   6773:         }
1.314     www      6774:     }
1.492     albertel 6775: 
1.766     albertel 6776:     if ($priv eq 'bre'
                   6777: 	&& $thisallowed ne 'F' 
                   6778: 	&& $thisallowed ne '2'
                   6779: 	&& &is_portfolio_url($uri)) {
                   6780: 	$thisallowed = &portfolio_access($uri);
                   6781:     }
                   6782:     
1.52      www      6783: # Full access at system, domain or course-wide level? Exit.
1.29      www      6784:     if ($thisallowed=~/F/) {
                   6785: 	return 'F';
                   6786:     }
                   6787: 
1.52      www      6788: # If this is generating or modifying users, exit with special codes
1.29      www      6789: 
1.643     www      6790:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6791: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6792: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6793: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6794: 	    unless ($auname) { return $thisallowed; }
                   6795: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6796: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6797: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6798: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6799: 	}
1.52      www      6800: 	return $thisallowed;
                   6801:     }
                   6802: #
1.103     harris41 6803: # Gathered so far: system, domain and course wide privileges
1.52      www      6804: #
                   6805: # Course: See if uri or referer is an individual resource that is part of 
                   6806: # the course
                   6807: 
1.620     albertel 6808:     if ($env{'request.course.id'}) {
1.232     www      6809: 
1.620     albertel 6810:        $courseprivid=$env{'request.course.id'};
                   6811:        if ($env{'request.course.sec'}) {
                   6812:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6813:        }
                   6814:        $courseprivid=~s/\_/\//;
                   6815:        my $checkreferer=1;
1.232     www      6816:        my ($match,$cond)=&is_on_map($uri);
                   6817:        if ($match) {
                   6818:            $statecond=$cond;
1.620     albertel 6819:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6820:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6821:                my $value = $1;
                   6822:                if ($priv eq 'bre') {
                   6823:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6824:                    if (@blockers > 0) {
                   6825:                        $thisallowed = 'B';
                   6826:                    } else {
                   6827:                        $thisallowed.=$value;
                   6828:                    }
                   6829:                } else {
                   6830:                    $thisallowed.=$value;
                   6831:                }
1.52      www      6832:                $checkreferer=0;
                   6833:            }
1.29      www      6834:        }
1.83      www      6835:        
1.148     www      6836:        if ($checkreferer) {
1.620     albertel 6837: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6838:             unless ($refuri) {
1.800     albertel 6839:                 foreach my $key (keys(%env)) {
                   6840: 		    if ($key=~/^httpref\..*\*/) {
                   6841: 			my $pattern=$key;
1.156     www      6842:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6843:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6844:                         $pattern=~s/\//\\\//g;
1.152     www      6845:                         if ($orguri=~/$pattern/) {
1.800     albertel 6846: 			    $refuri=$env{$key};
1.148     www      6847:                         }
                   6848:                     }
1.191     harris41 6849:                 }
1.148     www      6850:             }
1.232     www      6851: 
1.148     www      6852:          if ($refuri) { 
1.152     www      6853: 	  $refuri=&declutter($refuri);
1.232     www      6854:           my ($match,$cond)=&is_on_map($refuri);
                   6855:             if ($match) {
                   6856:               my $refstatecond=$cond;
1.620     albertel 6857:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6858:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6859:                   my $value = $1;
                   6860:                   if ($priv eq 'bre') {
                   6861:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6862:                       if (@blockers > 0) {
                   6863:                           $thisallowed = 'B';
                   6864:                       } else {
                   6865:                           $thisallowed.=$value;
                   6866:                       }
                   6867:                   } else {
                   6868:                       $thisallowed.=$value;
                   6869:                   }
1.53      www      6870:                   $uri=$refuri;
                   6871:                   $statecond=$refstatecond;
1.52      www      6872:               }
                   6873:           }
1.148     www      6874:         }
1.29      www      6875:        }
1.52      www      6876:    }
1.29      www      6877: 
1.52      www      6878: #
1.103     harris41 6879: # Gathered now: all privileges that could apply, and condition number
1.52      www      6880: # 
                   6881: #
                   6882: # Full or no access?
                   6883: #
1.29      www      6884: 
1.52      www      6885:     if ($thisallowed=~/F/) {
                   6886: 	return 'F';
                   6887:     }
1.29      www      6888: 
1.52      www      6889:     unless ($thisallowed) {
                   6890:         return '';
                   6891:     }
1.29      www      6892: 
1.52      www      6893: # Restrictions exist, deal with them
                   6894: #
                   6895: #   C:according to course preferences
                   6896: #   R:according to resource settings
                   6897: #   L:unless locked
                   6898: #   X:according to user session state
                   6899: #
                   6900: 
                   6901: # Possibly locked functionality, check all courses
1.54      www      6902: # Locks might take effect only after 10 minutes cache expiration for other
                   6903: # courses, and 2 minutes for current course
1.52      www      6904: 
                   6905:     my $envkey;
                   6906:     if ($thisallowed=~/L/) {
1.1000    raeburn  6907:         foreach $envkey (keys(%env)) {
1.54      www      6908:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6909:                my $courseid=$2;
                   6910:                my $roleid=$1.'.'.$2;
1.92      www      6911:                $courseid=~s/^\///;
1.54      www      6912:                my $expiretime=600;
1.620     albertel 6913:                if ($env{'request.role'} eq $roleid) {
1.54      www      6914: 		  $expiretime=120;
                   6915:                }
                   6916: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   6917:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 6918:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 6919: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      6920:                }
1.620     albertel 6921:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6922:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   6923: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   6924:                        &log($env{'user.domain'},$env{'user.name'},
                   6925:                             $env{'user.home'},
1.57      www      6926:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      6927:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6928:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6929: 		       return '';
                   6930:                    }
                   6931:                }
1.620     albertel 6932:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6933:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   6934: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   6935:                        &log($env{'user.domain'},$env{'user.name'},
                   6936:                             $env{'user.home'},
1.57      www      6937:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      6938:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6939:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6940: 		       return '';
                   6941:                    }
                   6942:                }
                   6943: 	   }
1.29      www      6944:        }
1.52      www      6945:     }
                   6946:    
                   6947: #
                   6948: # Rest of the restrictions depend on selected course
                   6949: #
                   6950: 
1.620     albertel 6951:     unless ($env{'request.course.id'}) {
1.766     albertel 6952: 	if ($thisallowed eq 'A') {
                   6953: 	    return 'A';
1.814     raeburn  6954:         } elsif ($thisallowed eq 'B') {
                   6955:             return 'B';
1.766     albertel 6956: 	} else {
                   6957: 	    return '1';
                   6958: 	}
1.52      www      6959:     }
1.29      www      6960: 
1.52      www      6961: #
                   6962: # Now user is definitely in a course
                   6963: #
1.53      www      6964: 
                   6965: 
                   6966: # Course preferences
                   6967: 
                   6968:    if ($thisallowed=~/C/) {
1.620     albertel 6969:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   6970:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   6971:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 6972: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  6973: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6974: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6975: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   6976: 			$env{'request.course.id'});
                   6977: 	   }
1.237     www      6978:            return '';
                   6979:        }
                   6980: 
1.620     albertel 6981:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 6982: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  6983: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6984: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   6985: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   6986: 			$env{'request.course.id'});
                   6987: 	   }
1.54      www      6988:            return '';
                   6989:        }
1.53      www      6990:    }
                   6991: 
                   6992: # Resource preferences
                   6993: 
                   6994:    if ($thisallowed=~/R/) {
1.620     albertel 6995:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 6996:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  6997: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6998: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6999: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7000: 	   }
                   7001: 	   return '';
1.54      www      7002:        }
1.53      www      7003:    }
1.30      www      7004: 
1.246     www      7005: # Restricted by state or randomout?
1.30      www      7006: 
1.52      www      7007:    if ($thisallowed=~/X/) {
1.620     albertel 7008:       if ($env{'acc.randomout'}) {
1.579     albertel 7009: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7010:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7011:             return ''; 
                   7012:          }
1.247     www      7013:       }
                   7014:       if (&condval($statecond)) {
1.52      www      7015: 	 return '2';
                   7016:       } else {
                   7017:          return '';
                   7018:       }
                   7019:    }
1.30      www      7020: 
1.766     albertel 7021:     if ($thisallowed eq 'A') {
                   7022: 	return 'A';
1.814     raeburn  7023:     } elsif ($thisallowed eq 'B') {
                   7024:         return 'B';
1.766     albertel 7025:     }
1.52      www      7026:    return 'F';
1.232     www      7027: }
1.1162    raeburn  7028: 
1.1172.2.13  raeburn  7029: # ------------------------------------------- Check construction space access
                   7030: 
                   7031: sub constructaccess {
                   7032:     my ($url,$setpriv)=@_;
                   7033: 
                   7034: # We do not allow editing of previous versions of files
                   7035:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7036: 
                   7037: # Get username and domain from URL
                   7038:     my ($ownername,$ownerdomain,$ownerhome);
                   7039: 
                   7040:     ($ownerdomain,$ownername) =
                   7041:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
                   7042: 
                   7043: # The URL does not really point to any authorspace, forget it
                   7044:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7045: 
                   7046: # Now we need to see if the user has access to the authorspace of
                   7047: # $ownername at $ownerdomain
                   7048: 
                   7049:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7050: # Real author for this?
                   7051:        $ownerhome = $env{'user.home'};
                   7052:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7053:           return ($ownername,$ownerdomain,$ownerhome);
                   7054:        }
                   7055:     } else {
                   7056: # Co-author for this?
                   7057:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7058:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7059:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7060:             return ($ownername,$ownerdomain,$ownerhome);
                   7061:         }
                   7062:     }
                   7063: 
                   7064: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7065: # we might as well leave
                   7066:    unless ($setpriv) { return ''; }
                   7067: 
                   7068: # Backdoor access?
                   7069:     my $allowed=&allowed('eco',$ownerdomain);
                   7070: # Nope
                   7071:     unless ($allowed) { return ''; }
                   7072: # Looks like we may have access, but could be locked by the owner of the construction space
                   7073:     if ($allowed eq 'U') {
                   7074:         my %blocked=&get('environment',['domcoord.author'],
                   7075:                          $ownerdomain,$ownername);
                   7076: # Is blocked by owner
                   7077:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7078:     }
                   7079:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7080: # Grant temporary access
                   7081:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  7082:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  7083:         if (!$update) { $update = $then; }
                   7084:         my $refresh=$env{'user.refresh.time'};
                   7085:         if (!$refresh) { $refresh = $update; }
                   7086:         my $now = time;
                   7087:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7088:                            $now,'ca','constructaccess');
                   7089:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7090:         return($ownername,$ownerdomain,$ownerhome);
                   7091:     }
                   7092: # No business here
                   7093:     return '';
                   7094: }
                   7095: 
1.1162    raeburn  7096: sub get_comm_blocks {
                   7097:     my ($cdom,$cnum) = @_;
                   7098:     if ($cdom eq '' || $cnum eq '') {
                   7099:         return unless ($env{'request.course.id'});
                   7100:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7101:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7102:     }
                   7103:     my %commblocks;
                   7104:     my $hashid=$cdom.'_'.$cnum;
                   7105:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7106:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7107:         %commblocks = %{$blocksref};
                   7108:     } else {
                   7109:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7110:         my $cachetime = 600;
                   7111:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7112:     }
                   7113:     return %commblocks;
                   7114: }
                   7115: 
                   7116: sub has_comm_blocking {
                   7117:     my ($priv,$symb,$uri,$blocks) = @_;
                   7118:     return unless ($env{'request.course.id'});
                   7119:     return unless ($priv eq 'bre');
                   7120:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7121:     my %commblocks;
                   7122:     if (ref($blocks) eq 'HASH') {
                   7123:         %commblocks = %{$blocks};
                   7124:     } else {
                   7125:         %commblocks = &get_comm_blocks();
                   7126:     }
                   7127:     return unless (keys(%commblocks) > 0);
                   7128:     if (!$symb) { $symb=&symbread($uri,1); }
                   7129:     my ($map,$resid,undef)=&decode_symb($symb);
                   7130:     my %tocheck = (
                   7131:                     maps      => $map,
                   7132:                     resources => $symb,
                   7133:                   );
                   7134:     my @blockers;
                   7135:     my $now = time;
1.1163    raeburn  7136:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1162    raeburn  7137:     foreach my $block (keys(%commblocks)) {
                   7138:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7139:             my ($start,$end) = ($1,$2);
                   7140:             if ($start <= $now && $end >= $now) {
                   7141:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7142:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7143:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7144:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
                   7145:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7146:                                     push(@blockers,$block);
                   7147:                                 }
                   7148:                             }
                   7149:                         }
                   7150:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7151:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
                   7152:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
                   7153:                                     push(@blockers,$block);
                   7154:                                 }
                   7155:                             }
                   7156:                         }
                   7157:                     }
                   7158:                 }
                   7159:             }
                   7160:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7161:             my $item = $1;
1.1163    raeburn  7162:             my @to_test;
1.1162    raeburn  7163:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7164:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7165:                     my $check_interval;
                   7166:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
                   7167:                         my @interval;
                   7168:                         my $type = 'map';
                   7169:                         if ($item eq 'course') {
                   7170:                             $type = 'course';
                   7171:                             @interval=&EXT("resource.0.interval");
                   7172:                         } else {
                   7173:                             if ($item =~ /___\d+___/) {
                   7174:                                 $type = 'resource';
                   7175:                                 @interval=&EXT("resource.0.interval",$item);
1.1163    raeburn  7176:                                 if (ref($navmap)) {                        
                   7177:                                     my $res = $navmap->getBySymb($item); 
                   7178:                                     push(@to_test,$res);
                   7179:                                 }
1.1162    raeburn  7180:                             } else {
                   7181:                                 my $mapsymb = &symbread($item,1);
                   7182:                                 if ($mapsymb) {
                   7183:                                     if (ref($navmap)) {
                   7184:                                         my $mapres = $navmap->getBySymb($mapsymb);
1.1163    raeburn  7185:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
                   7186:                                         foreach my $res (@to_test) {
1.1162    raeburn  7187:                                             my $symb = $res->symb();
                   7188:                                             next if ($symb eq $mapsymb);
                   7189:                                             if ($symb ne '') {
                   7190:                                                 @interval=&EXT("resource.0.interval",$symb);
                   7191:                                                 last;
                   7192:                                             }
                   7193:                                         }
                   7194:                                     }
                   7195:                                 }
                   7196:                             }
                   7197:                         }
                   7198:                         if ($interval[0] =~ /\d+/) {
                   7199:                             my $first_access;
                   7200:                             if ($type eq 'resource') {
                   7201:                                 $first_access=&get_first_access($interval[1],$item);
                   7202:                             } elsif ($type eq 'map') {
                   7203:                                 $first_access=&get_first_access($interval[1],undef,$item);
                   7204:                             } else {
                   7205:                                 $first_access=&get_first_access($interval[1]);
                   7206:                             }
                   7207:                             if ($first_access) {
                   7208:                                 my $timesup = $first_access+$interval[0];
                   7209:                                 if ($timesup > $now) {
1.1163    raeburn  7210:                                     foreach my $res (@to_test) {
                   7211:                                         if ($res->is_problem()) {
                   7212:                                             if ($res->completable()) {
                   7213:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7214:                                                     push(@blockers,$block);
                   7215:                                                 }
                   7216:                                                 last;
                   7217:                                             }
                   7218:                                         }
1.1162    raeburn  7219:                                     }
                   7220:                                 }
                   7221:                             }
                   7222:                         }
                   7223:                     }
                   7224:                 }
                   7225:             }
                   7226:         }
                   7227:     }
                   7228:     return @blockers;
                   7229: }
                   7230: 
                   7231: sub check_docs_block {
                   7232:     my ($docsblock,$tocheck) =@_;
                   7233:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
                   7234:         return;
                   7235:     }
                   7236:     if (ref($docsblock->{'maps'}) eq 'HASH') {
                   7237:         if ($tocheck->{'maps'}) {
                   7238:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
                   7239:                 return 1;
                   7240:             }
                   7241:         }
                   7242:     }
                   7243:     if (ref($docsblock->{'resources'}) eq 'HASH') {
                   7244:         if ($tocheck->{'resources'}) {
                   7245:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
                   7246:                 return 1;
                   7247:             }
                   7248:         }
                   7249:     }
                   7250:     return;
                   7251: }
                   7252: 
1.1133    foxr     7253: #
                   7254: #   Removes the versino from a URI and
                   7255: #   splits it in to its filename and path to the filename.
                   7256: #   Seems like File::Basename could have done this more clearly.
                   7257: #   Parameters:
                   7258: #      $uri   - input URI
                   7259: #   Returns:
                   7260: #     Two element list consisting of 
                   7261: #     $pathname  - the URI up to and excluding the trailing /
                   7262: #     $filename  - The part of the URI following the last /
                   7263: #  NOTE:
                   7264: #    Another realization of this is simply:
                   7265: #    use File::Basename;
                   7266: #    ...
                   7267: #    $uri = shift;
                   7268: #    $filename = basename($uri);
                   7269: #    $path     = dirname($uri);
                   7270: #    return ($filename, $path);
                   7271: #
                   7272: #     The implementation below is probably faster however.
                   7273: #
1.710     albertel 7274: sub split_uri_for_cond {
                   7275:     my $uri=&deversion(&declutter(shift));
                   7276:     my @uriparts=split(/\//,$uri);
                   7277:     my $filename=pop(@uriparts);
                   7278:     my $pathname=join('/',@uriparts);
                   7279:     return ($pathname,$filename);
                   7280: }
1.232     www      7281: # --------------------------------------------------- Is a resource on the map?
                   7282: 
                   7283: sub is_on_map {
1.710     albertel 7284:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7285:     #Trying to find the conditional for the file
1.620     albertel 7286:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7287: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7288:     if ($match) {
1.289     bowersj2 7289: 	return (1,$1);
                   7290:     } else {
1.434     www      7291: 	return (0,0);
1.289     bowersj2 7292:     }
1.12      www      7293: }
                   7294: 
1.427     www      7295: # --------------------------------------------------------- Get symb from alias
                   7296: 
                   7297: sub get_symb_from_alias {
                   7298:     my $symb=shift;
                   7299:     my ($map,$resid,$url)=&decode_symb($symb);
                   7300: # Already is a symb
                   7301:     if ($url) { return $symb; }
                   7302: # Must be an alias
                   7303:     my $aliassymb='';
                   7304:     my %bighash;
1.620     albertel 7305:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7306:                             &GDBM_READER(),0640)) {
                   7307:         my $rid=$bighash{'mapalias_'.$symb};
                   7308: 	if ($rid) {
                   7309: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7310: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7311: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7312: 	}
                   7313:         untie %bighash;
                   7314:     }
                   7315:     return $aliassymb;
                   7316: }
                   7317: 
1.12      www      7318: # ----------------------------------------------------------------- Define Role
                   7319: 
                   7320: sub definerole {
                   7321:   if (allowed('mcr','/')) {
                   7322:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7323:     foreach my $role (split(':',$sysrole)) {
                   7324: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7325:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7326:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7327: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7328:                return "refused:s:$crole&$cqual"; 
                   7329:             }
                   7330:         }
1.191     harris41 7331:     }
1.800     albertel 7332:     foreach my $role (split(':',$domrole)) {
                   7333: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7334:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7335:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7336: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7337:                return "refused:d:$crole&$cqual"; 
                   7338:             }
                   7339:         }
1.191     harris41 7340:     }
1.800     albertel 7341:     foreach my $role (split(':',$courole)) {
                   7342: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7343:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7344:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7345: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7346:                return "refused:c:$crole&$cqual"; 
                   7347:             }
                   7348:         }
1.191     harris41 7349:     }
1.620     albertel 7350:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7351:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7352: 	        "rolesdef_$rolename=".
                   7353:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7354:     return reply($command,$env{'user.home'});
1.12      www      7355:   } else {
                   7356:     return 'refused';
                   7357:   }
1.105     harris41 7358: }
                   7359: 
                   7360: # ---------------- Make a metadata query against the network of library servers
                   7361: 
                   7362: sub metadata_query {
1.244     matthew  7363:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 7364:     my %rhash;
1.845     albertel 7365:     my %libserv = &all_library();
1.244     matthew  7366:     my @server_list = (defined($server_array) ? @$server_array
                   7367:                                               : keys(%libserv) );
                   7368:     for my $server (@server_list) {
1.118     harris41 7369: 	unless ($custom or $customshow) {
                   7370: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   7371: 	    $rhash{$server}=$reply;
                   7372: 	}
                   7373: 	else {
                   7374: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   7375: 			     &escape($custom).':'.&escape($customshow),
                   7376: 			     $server);
                   7377: 	    $rhash{$server}=$reply;
                   7378: 	}
1.112     harris41 7379:     }
1.118     harris41 7380:     return \%rhash;
1.240     www      7381: }
                   7382: 
                   7383: # ----------------------------------------- Send log queries and wait for reply
                   7384: 
                   7385: sub log_query {
                   7386:     my ($uname,$udom,$query,%filters)=@_;
                   7387:     my $uhome=&homeserver($uname,$udom);
                   7388:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7389:     my $uhost=&hostname($uhome);
1.800     albertel 7390:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7391:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7392:                        $uhome);
1.479     albertel 7393:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7394:     return get_query_reply($queryid);
                   7395: }
                   7396: 
1.818     raeburn  7397: # -------------------------- Update MySQL table for portfolio file
                   7398: 
                   7399: sub update_portfolio_table {
1.821     raeburn  7400:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7401:     if ($group ne '') {
                   7402:         $file_name =~s /^\Q$group\E//;
                   7403:     }
1.818     raeburn  7404:     my $homeserver = &homeserver($uname,$udom);
                   7405:     my $queryid=
1.821     raeburn  7406:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7407:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7408:     my $reply = &get_query_reply($queryid);
                   7409:     return $reply;
                   7410: }
                   7411: 
1.899     raeburn  7412: # -------------------------- Update MySQL allusers table
                   7413: 
                   7414: sub update_allusers_table {
                   7415:     my ($uname,$udom,$names) = @_;
                   7416:     my $homeserver = &homeserver($uname,$udom);
                   7417:     my $queryid=
                   7418:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7419:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7420:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7421:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7422:                'generation='.&escape($names->{'generation'}).'%%'.
                   7423:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7424:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7425:     return;
1.899     raeburn  7426: }
                   7427: 
1.508     raeburn  7428: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7429: 
                   7430: sub fetch_enrollment_query {
1.511     raeburn  7431:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  7432:     my $homeserver;
1.547     raeburn  7433:     my $maxtries = 1;
1.508     raeburn  7434:     if ($context eq 'automated') {
                   7435:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  7436:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7437:     } else {
                   7438:         $homeserver = &homeserver($cnum,$dom);
                   7439:     }
1.838     albertel 7440:     my $host=&hostname($homeserver);
1.506     raeburn  7441:     my $cmd = '';
1.1000    raeburn  7442:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7443:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7444:     }
                   7445:     $cmd =~ s/%%$//;
                   7446:     $cmd = &escape($cmd);
                   7447:     my $query = 'fetchenrollment';
1.620     albertel 7448:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7449:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7450:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7451:         return 'error: '.$queryid;
                   7452:     }
1.506     raeburn  7453:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7454:     my $tries = 1;
                   7455:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7456:         $reply = &get_query_reply($queryid);
                   7457:         $tries ++;
                   7458:     }
1.526     raeburn  7459:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7460:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7461:     } else {
1.901     albertel 7462:         my @responses = split(/:/,$reply);
1.515     raeburn  7463:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7464:             foreach my $line (@responses) {
                   7465:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7466:                 $$replyref{$key} = $value;
                   7467:             }
                   7468:         } else {
1.1117    foxr     7469:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7470:             foreach my $line (@responses) {
                   7471:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7472:                 $$replyref{$key} = $value;
                   7473:                 if ($value > 0) {
1.800     albertel 7474:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7475:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7476:                         my $destname = $pathname.'/'.$filename;
                   7477:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7478:                         if ($xml_classlist =~ /^error/) {
                   7479:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7480:                         } else {
1.506     raeburn  7481:                             if ( open(FILE,">$destname") ) {
                   7482:                                 print FILE &unescape($xml_classlist);
                   7483:                                 close(FILE);
1.526     raeburn  7484:                             } else {
                   7485:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7486:                             }
                   7487:                         }
                   7488:                     }
                   7489:                 }
                   7490:             }
                   7491:         }
                   7492:         return 'ok';
                   7493:     }
                   7494:     return 'error';
                   7495: }
                   7496: 
1.242     www      7497: sub get_query_reply {
                   7498:     my $queryid=shift;
1.1117    foxr     7499:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7500:     my $reply='';
                   7501:     for (1..100) {
                   7502: 	sleep 2;
                   7503:         if (-e $replyfile.'.end') {
1.448     albertel 7504: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7505: 		$reply = join('',<$fh>);
                   7506: 		close($fh);
1.240     www      7507: 	   } else { return 'error: reply_file_error'; }
1.242     www      7508:            return &unescape($reply);
                   7509: 	}
1.240     www      7510:     }
1.242     www      7511:     return 'timeout:'.$queryid;
1.240     www      7512: }
                   7513: 
                   7514: sub courselog_query {
1.241     www      7515: #
                   7516: # possible filters:
                   7517: # url: url or symb
                   7518: # username
                   7519: # domain
                   7520: # action: view, submit, grade
                   7521: # start: timestamp
                   7522: # end: timestamp
                   7523: #
1.240     www      7524:     my (%filters)=@_;
1.620     albertel 7525:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7526:     if ($filters{'url'}) {
                   7527: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7528:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7529:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7530:     }
1.620     albertel 7531:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7532:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7533:     return &log_query($cname,$cdom,'courselog',%filters);
                   7534: }
                   7535: 
                   7536: sub userlog_query {
1.858     raeburn  7537: #
                   7538: # possible filters:
                   7539: # action: log check role
                   7540: # start: timestamp
                   7541: # end: timestamp
                   7542: #
1.240     www      7543:     my ($uname,$udom,%filters)=@_;
                   7544:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7545: }
                   7546: 
1.506     raeburn  7547: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7548: 
                   7549: sub auto_run {
1.508     raeburn  7550:     my ($cnum,$cdom) = @_;
1.876     raeburn  7551:     my $response = 0;
                   7552:     my $settings;
                   7553:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7554:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7555:         $settings = $domconfig{'autoenroll'};
                   7556:         if ($settings->{'run'} eq '1') {
                   7557:             $response = 1;
                   7558:         }
                   7559:     } else {
1.934     raeburn  7560:         my $homeserver;
                   7561:         if (&is_course($cdom,$cnum)) {
                   7562:             $homeserver = &homeserver($cnum,$cdom);
                   7563:         } else {
                   7564:             $homeserver = &domain($cdom,'primary');
                   7565:         }
                   7566:         if ($homeserver ne 'no_host') {
                   7567:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7568:         }
1.876     raeburn  7569:     }
1.506     raeburn  7570:     return $response;
                   7571: }
1.776     albertel 7572: 
1.506     raeburn  7573: sub auto_get_sections {
1.508     raeburn  7574:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7575:     my $homeserver;
                   7576:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7577:         $homeserver = &homeserver($cnum,$cdom);
                   7578:     }
                   7579:     if (!defined($homeserver)) { 
                   7580:         if ($cdom =~ /^$match_domain$/) {
                   7581:             $homeserver = &domain($cdom,'primary');
                   7582:         }
                   7583:     }
                   7584:     my @secs;
                   7585:     if (defined($homeserver)) {
                   7586:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7587:         unless ($response eq 'refused') {
                   7588:             @secs = split(/:/,$response);
                   7589:         }
1.506     raeburn  7590:     }
                   7591:     return @secs;
                   7592: }
1.776     albertel 7593: 
1.506     raeburn  7594: sub auto_new_course {
1.1099    raeburn  7595:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7596:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7597:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7598:     return $response;
                   7599: }
1.776     albertel 7600: 
1.506     raeburn  7601: sub auto_validate_courseID {
1.508     raeburn  7602:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7603:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7604:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7605:     return $response;
                   7606: }
1.776     albertel 7607: 
1.1007    raeburn  7608: sub auto_validate_instcode {
1.1020    raeburn  7609:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7610:     my ($homeserver,$response);
                   7611:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7612:         $homeserver = &homeserver($cnum,$cdom);
                   7613:     }
                   7614:     if (!defined($homeserver)) {
                   7615:         if ($cdom =~ /^$match_domain$/) {
                   7616:             $homeserver = &domain($cdom,'primary');
                   7617:         }
                   7618:     }
1.1065    raeburn  7619:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7620:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  7621:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   7622:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  7623: }
                   7624: 
1.506     raeburn  7625: sub auto_create_password {
1.873     raeburn  7626:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7627:     my ($homeserver,$response);
1.506     raeburn  7628:     my $create_passwd = 0;
                   7629:     my $authchk = '';
1.873     raeburn  7630:     if ($udom =~ /^$match_domain$/) {
                   7631:         $homeserver = &domain($udom,'primary');
                   7632:     }
                   7633:     if ($homeserver eq '') {
                   7634:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7635:             $homeserver = &homeserver($cnum,$cdom);
                   7636:         }
                   7637:     }
                   7638:     if ($homeserver eq '') {
                   7639:         $authchk = 'nodomain';
1.506     raeburn  7640:     } else {
1.873     raeburn  7641:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   7642:         if ($response eq 'refused') {
                   7643:             $authchk = 'refused';
                   7644:         } else {
1.901     albertel 7645:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  7646:         }
1.506     raeburn  7647:     }
                   7648:     return ($authparam,$create_passwd,$authchk);
                   7649: }
                   7650: 
1.706     raeburn  7651: sub auto_photo_permission {
                   7652:     my ($cnum,$cdom,$students) = @_;
                   7653:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 7654:     my ($outcome,$perm_reqd,$conditions) = 
                   7655: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 7656:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7657: 	return (undef,undef);
                   7658:     }
1.706     raeburn  7659:     return ($outcome,$perm_reqd,$conditions);
                   7660: }
                   7661: 
                   7662: sub auto_checkphotos {
                   7663:     my ($uname,$udom,$pid) = @_;
                   7664:     my $homeserver = &homeserver($uname,$udom);
                   7665:     my ($result,$resulttype);
                   7666:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 7667: 				   &escape($uname).':'.&escape($pid),
                   7668: 				   $homeserver));
1.709     albertel 7669:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7670: 	return (undef,undef);
                   7671:     }
1.706     raeburn  7672:     if ($outcome) {
                   7673:         ($result,$resulttype) = split(/:/,$outcome);
                   7674:     } 
                   7675:     return ($result,$resulttype);
                   7676: }
                   7677: 
                   7678: sub auto_photochoice {
                   7679:     my ($cnum,$cdom) = @_;
                   7680:     my $homeserver = &homeserver($cnum,$cdom);
                   7681:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 7682: 						       &escape($cdom),
                   7683: 						       $homeserver)));
1.709     albertel 7684:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7685: 	return (undef,undef);
                   7686:     }
1.706     raeburn  7687:     return ($update,$comment);
                   7688: }
                   7689: 
                   7690: sub auto_photoupdate {
                   7691:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   7692:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 7693:     my $host=&hostname($homeserver);
1.706     raeburn  7694:     my $cmd = '';
                   7695:     my $maxtries = 1;
1.800     albertel 7696:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   7697:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  7698:     }
                   7699:     $cmd =~ s/%%$//;
                   7700:     $cmd = &escape($cmd);
                   7701:     my $query = 'institutionalphotos';
                   7702:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7703:     unless ($queryid=~/^\Q$host\E\_/) {
                   7704:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7705:         return 'error: '.$queryid;
                   7706:     }
                   7707:     my $reply = &get_query_reply($queryid);
                   7708:     my $tries = 1;
                   7709:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7710:         $reply = &get_query_reply($queryid);
                   7711:         $tries ++;
                   7712:     }
                   7713:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7714:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7715:     } else {
                   7716:         my @responses = split(/:/,$reply);
                   7717:         my $outcome = shift(@responses); 
                   7718:         foreach my $item (@responses) {
                   7719:             my ($key,$value) = split(/=/,$item);
                   7720:             $$photo{$key} = $value;
                   7721:         }
                   7722:         return $outcome;
                   7723:     }
                   7724:     return 'error';
                   7725: }
                   7726: 
1.521     raeburn  7727: sub auto_instcode_format {
1.793     albertel 7728:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7729: 	$cat_order) = @_;
1.521     raeburn  7730:     my $courses = '';
1.772     raeburn  7731:     my @homeservers;
1.521     raeburn  7732:     if ($caller eq 'global') {
1.841     albertel 7733: 	my %servers = &get_servers($codedom,'library');
                   7734: 	foreach my $tryserver (keys(%servers)) {
                   7735: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7736: 		push(@homeservers,$tryserver);
                   7737: 	    }
1.584     raeburn  7738:         }
1.1022    raeburn  7739:     } elsif ($caller eq 'requests') {
                   7740:         if ($codedom =~ /^$match_domain$/) {
                   7741:             my $chome = &domain($codedom,'primary');
                   7742:             unless ($chome eq 'no_host') {
                   7743:                 push(@homeservers,$chome);
                   7744:             }
                   7745:         }
1.521     raeburn  7746:     } else {
1.772     raeburn  7747:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7748:     }
1.793     albertel 7749:     foreach my $code (keys(%{$instcodes})) {
                   7750:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7751:     }
                   7752:     chop($courses);
1.772     raeburn  7753:     my $ok_response = 0;
                   7754:     my $response;
                   7755:     while (@homeservers > 0 && $ok_response == 0) {
                   7756:         my $server = shift(@homeservers); 
                   7757:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7758:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7759:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7760: 		split(/:/,$response);
1.772     raeburn  7761:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7762:             push(@{$codetitles},&str2array($codetitles_str));
                   7763:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   7764:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   7765:             $ok_response = 1;
                   7766:         }
                   7767:     }
                   7768:     if ($ok_response) {
1.521     raeburn  7769:         return 'ok';
1.772     raeburn  7770:     } else {
                   7771:         return $response;
1.521     raeburn  7772:     }
                   7773: }
                   7774: 
1.792     raeburn  7775: sub auto_instcode_defaults {
                   7776:     my ($domain,$returnhash,$code_order) = @_;
                   7777:     my @homeservers;
1.841     albertel 7778: 
                   7779:     my %servers = &get_servers($domain,'library');
                   7780:     foreach my $tryserver (keys(%servers)) {
                   7781: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7782: 	    push(@homeservers,$tryserver);
                   7783: 	}
1.792     raeburn  7784:     }
1.841     albertel 7785: 
1.792     raeburn  7786:     my $response;
1.841     albertel 7787:     foreach my $server (@homeservers) {
1.792     raeburn  7788:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 7789:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   7790: 	
                   7791: 	foreach my $pair (split(/\&/,$response)) {
                   7792: 	    my ($name,$value)=split(/\=/,$pair);
                   7793: 	    if ($name eq 'code_order') {
                   7794: 		@{$code_order} = split(/\&/,&unescape($value));
                   7795: 	    } else {
                   7796: 		$returnhash->{&unescape($name)}=&unescape($value);
                   7797: 	    }
                   7798: 	}
                   7799: 	return 'ok';
1.792     raeburn  7800:     }
1.841     albertel 7801: 
                   7802:     return $response;
1.1003    raeburn  7803: }
                   7804: 
                   7805: sub auto_possible_instcodes {
1.1007    raeburn  7806:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   7807:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   7808:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   7809:         return;
                   7810:     }
1.1003    raeburn  7811:     my (@homeservers,$uhome);
                   7812:     if (defined(&domain($domain,'primary'))) {
                   7813:         $uhome=&domain($domain,'primary');
                   7814:         push(@homeservers,&domain($domain,'primary'));
                   7815:     } else {
                   7816:         my %servers = &get_servers($domain,'library');
                   7817:         foreach my $tryserver (keys(%servers)) {
                   7818:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7819:                 push(@homeservers,$tryserver);
                   7820:             }
                   7821:         }
                   7822:     }
                   7823:     my $response;
                   7824:     foreach my $server (@homeservers) {
                   7825:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   7826:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  7827:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   7828:             split(':',$response);
                   7829:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   7830:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  7831:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  7832:             my ($name,$value)=split('=',$item);
                   7833:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7834:         }
                   7835:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  7836:             my ($name,$value)=split('=',$item);
                   7837:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7838:         }
                   7839:         return 'ok';
                   7840:     }
                   7841:     return $response;
                   7842: }
1.792     raeburn  7843: 
1.1010    raeburn  7844: sub auto_courserequest_checks {
                   7845:     my ($dom) = @_;
1.1020    raeburn  7846:     my ($homeserver,%validations);
                   7847:     if ($dom =~ /^$match_domain$/) {
                   7848:         $homeserver = &domain($dom,'primary');
                   7849:     }
                   7850:     unless ($homeserver eq 'no_host') {
                   7851:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   7852:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7853:             my @items = split(/&/,$response);
                   7854:             foreach my $item (@items) {
                   7855:                 my ($key,$value) = split('=',$item);
                   7856:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   7857:             }
                   7858:         }
                   7859:     }
1.1010    raeburn  7860:     return %validations; 
                   7861: }
                   7862: 
1.1020    raeburn  7863: sub auto_courserequest_validation {
                   7864:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   7865:     my ($homeserver,$response);
                   7866:     if ($dom =~ /^$match_domain$/) {
                   7867:         $homeserver = &domain($dom,'primary');
                   7868:     }
                   7869:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  7870:           
1.1020    raeburn  7871:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  7872:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  7873:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   7874:                                     $homeserver));
                   7875:     }
                   7876:     return $response;
                   7877: }
                   7878: 
1.777     albertel 7879: sub auto_validate_class_sec {
1.918     raeburn  7880:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  7881:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  7882:     my $ownerlist;
                   7883:     if (ref($owners) eq 'ARRAY') {
                   7884:         $ownerlist = join(',',@{$owners});
                   7885:     } else {
                   7886:         $ownerlist = $owners;
                   7887:     }
1.773     raeburn  7888:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  7889:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  7890:     return $response;
                   7891: }
                   7892: 
1.679     raeburn  7893: # ------------------------------------------------------- Course Group routines
                   7894: 
                   7895: sub get_coursegroups {
1.809     raeburn  7896:     my ($cdom,$cnum,$group,$namespace) = @_;
                   7897:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  7898: }
                   7899: 
1.679     raeburn  7900: sub modify_coursegroup {
                   7901:     my ($cdom,$cnum,$groupsettings) = @_;
                   7902:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   7903: }
                   7904: 
1.809     raeburn  7905: sub toggle_coursegroup_status {
                   7906:     my ($cdom,$cnum,$group,$action) = @_;
                   7907:     my ($from_namespace,$to_namespace);
                   7908:     if ($action eq 'delete') {
                   7909:         $from_namespace = 'coursegroups';
                   7910:         $to_namespace = 'deleted_groups';
                   7911:     } else {
                   7912:         $from_namespace = 'deleted_groups';
                   7913:         $to_namespace = 'coursegroups';
                   7914:     }
                   7915:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  7916:     if (my $tmp = &error(%curr_group)) {
                   7917:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   7918:         return ('read error',$tmp);
                   7919:     } else {
                   7920:         my %savedsettings = %curr_group; 
1.809     raeburn  7921:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  7922:         my $deloutcome;
                   7923:         if ($result eq 'ok') {
1.809     raeburn  7924:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  7925:         } else {
                   7926:             return ('write error',$result);
                   7927:         }
                   7928:         if ($deloutcome eq 'ok') {
                   7929:             return 'ok';
                   7930:         } else {
                   7931:             return ('delete error',$deloutcome);
                   7932:         }
                   7933:     }
                   7934: }
                   7935: 
1.679     raeburn  7936: sub modify_group_roles {
1.957     raeburn  7937:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  7938:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   7939:     my $role = 'gr/'.&escape($userprivs);
                   7940:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  7941:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  7942:     if ($result eq 'ok') {
                   7943:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   7944:     }
1.679     raeburn  7945:     return $result;
                   7946: }
                   7947: 
                   7948: sub modify_coursegroup_membership {
                   7949:     my ($cdom,$cnum,$membership) = @_;
                   7950:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   7951:     return $result;
                   7952: }
                   7953: 
1.682     raeburn  7954: sub get_active_groups {
                   7955:     my ($udom,$uname,$cdom,$cnum) = @_;
                   7956:     my $now = time;
                   7957:     my %groups = ();
                   7958:     foreach my $key (keys(%env)) {
1.811     albertel 7959:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  7960:             my ($start,$end) = split(/\./,$env{$key});
                   7961:             if (($end!=0) && ($end<$now)) { next; }
                   7962:             if (($start!=0) && ($start>$now)) { next; }
                   7963:             if ($1 eq $cdom && $2 eq $cnum) {
                   7964:                 $groups{$3} = $env{$key} ;
                   7965:             }
                   7966:         }
                   7967:     }
                   7968:     return %groups;
                   7969: }
                   7970: 
1.683     raeburn  7971: sub get_group_membership {
                   7972:     my ($cdom,$cnum,$group) = @_;
                   7973:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   7974: }
                   7975: 
                   7976: sub get_users_groups {
                   7977:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  7978:     my @usersgroups;
1.683     raeburn  7979:     my $cachetime=1800;
                   7980: 
                   7981:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  7982:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   7983:     if (defined($cached)) {
1.734     albertel 7984:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  7985:     } else {  
                   7986:         $grouplist = '';
1.816     raeburn  7987:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  7988:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  7989:         my $access_end = $env{'course.'.$courseid.
                   7990:                               '.default_enrollment_end_date'};
                   7991:         my $now = time;
                   7992:         foreach my $key (keys(%roleshash)) {
                   7993:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   7994:                 my $group = $1;
                   7995:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   7996:                     my $start = $2;
                   7997:                     my $end = $1;
                   7998:                     if ($start == -1) { next; } # deleted from group
                   7999:                     if (($start!=0) && ($start>$now)) { next; }
                   8000:                     if (($end!=0) && ($end<$now)) {
                   8001:                         if ($access_end && $access_end < $now) {
                   8002:                             if ($access_end - $end < 86400) {
                   8003:                                 push(@usersgroups,$group);
1.733     raeburn  8004:                             }
                   8005:                         }
1.817     raeburn  8006:                         next;
1.733     raeburn  8007:                     }
1.817     raeburn  8008:                     push(@usersgroups,$group);
1.683     raeburn  8009:                 }
                   8010:             }
                   8011:         }
1.817     raeburn  8012:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8013:         $grouplist = join(':',@usersgroups);
                   8014:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8015:     }
1.733     raeburn  8016:     return @usersgroups;
1.683     raeburn  8017: }
                   8018: 
                   8019: sub devalidate_getgroups_cache {
                   8020:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8021:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8022: 
1.683     raeburn  8023:     my $hashid="$udom:$uname:$courseid";
                   8024:     &devalidate_cache_new('getgroups',$hashid);
                   8025: }
                   8026: 
1.12      www      8027: # ------------------------------------------------------------------ Plain Text
                   8028: 
                   8029: sub plaintext {
1.988     raeburn  8030:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8031:     if ($short =~ m{^cr/}) {
1.758     albertel 8032: 	return (split('/',$short))[-1];
                   8033:     }
1.742     raeburn  8034:     if (!defined($cid)) {
                   8035:         $cid = $env{'request.course.id'};
                   8036:     }
                   8037:     my %rolenames = (
1.1008    raeburn  8038:                       Course    => 'std',
                   8039:                       Community => 'alt1',
1.742     raeburn  8040:                     );
1.1037    raeburn  8041:     if ($cid ne '') {
                   8042:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8043:             unless ($forcedefault) {
                   8044:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8045:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8046:                 return &Apache::lonlocal::mt($roletext);
                   8047:             }
                   8048:         }
                   8049:     }
                   8050:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8051:         (defined($rolenames{$type})) && 
                   8052:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8053:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8054:     } elsif ($cid ne '') {
                   8055:         my $crstype = $env{'course.'.$cid.'.type'};
                   8056:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8057:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8058:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8059:         }
1.742     raeburn  8060:     }
1.1037    raeburn  8061:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8062: }
                   8063: 
                   8064: # ----------------------------------------------------------------- Assign Role
                   8065: 
                   8066: sub assignrole {
1.957     raeburn  8067:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8068:         $context)=@_;
1.21      www      8069:     my $mrole;
                   8070:     if ($role =~ /^cr\//) {
1.393     www      8071:         my $cwosec=$url;
1.811     albertel 8072:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8073: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8074:            my $refused = 1;
                   8075:            if ($context eq 'requestcourses') {
                   8076:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8077:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8078:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8079:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8080:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8081:                            if ($crsenv{'internal.courseowner'} eq
                   8082:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8083:                                $refused = '';
                   8084:                            }
                   8085:                        }
                   8086:                    }
                   8087:                }
                   8088:            }
                   8089:            if ($refused) {
                   8090:                &logthis('Refused custom assignrole: '.
                   8091:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8092:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8093:                return 'refused';
                   8094:            }
1.104     www      8095:         }
1.21      www      8096:         $mrole='cr';
1.678     raeburn  8097:     } elsif ($role =~ /^gr\//) {
                   8098:         my $cwogrp=$url;
1.811     albertel 8099:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8100:         unless (&allowed('mdg',$cwogrp)) {
                   8101:             &logthis('Refused group assignrole: '.
                   8102:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   8103:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   8104:             return 'refused';
                   8105:         }
                   8106:         $mrole='gr';
1.21      www      8107:     } else {
1.82      www      8108:         my $cwosec=$url;
1.811     albertel 8109:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  8110:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   8111:             my $refused;
                   8112:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   8113:                 if (!(&allowed('c'.$role,$url))) {
                   8114:                     $refused = 1;
                   8115:                 }
                   8116:             } else {
                   8117:                 $refused = 1;
                   8118:             }
1.947     raeburn  8119:             if ($refused) {
1.1045    raeburn  8120:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8121:                 if (!$selfenroll && $context eq 'course') {
                   8122:                     my %crsenv;
                   8123:                     if ($role eq 'cc' || $role eq 'co') {
                   8124:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8125:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   8126:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   8127:                                 if ($crsenv{'internal.courseowner'} eq 
                   8128:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8129:                                     $refused = '';
                   8130:                                 }
                   8131:                             }
                   8132:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   8133:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   8134:                                 if ($crsenv{'internal.courseowner'} eq 
                   8135:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8136:                                     $refused = '';
                   8137:                                 }
                   8138:                             }
                   8139:                         }
                   8140:                     }
                   8141:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8142:                     $refused = '';
1.1017    raeburn  8143:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8144:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8145:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8146:                         my $wrongcc;
                   8147:                         if ($cnum =~ /^$match_community$/) {
                   8148:                             $wrongcc = 1 if ($role eq 'cc');
                   8149:                         } else {
                   8150:                             $wrongcc = 1 if ($role eq 'co');
                   8151:                         }
                   8152:                         unless ($wrongcc) {
                   8153:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8154:                             if ($crsenv{'internal.courseowner'} eq 
                   8155:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8156:                                 $refused = '';
                   8157:                             }
1.1017    raeburn  8158:                         }
                   8159:                     }
1.1172.2.9  raeburn  8160:                 } elsif ($context eq 'requestauthor') {
                   8161:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   8162:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8163:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8164:                             $refused = '';
                   8165:                         } else {
                   8166:                             my %domdefaults = &get_domain_defaults($udom);
                   8167:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   8168:                                 my $checkbystatus;
                   8169:                                 if ($env{'user.adv'}) {
                   8170:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8171:                                     if ($disposition eq 'automatic') {
                   8172:                                         $refused = '';
                   8173:                                     } elsif ($disposition eq '') {
                   8174:                                         $checkbystatus = 1;
                   8175:                                     }
                   8176:                                 } else {
                   8177:                                     $checkbystatus = 1;
                   8178:                                 }
                   8179:                                 if ($checkbystatus) {
                   8180:                                     if ($env{'environment.inststatus'}) {
                   8181:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8182:                                         foreach my $type (@inststatuses) {
                   8183:                                             if (($type ne '') &&
                   8184:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   8185:                                                 $refused = '';
                   8186:                                             }
                   8187:                                         }
                   8188:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8189:                                         $refused = '';
                   8190:                                     }
                   8191:                                 }
                   8192:                             }
                   8193:                         }
                   8194:                     }
1.1017    raeburn  8195:                 }
                   8196:                 if ($refused) {
1.947     raeburn  8197:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8198:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8199: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8200:                     return 'refused';
                   8201:                 }
1.932     raeburn  8202:             }
1.1131    raeburn  8203:         } elsif ($role eq 'au') {
                   8204:             if ($url ne '/'.$udom.'/') {
                   8205:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8206:                          ' to assign author role for '.$uname.':'.$udom.
                   8207:                          ' in domain: '.$url.' refused (wrong domain).');
                   8208:                 return 'refused';
                   8209:             }
1.104     www      8210:         }
1.21      www      8211:         $mrole=$role;
                   8212:     }
1.620     albertel 8213:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8214:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8215:     if ($end) { $command.='_'.$end; }
1.21      www      8216:     if ($start) {
                   8217: 	if ($end) { 
1.81      www      8218:            $command.='_'.$start; 
1.21      www      8219:         } else {
1.81      www      8220:            $command.='_0_'.$start;
1.21      www      8221:         }
                   8222:     }
1.739     raeburn  8223:     my $origstart = $start;
                   8224:     my $origend = $end;
1.957     raeburn  8225:     my $delflag;
1.357     www      8226: # actually delete
                   8227:     if ($deleteflag) {
1.373     www      8228: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8229: # modify command to delete the role
1.620     albertel 8230:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8231:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8232: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8233: # set start and finish to negative values for userrolelog
                   8234:            $start=-1;
                   8235:            $end=-1;
1.957     raeburn  8236:            $delflag = 1;
1.357     www      8237:         }
                   8238:     }
                   8239: # send command
1.349     www      8240:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8241: # log new user role if status is ok
1.349     www      8242:     if ($answer eq 'ok') {
1.663     raeburn  8243: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  8244:         if (($role eq 'cc') || ($role eq 'in') ||
                   8245:             ($role eq 'ep') || ($role eq 'ad') ||
                   8246:             ($role eq 'ta') || ($role eq 'st') ||
                   8247:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8248:             ($role eq 'co')) {
1.1172.2.13  raeburn  8249: # for course roles, perform group memberships changes triggered by role change.
                   8250:             unless ($role =~ /^gr/) {
                   8251:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8252:                                                  $origstart,$selfenroll,$context);
                   8253:             }
1.1172.2.9  raeburn  8254:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8255:                            $selfenroll,$context);
                   8256:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8257:                  ($role eq 'au') || ($role eq 'dc')) {
                   8258:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8259:                            $context);
                   8260:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8261:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8262:                              $context);
                   8263:         }
1.1053    raeburn  8264:         if ($role eq 'cc') {
                   8265:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8266:         }
1.349     www      8267:     }
                   8268:     return $answer;
1.169     harris41 8269: }
                   8270: 
1.1053    raeburn  8271: sub autoupdate_coowners {
                   8272:     my ($url,$end,$start,$uname,$udom) = @_;
                   8273:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8274:     if (($cdom ne '') && ($cnum ne '')) {
                   8275:         my $now = time;
                   8276:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8277:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8278:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8279:             my $instcode = $coursehash{'internal.coursecode'};
                   8280:             if ($instcode ne '') {
1.1056    raeburn  8281:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8282:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8283:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8284:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8285:                         if ($result eq 'valid') {
                   8286:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8287:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8288:                                     push(@newcoowners,$coowner);
                   8289:                                 }
                   8290:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8291:                                     push(@newcoowners,$uname.':'.$udom);
                   8292:                                 }
                   8293:                                 @newcoowners = sort(@newcoowners);
                   8294:                             } else {
                   8295:                                 push(@newcoowners,$uname.':'.$udom);
                   8296:                             }
                   8297:                         } else {
                   8298:                             if ($coursehash{'internal.co-owners'}) {
                   8299:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8300:                                     unless ($coowner eq $uname.':'.$udom) {
                   8301:                                         push(@newcoowners,$coowner);
                   8302:                                     }
                   8303:                                 }
                   8304:                                 unless (@newcoowners > 0) {
                   8305:                                     $delcoowners = 1;
                   8306:                                     $coowners = '';
                   8307:                                 }
                   8308:                             }
                   8309:                         }
                   8310:                         if (@newcoowners || $delcoowners) {
                   8311:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8312:                                             $delcoowners,@newcoowners);
                   8313:                         }
                   8314:                     }
                   8315:                 }
                   8316:             }
                   8317:         }
                   8318:     }
                   8319: }
                   8320: 
                   8321: sub store_coowners {
                   8322:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8323:     my $cid = $cdom.'_'.$cnum;
                   8324:     my ($coowners,$delresult,$putresult);
                   8325:     if (@newcoowners) {
                   8326:         $coowners = join(',',@newcoowners);
                   8327:         my %coownershash = (
                   8328:                             'internal.co-owners' => $coowners,
                   8329:                            );
                   8330:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8331:         if ($putresult eq 'ok') {
                   8332:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8333:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8334:             }
                   8335:         }
                   8336:     }
                   8337:     if ($delcoowners) {
                   8338:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8339:         if ($delresult eq 'ok') {
                   8340:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8341:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8342:             }
                   8343:         }
                   8344:     }
                   8345:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8346:         my %crsinfo =
                   8347:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8348:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8349:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8350:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8351:         }
                   8352:     }
                   8353: }
                   8354: 
1.169     harris41 8355: # -------------------------------------------------- Modify user authentication
1.197     www      8356: # Overrides without validation
                   8357: 
1.169     harris41 8358: sub modifyuserauth {
                   8359:     my ($udom,$uname,$umode,$upass)=@_;
                   8360:     my $uhome=&homeserver($uname,$udom);
1.197     www      8361:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8362:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8363:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8364:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8365:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8366: 		     &escape($upass),$uhome);
1.620     albertel 8367:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8368:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8369:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8370:     &log($udom,,$uname,$uhome,
1.620     albertel 8371:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8372:                                      $env{'user.name'}.', '.$umode.
1.197     www      8373:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8374:     unless ($reply eq 'ok') {
1.197     www      8375:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8376: 	return 'error: '.$reply;
                   8377:     }   
1.170     harris41 8378:     return 'ok';
1.80      www      8379: }
                   8380: 
1.81      www      8381: # --------------------------------------------------------------- Modify a user
1.80      www      8382: 
1.81      www      8383: sub modifyuser {
1.206     matthew  8384:     my ($udom,    $uname, $uid,
                   8385:         $umode,   $upass, $first,
                   8386:         $middle,  $last,  $gene,
1.1058    raeburn  8387:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8388:     $udom= &LONCAPA::clean_domain($udom);
                   8389:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8390:     my $showcandelete = 'none';
                   8391:     if (ref($candelete) eq 'ARRAY') {
                   8392:         if (@{$candelete} > 0) {
                   8393:             $showcandelete = join(', ',@{$candelete});
                   8394:         }
                   8395:     }
1.81      www      8396:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8397:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8398: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8399:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8400:                                      ' desiredhome not specified'). 
1.620     albertel 8401:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8402:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8403:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8404:     my $newuser;
                   8405:     if ($uhome eq 'no_host') {
                   8406:         $newuser = 1;
                   8407:     }
1.80      www      8408: # ----------------------------------------------------------------- Create User
1.406     albertel 8409:     if (($uhome eq 'no_host') && 
                   8410: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8411:         my $unhome='';
1.844     albertel 8412:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8413:             $unhome = $desiredhome;
1.620     albertel 8414: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8415: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8416:         } else { # load balancing routine for determining $unhome
1.81      www      8417:             my $loadm=10000000;
1.841     albertel 8418: 	    my %servers = &get_servers($udom,'library');
                   8419: 	    foreach my $tryserver (keys(%servers)) {
                   8420: 		my $answer=reply('load',$tryserver);
                   8421: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8422: 		    $loadm=$answer;
                   8423: 		    $unhome=$tryserver;
                   8424: 		}
1.80      www      8425: 	    }
                   8426:         }
                   8427:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8428: 	    return 'error: unable to find a home server for '.$uname.
                   8429:                    ' in domain '.$udom;
1.80      www      8430:         }
                   8431:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8432:                          &escape($upass),$unhome);
                   8433: 	unless ($reply eq 'ok') {
                   8434:             return 'error: '.$reply;
                   8435:         }   
1.230     stredwic 8436:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8437:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8438: 	    return 'error: unable verify users home machine.';
1.80      www      8439:         }
1.209     matthew  8440:     }   # End of creation of new user
1.80      www      8441: # ---------------------------------------------------------------------- Add ID
                   8442:     if ($uid) {
                   8443:        $uid=~tr/A-Z/a-z/;
                   8444:        my %uidhash=&idrget($udom,$uname);
1.196     www      8445:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8446:          && (!$forceid)) {
1.80      www      8447: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8448: 	      return 'error: user id "'.$uid.'" does not match '.
                   8449:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8450:           }
                   8451:        } else {
                   8452: 	  &idput($udom,($uname => $uid));
                   8453:        }
                   8454:     }
                   8455: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8456:     my @tmp=&get('environment',
1.899     raeburn  8457: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8458:                     'permanentemail','inststatus'],
1.134     albertel 8459: 		   $udom,$uname);
1.1075    raeburn  8460:     my (%names,%oldnames);
1.313     matthew  8461:     if ($tmp[0] =~ m/^error:.*/) { 
                   8462:         %names=(); 
                   8463:     } else {
                   8464:         %names = @tmp;
1.1075    raeburn  8465:         %oldnames = %names;
1.313     matthew  8466:     }
1.388     www      8467: #
1.1058    raeburn  8468: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8469: # of users did not contain them), do not overwrite existing values
                   8470: # unless field is in $candelete array ref.  
                   8471: #
                   8472: 
                   8473:     my @fields = ('firstname','middlename','lastname','generation',
                   8474:                   'permanentemail','id');
                   8475:     my %newvalues;
                   8476:     if (ref($candelete) eq 'ARRAY') {
                   8477:         foreach my $field (@fields) {
                   8478:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8479:                 if ($field eq 'firstname') {
                   8480:                     $names{$field} = $first;
                   8481:                 } elsif ($field eq 'middlename') {
                   8482:                     $names{$field} = $middle;
                   8483:                 } elsif ($field eq 'lastname') {
                   8484:                     $names{$field} = $last;
                   8485:                 } elsif ($field eq 'generation') { 
                   8486:                     $names{$field} = $gene;
                   8487:                 } elsif ($field eq 'permanentemail') {
                   8488:                     $names{$field} = $email;
                   8489:                 } elsif ($field eq 'id') {
                   8490:                     $names{$field}  = $uid;
                   8491:                 }
                   8492:             }
                   8493:         }
                   8494:     }
1.388     www      8495:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  8496:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      8497:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  8498:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      8499:     if ($email) {
                   8500:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  8501:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      8502:     }
1.899     raeburn  8503:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  8504:     if (defined($inststatus)) {
                   8505:         $names{'inststatus'} = '';
                   8506:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   8507:         if (ref($usertypes) eq 'HASH') {
                   8508:             my @okstatuses; 
                   8509:             foreach my $item (split(/:/,$inststatus)) {
                   8510:                 if (defined($usertypes->{$item})) {
                   8511:                     push(@okstatuses,$item);  
                   8512:                 }
                   8513:             }
                   8514:             if (@okstatuses) {
                   8515:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   8516:             }
                   8517:         }
                   8518:     }
1.1075    raeburn  8519:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  8520:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  8521:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  8522:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   8523:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   8524:     } else {
                   8525:         $logmsg .= ' during self creation';
                   8526:     }
1.1075    raeburn  8527:     my $changed;
                   8528:     if ($newuser) {
                   8529:         $changed = 1;
                   8530:     } else {
                   8531:         foreach my $field (@fields) {
                   8532:             if ($names{$field} ne $oldnames{$field}) {
                   8533:                 $changed = 1;
                   8534:                 last;
                   8535:             }
                   8536:         }
                   8537:     }
                   8538:     unless ($changed) {
                   8539:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   8540:         &logthis($logmsg);
                   8541:         return 'ok';
                   8542:     }
                   8543:     my $reply = &put('environment', \%names, $udom,$uname);
                   8544:     if ($reply ne 'ok') { 
                   8545:         return 'error: '.$reply;
                   8546:     }
1.1087    raeburn  8547:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   8548:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   8549:     }
1.1075    raeburn  8550:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   8551:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   8552:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  8553:     &logthis($logmsg);
1.134     albertel 8554:     return 'ok';
1.80      www      8555: }
                   8556: 
1.81      www      8557: # -------------------------------------------------------------- Modify student
1.80      www      8558: 
1.81      www      8559: sub modifystudent {
                   8560:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  8561:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.19  raeburn  8562:         $selfenroll,$context,$inststatus,$credits)=@_;
1.455     albertel 8563:     if (!$cid) {
1.620     albertel 8564: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8565: 	    return 'not_in_class';
                   8566: 	}
1.80      www      8567:     }
                   8568: # --------------------------------------------------------------- Make the user
1.81      www      8569:     my $reply=&modifyuser
1.209     matthew  8570: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  8571:          $desiredhome,$email,$inststatus);
1.80      www      8572:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  8573:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  8574:     # student's environment
1.297     matthew  8575:     $uid = undef if (!$forceid);
1.455     albertel 8576:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  8577: 					$gene,$usec,$end,$start,$type,$locktype,
                   8578:                                         $cid,$selfenroll,$context,$credits);
1.297     matthew  8579:     return $reply;
                   8580: }
                   8581: 
                   8582: sub modify_student_enrollment {
1.1172.2.23  raeburn  8583:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
                   8584:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455     albertel 8585:     my ($cdom,$cnum,$chome);
                   8586:     if (!$cid) {
1.620     albertel 8587: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8588: 	    return 'not_in_class';
                   8589: 	}
1.620     albertel 8590: 	$cdom=$env{'course.'.$cid.'.domain'};
                   8591: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 8592:     } else {
                   8593: 	($cdom,$cnum)=split(/_/,$cid);
                   8594:     }
1.620     albertel 8595:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 8596:     if (!$chome) {
1.457     raeburn  8597: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  8598:     }
1.455     albertel 8599:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  8600:     # Make sure the user exists
1.81      www      8601:     my $uhome=&homeserver($uname,$udom);
                   8602:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8603: 	return 'error: no such user';
                   8604:     }
1.297     matthew  8605:     # Get student data if we were not given enough information
                   8606:     if (!defined($first)  || $first  eq '' || 
                   8607:         !defined($last)   || $last   eq '' || 
                   8608:         !defined($uid)    || $uid    eq '' || 
                   8609:         !defined($middle) || $middle eq '' || 
                   8610:         !defined($gene)   || $gene   eq '') {
1.294     matthew  8611:         # They did not supply us with enough data to enroll the student, so
                   8612:         # we need to pick up more information.
1.297     matthew  8613:         my %tmp = &get('environment',
1.294     matthew  8614:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  8615:                        ,$udom,$uname);
                   8616: 
1.800     albertel 8617:         #foreach my $key (keys(%tmp)) {
                   8618:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 8619:         #}
1.294     matthew  8620:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   8621:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   8622:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  8623:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  8624:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   8625:     }
1.556     albertel 8626:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  8627:     my $user = "$uname:$udom";
                   8628:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 8629:     my $reply=cput('classlist',
1.1148    raeburn  8630: 		   {$user => 
1.1172.2.19  raeburn  8631: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487     albertel 8632: 		   $cdom,$cnum);
1.1148    raeburn  8633:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   8634:         &devalidate_getsection_cache($udom,$uname,$cid);
                   8635:     } else { 
1.81      www      8636: 	return 'error: '.$reply;
                   8637:     }
1.297     matthew  8638:     # Add student role to user
1.83      www      8639:     my $uurl='/'.$cid;
1.81      www      8640:     $uurl=~s/\_/\//g;
                   8641:     if ($usec) {
                   8642: 	$uurl.='/'.$usec;
                   8643:     }
1.1148    raeburn  8644:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   8645:                              $selfenroll,$context);
                   8646:     if ($result ne 'ok') {
                   8647:         if ($old_entry{$user} ne '') {
                   8648:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   8649:         } else {
                   8650:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   8651:         }
                   8652:     }
                   8653:     return $result; 
1.21      www      8654: }
                   8655: 
1.556     albertel 8656: sub format_name {
                   8657:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   8658:     my $name;
                   8659:     if ($first ne 'lastname') {
                   8660: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   8661:     } else {
                   8662: 	if ($lastname=~/\S/) {
                   8663: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   8664: 	    $name=~s/\s+,/,/;
                   8665: 	} else {
                   8666: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   8667: 	}
                   8668:     }
                   8669:     $name=~s/^\s+//;
                   8670:     $name=~s/\s+$//;
                   8671:     $name=~s/\s+/ /g;
                   8672:     return $name;
                   8673: }
                   8674: 
1.84      www      8675: # ------------------------------------------------- Write to course preferences
                   8676: 
                   8677: sub writecoursepref {
                   8678:     my ($courseid,%prefs)=@_;
                   8679:     $courseid=~s/^\///;
                   8680:     $courseid=~s/\_/\//g;
                   8681:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   8682:     my $chome=homeserver($cnum,$cdomain);
                   8683:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   8684: 	return 'error: no such course';
                   8685:     }
                   8686:     my $cstring='';
1.800     albertel 8687:     foreach my $pref (keys(%prefs)) {
                   8688: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 8689:     }
1.84      www      8690:     $cstring=~s/\&$//;
                   8691:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   8692: }
                   8693: 
                   8694: # ---------------------------------------------------------- Make/modify course
                   8695: 
                   8696: sub createcourse {
1.741     raeburn  8697:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  8698:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      8699:     $url=&declutter($url);
                   8700:     my $cid='';
1.1028    raeburn  8701:     if ($context eq 'requestcourses') {
                   8702:         my $can_create = 0;
                   8703:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   8704:         if ($udom eq $ownerdom) {
                   8705:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   8706:                                   $context)) {
                   8707:                 $can_create = 1;
                   8708:             }
                   8709:         } else {
                   8710:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   8711:                                            $category);
                   8712:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   8713:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   8714:                 if (@curr > 0) {
                   8715:                     my @options = qw(approval validate autolimit);
                   8716:                     my $optregex = join('|',@options);
                   8717:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   8718:                         $can_create = 1;
                   8719:                     }
                   8720:                 }
                   8721:             }
                   8722:         }
                   8723:         if ($can_create) {
                   8724:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   8725:                 unless (&allowed('ccc',$udom)) {
                   8726:                     return 'refused'; 
                   8727:                 }
1.1017    raeburn  8728:             }
                   8729:         } else {
                   8730:             return 'refused';
                   8731:         }
1.1028    raeburn  8732:     } elsif (!&allowed('ccc',$udom)) {
                   8733:         return 'refused';
1.84      www      8734:     }
1.1011    raeburn  8735: # --------------------------------------------------------------- Get Unique ID
                   8736:     my $uname;
                   8737:     if ($cnum =~ /^$match_courseid$/) {
                   8738:         my $chome=&homeserver($cnum,$udom,'true');
                   8739:         if (($chome eq '') || ($chome eq 'no_host')) {
                   8740:             $uname = $cnum;
                   8741:         } else {
1.1038    raeburn  8742:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8743:         }
                   8744:     } else {
1.1038    raeburn  8745:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8746:     }
                   8747:     return $uname if ($uname =~ /^error/);
                   8748: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  8749:     if (!defined($course_server)) {
                   8750:         if (defined(&domain($udom,'primary'))) {
                   8751:             $course_server = &domain($udom,'primary');
                   8752:         } else {
                   8753:             $course_server = $env{'user.home'}; 
                   8754:         }
                   8755:     }
                   8756:     my %host_servers =
                   8757:         &Apache::lonnet::get_servers($udom,'library');
                   8758:     unless ($host_servers{$course_server}) {
                   8759:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  8760:     }
1.84      www      8761: # ------------------------------------------------------------- Make the course
                   8762:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  8763:                       $course_server);
1.84      www      8764:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  8765:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      8766:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8767: 	return 'error: no such course';
                   8768:     }
1.271     www      8769: # ----------------------------------------------------------------- Course made
1.516     raeburn  8770: # log existence
1.1029    raeburn  8771:     my $now = time;
1.918     raeburn  8772:     my $newcourse = {
                   8773:                     $udom.'_'.$uname => {
1.921     raeburn  8774:                                      description => $description,
                   8775:                                      inst_code   => $inst_code,
                   8776:                                      owner       => $course_owner,
                   8777:                                      type        => $crstype,
1.1029    raeburn  8778:                                      creator     => $env{'user.name'}.':'.
                   8779:                                                     $env{'user.domain'},
                   8780:                                      created     => $now,
                   8781:                                      context     => $context,
1.918     raeburn  8782:                                                 },
                   8783:                     };
1.921     raeburn  8784:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      8785: # set toplevel url
1.271     www      8786:     my $topurl=$url;
                   8787:     unless ($nonstandard) {
                   8788: # ------------------------------------------ For standard courses, make top url
                   8789:         my $mapurl=&clutter($url);
1.278     www      8790:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 8791:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      8792: <map>
                   8793: <resource id="1" type="start"></resource>
                   8794: <resource id="2" src="$mapurl"></resource>
                   8795: <resource id="3" type="finish"></resource>
                   8796: <link index="1" from="1" to="2"></link>
                   8797: <link index="2" from="2" to="3"></link>
                   8798: </map>
                   8799: ENDINITMAP
                   8800:         $topurl=&declutter(
1.638     albertel 8801:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      8802:                           );
                   8803:     }
                   8804: # ----------------------------------------------------------- Write preferences
1.84      www      8805:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  8806:                      ('description'              => $description,
                   8807:                       'url'                      => $topurl,
                   8808:                       'internal.creator'         => $env{'user.name'}.':'.
                   8809:                                                     $env{'user.domain'},
                   8810:                       'internal.created'         => $now,
                   8811:                       'internal.creationcontext' => $context)
                   8812:                     );
1.84      www      8813:     return '/'.$udom.'/'.$uname;
                   8814: }
                   8815: 
1.1011    raeburn  8816: # ------------------------------------------------------------------- Create ID
                   8817: sub generate_coursenum {
1.1038    raeburn  8818:     my ($udom,$crstype) = @_;
1.1011    raeburn  8819:     my $domdesc = &domain($udom);
                   8820:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  8821:     my $first;
                   8822:     if ($crstype eq 'Community') {
                   8823:         $first = '0';
                   8824:     } else {
                   8825:         $first = int(1+rand(9)); 
                   8826:     } 
                   8827:     my $uname=$first.
1.1011    raeburn  8828:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8829:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8830:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8831: # ----------------------------------------------- Make sure that does not exist
                   8832:     my $uhome=&homeserver($uname,$udom,'true');
                   8833:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  8834:         if ($crstype eq 'Community') {
                   8835:             $first = '0';
                   8836:         } else {
                   8837:             $first = int(1+rand(9));
                   8838:         }
                   8839:         $uname=$first.
1.1011    raeburn  8840:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8841:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8842:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8843:         $uhome=&homeserver($uname,$udom,'true');
                   8844:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   8845:             return 'error: unable to generate unique course-ID';
                   8846:         }
                   8847:     }
                   8848:     return $uname;
                   8849: }
                   8850: 
1.813     albertel 8851: sub is_course {
1.1167    droeschl 8852:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   8853:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   8854: 
                   8855:     return unless $cdom and $cnum;
                   8856: 
                   8857:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   8858:         '.');
                   8859: 
1.1172.2.23  raeburn  8860:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 8861:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 8862: }
                   8863: 
1.1015    raeburn  8864: sub store_userdata {
                   8865:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  8866:     my $result;
1.1016    raeburn  8867:     if ($datakey ne '') {
1.1013    raeburn  8868:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  8869:             if ($udom eq '' || $uname eq '') {
                   8870:                 $udom = $env{'user.domain'};
                   8871:                 $uname = $env{'user.name'};
                   8872:             }
                   8873:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  8874:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   8875:                 $result = 'error: no_host';
                   8876:             } else {
                   8877:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   8878:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   8879: 
                   8880:                 my $namevalue='';
                   8881:                 foreach my $key (keys(%{$storehash})) {
                   8882:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   8883:                 }
                   8884:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  8885:                 unless ($namespace eq 'courserequests') {
                   8886:                     $datakey = &escape($datakey);
                   8887:                 }
1.1105    raeburn  8888:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   8889:                                   $namevalue,$uhome);
1.1013    raeburn  8890:             }
                   8891:         } else {
                   8892:             $result = 'error: data to store was not a hash reference'; 
                   8893:         }
                   8894:     } else {
                   8895:         $result= 'error: invalid requestkey'; 
                   8896:     }
                   8897:     return $result;
                   8898: }
                   8899: 
1.21      www      8900: # ---------------------------------------------------------- Assign Custom Role
                   8901: 
                   8902: sub assigncustomrole {
1.957     raeburn  8903:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8904:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  8905:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      8906: }
                   8907: 
                   8908: # ----------------------------------------------------------------- Revoke Role
                   8909: 
                   8910: sub revokerole {
1.957     raeburn  8911:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8912:     my $now=time;
1.965     raeburn  8913:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      8914: }
                   8915: 
                   8916: # ---------------------------------------------------------- Revoke Custom Role
                   8917: 
                   8918: sub revokecustomrole {
1.957     raeburn  8919:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8920:     my $now=time;
1.357     www      8921:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  8922:            $deleteflag,$selfenroll,$context);
1.17      www      8923: }
                   8924: 
1.533     banghart 8925: # ------------------------------------------------------------ Disk usage
1.535     albertel 8926: sub diskusage {
1.955     raeburn  8927:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   8928:     $directorypath =~ s/\/$//;
                   8929:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   8930:                        .&escape($getpropath).':'.&escape($uname).':'
                   8931:                        .&escape($udom),homeserver($uname,$udom));
                   8932:     if ($listing eq 'unknown_cmd') {
                   8933:         if ($getpropath) {
                   8934:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   8935:         }
                   8936:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   8937:     }
1.514     albertel 8938:     return $listing;
1.512     banghart 8939: }
                   8940: 
1.566     banghart 8941: sub is_locked {
1.1096    raeburn  8942:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 8943:     my @check;
                   8944:     my $is_locked;
1.1093    raeburn  8945:     push (@check,$file_name);
1.613     albertel 8946:     my %locked = &get('file_permissions',\@check,
1.620     albertel 8947: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 8948:     my ($tmp)=keys(%locked);
                   8949:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  8950:     
1.566     banghart 8951:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  8952:         $is_locked = 'false';
                   8953:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  8954:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  8955:                $is_locked = 'true';
1.1096    raeburn  8956:                if (ref($which) eq 'ARRAY') {
                   8957:                    push(@{$which},$entry);
                   8958:                } else {
                   8959:                    last;
                   8960:                }
1.745     raeburn  8961:            }
                   8962:        }
1.566     banghart 8963:     } else {
                   8964:         $is_locked = 'false';
                   8965:     }
1.1093    raeburn  8966:     return $is_locked;
1.566     banghart 8967: }
                   8968: 
1.759     albertel 8969: sub declutter_portfile {
                   8970:     my ($file) = @_;
1.833     albertel 8971:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 8972:     return $file;
                   8973: }
                   8974: 
1.559     banghart 8975: # ------------------------------------------------------------- Mark as Read Only
                   8976: 
                   8977: sub mark_as_readonly {
                   8978:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 8979:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8980:     my ($tmp)=keys(%current_permissions);
                   8981:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 8982:     foreach my $file (@{$files}) {
1.759     albertel 8983: 	$file = &declutter_portfile($file);
1.561     banghart 8984:         push(@{$current_permissions{$file}},$what);
1.559     banghart 8985:     }
1.613     albertel 8986:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8987:     return;
                   8988: }
                   8989: 
1.572     banghart 8990: # ------------------------------------------------------------Save Selected Files
                   8991: 
                   8992: sub save_selected_files {
                   8993:     my ($user, $path, @files) = @_;
                   8994:     my $filename = $user."savedfiles";
1.573     banghart 8995:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 8996:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 8997:     foreach my $file (@files) {
1.620     albertel 8998:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 8999:     }
                   9000:     foreach my $file (@other_files) {
1.574     banghart 9001:         print (OUT $file."\n");
1.572     banghart 9002:     }
1.574     banghart 9003:     close (OUT);
1.572     banghart 9004:     return 'ok';
                   9005: }
                   9006: 
1.574     banghart 9007: sub clear_selected_files {
                   9008:     my ($user) = @_;
                   9009:     my $filename = $user."savedfiles";
1.1117    foxr     9010:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 9011:     print (OUT undef);
                   9012:     close (OUT);
                   9013:     return ("ok");    
                   9014: }
                   9015: 
1.572     banghart 9016: sub files_in_path {
                   9017:     my ($user, $path) = @_;
                   9018:     my $filename = $user."savedfiles";
                   9019:     my %return_files;
1.1117    foxr     9020:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 9021:     while (my $line_in = <IN>) {
1.574     banghart 9022:         chomp ($line_in);
                   9023:         my @paths_and_file = split (m!/!, $line_in);
                   9024:         my $file_part = pop (@paths_and_file);
                   9025:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9026:         $path_part.='/';
                   9027:         my $path_and_file = $path_part.$file_part;
                   9028:         if ($path_part eq $path) {
                   9029:             $return_files{$file_part}= 'selected';
                   9030:         }
                   9031:     }
1.574     banghart 9032:     close (IN);
                   9033:     return (\%return_files);
1.572     banghart 9034: }
                   9035: 
                   9036: # called in portfolio select mode, to show files selected NOT in current directory
                   9037: sub files_not_in_path {
                   9038:     my ($user, $path) = @_;
                   9039:     my $filename = $user."savedfiles";
                   9040:     my @return_files;
                   9041:     my $path_part;
1.1117    foxr     9042:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 9043:     while (my $line = <IN>) {
1.572     banghart 9044:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9045:         my @paths_and_file = split(m|/|, $line);
                   9046:         my $file_part = pop(@paths_and_file);
                   9047:         chomp($file_part);
                   9048:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9049:         $path_part .= '/';
                   9050:         my $path_and_file = $path_part.$file_part;
                   9051:         if ($path_part ne $path) {
1.800     albertel 9052:             push(@return_files, ($path_and_file));
1.572     banghart 9053:         }
                   9054:     }
1.800     albertel 9055:     close(OUT);
1.574     banghart 9056:     return (@return_files);
1.572     banghart 9057: }
                   9058: 
1.745     raeburn  9059: #----------------------------------------------Get portfolio file permissions
1.629     banghart 9060: 
1.745     raeburn  9061: sub get_portfile_permissions {
                   9062:     my ($domain,$user) = @_;
1.613     albertel 9063:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9064:     my ($tmp)=keys(%current_permissions);
                   9065:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9066:     return \%current_permissions;
                   9067: }
                   9068: 
                   9069: #---------------------------------------------Get portfolio file access controls
                   9070: 
1.749     raeburn  9071: sub get_access_controls {
1.745     raeburn  9072:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 9073:     my %access;
                   9074:     my $real_file = $file;
                   9075:     $file =~ s/\.meta$//;
1.745     raeburn  9076:     if (defined($file)) {
1.749     raeburn  9077:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   9078:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 9079:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  9080:             }
                   9081:         }
1.745     raeburn  9082:     } else {
1.749     raeburn  9083:         foreach my $key (keys(%{$current_permissions})) {
                   9084:             if ($key =~ /\0accesscontrol$/) {
                   9085:                 if (defined($group)) {
                   9086:                     if ($key !~ m-^\Q$group\E/-) {
                   9087:                         next;
                   9088:                     }
                   9089:                 }
                   9090:                 my ($fullpath) = split(/\0/,$key);
                   9091:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   9092:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   9093:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   9094:                     }
                   9095:                 }
                   9096:             }
                   9097:         }
                   9098:     }
                   9099:     return %access;
                   9100: }
                   9101: 
                   9102: sub modify_access_controls {
                   9103:     my ($file_name,$changes,$domain,$user)=@_;
                   9104:     my ($outcome,$deloutcome);
                   9105:     my %store_permissions;
                   9106:     my %new_values;
                   9107:     my %new_control;
                   9108:     my %translation;
                   9109:     my @deletions = ();
                   9110:     my $now = time;
                   9111:     if (exists($$changes{'activate'})) {
                   9112:         if (ref($$changes{'activate'}) eq 'HASH') {
                   9113:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   9114:             my $numnew = scalar(@newitems);
                   9115:             for (my $i=0; $i<$numnew; $i++) {
                   9116:                 my $newkey = $newitems[$i];
                   9117:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  9118:                 if ($newkey =~ /^\d+:/) { 
                   9119:                     $newkey =~ s/^(\d+)/$newid/;
                   9120:                     $translation{$1} = $newid;
                   9121:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   9122:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   9123:                     $translation{$1} = $newid;
                   9124:                 }
1.749     raeburn  9125:                 $new_values{$file_name."\0".$newkey} = 
                   9126:                                           $$changes{'activate'}{$newitems[$i]};
                   9127:                 $new_control{$newkey} = $now;
                   9128:             }
                   9129:         }
                   9130:     }
                   9131:     my %todelete;
                   9132:     my %changed_items;
                   9133:     foreach my $action ('delete','update') {
                   9134:         if (exists($$changes{$action})) {
                   9135:             if (ref($$changes{$action}) eq 'HASH') {
                   9136:                 foreach my $key (keys(%{$$changes{$action}})) {
                   9137:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   9138:                     if ($action eq 'delete') { 
                   9139:                         $todelete{$itemnum} = 1;
                   9140:                     } else {
                   9141:                         $changed_items{$itemnum} = $key;
                   9142:                     }
                   9143:                 }
1.745     raeburn  9144:             }
                   9145:         }
1.749     raeburn  9146:     }
                   9147:     # get lock on access controls for file.
                   9148:     my $lockhash = {
                   9149:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   9150:                                                        ':'.$env{'user.domain'},
                   9151:                    }; 
                   9152:     my $tries = 0;
                   9153:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9154:    
                   9155:     while (($gotlock ne 'ok') && $tries <3) {
                   9156:         $tries ++;
                   9157:         sleep 1;
                   9158:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9159:     }
                   9160:     if ($gotlock eq 'ok') {
                   9161:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   9162:         my ($tmp)=keys(%curr_permissions);
                   9163:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   9164:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   9165:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   9166:             if (ref($curr_controls) eq 'HASH') {
                   9167:                 foreach my $control_item (keys(%{$curr_controls})) {
                   9168:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   9169:                     if (defined($todelete{$itemnum})) {
                   9170:                         push(@deletions,$file_name."\0".$control_item);
                   9171:                     } else {
                   9172:                         if (defined($changed_items{$itemnum})) {
                   9173:                             $new_control{$changed_items{$itemnum}} = $now;
                   9174:                             push(@deletions,$file_name."\0".$control_item);
                   9175:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   9176:                         } else {
                   9177:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   9178:                         }
                   9179:                     }
1.745     raeburn  9180:                 }
                   9181:             }
                   9182:         }
1.970     raeburn  9183:         my ($group);
                   9184:         if (&is_course($domain,$user)) {
                   9185:             ($group,my $file) = split(/\//,$file_name,2);
                   9186:         }
1.749     raeburn  9187:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   9188:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   9189:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   9190:         #  remove lock
                   9191:         my @del_lock = ($file_name."\0".'locked_access_records');
                   9192:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9193:         my $sqlresult =
1.970     raeburn  9194:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9195:                                     $group);
1.749     raeburn  9196:     } else {
                   9197:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9198:     }
1.749     raeburn  9199:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9200: }
                   9201: 
1.827     raeburn  9202: sub make_public_indefinitely {
                   9203:     my ($requrl) = @_;
                   9204:     my $now = time;
                   9205:     my $action = 'activate';
                   9206:     my $aclnum = 0;
                   9207:     if (&is_portfolio_url($requrl)) {
                   9208:         my (undef,$udom,$unum,$file_name,$group) =
                   9209:             &parse_portfolio_url($requrl);
                   9210:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   9211:         my %access_controls = &get_access_controls($current_perms,
                   9212:                                                    $group,$file_name);
                   9213:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9214:             my ($num,$scope,$end,$start) = 
                   9215:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   9216:             if ($scope eq 'public') {
                   9217:                 if ($start <= $now && $end == 0) {
                   9218:                     $action = 'none';
                   9219:                 } else {
                   9220:                     $action = 'update';
                   9221:                     $aclnum = $num;
                   9222:                 }
                   9223:                 last;
                   9224:             }
                   9225:         }
                   9226:         if ($action eq 'none') {
                   9227:              return 'ok';
                   9228:         } else {
                   9229:             my %changes;
                   9230:             my $newend = 0;
                   9231:             my $newstart = $now;
                   9232:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   9233:             $changes{$action}{$newkey} = {
                   9234:                 type => 'public',
                   9235:                 time => {
                   9236:                     start => $newstart,
                   9237:                     end   => $newend,
                   9238:                 },
                   9239:             };
                   9240:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9241:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   9242:             return $outcome;
                   9243:         }
                   9244:     } else {
                   9245:         return 'invalid';
                   9246:     }
                   9247: }
                   9248: 
1.745     raeburn  9249: #------------------------------------------------------Get Marked as Read Only
                   9250: 
                   9251: sub get_marked_as_readonly {
                   9252:     my ($domain,$user,$what,$group) = @_;
                   9253:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 9254:     my @readonly_files;
1.629     banghart 9255:     my $cmp1=$what;
                   9256:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  9257:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9258:         if (defined($group)) {
                   9259:             if ($file_name !~ m-^\Q$group\E/-) {
                   9260:                 next;
                   9261:             }
                   9262:         }
1.561     banghart 9263:         if (ref($value) eq "ARRAY"){
                   9264:             foreach my $stored_what (@{$value}) {
1.629     banghart 9265:                 my $cmp2=$stored_what;
1.759     albertel 9266:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  9267:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  9268:                 }
1.629     banghart 9269:                 if ($cmp1 eq $cmp2) {
1.561     banghart 9270:                     push(@readonly_files, $file_name);
1.745     raeburn  9271:                     last;
1.563     banghart 9272:                 } elsif (!defined($what)) {
                   9273:                     push(@readonly_files, $file_name);
1.745     raeburn  9274:                     last;
1.561     banghart 9275:                 }
                   9276:             }
1.745     raeburn  9277:         }
1.561     banghart 9278:     }
                   9279:     return @readonly_files;
                   9280: }
1.577     banghart 9281: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 9282: 
1.577     banghart 9283: sub get_marked_as_readonly_hash {
1.745     raeburn  9284:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 9285:     my %readonly_files;
1.745     raeburn  9286:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9287:         if (defined($group)) {
                   9288:             if ($file_name !~ m-^\Q$group\E/-) {
                   9289:                 next;
                   9290:             }
                   9291:         }
1.577     banghart 9292:         if (ref($value) eq "ARRAY"){
                   9293:             foreach my $stored_what (@{$value}) {
1.745     raeburn  9294:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 9295:                     foreach my $lock_descriptor(@{$stored_what}) {
                   9296:                         if ($lock_descriptor eq 'graded') {
                   9297:                             $readonly_files{$file_name} = 'graded';
                   9298:                         } elsif ($lock_descriptor eq 'handback') {
                   9299:                             $readonly_files{$file_name} = 'handback';
                   9300:                         } else {
                   9301:                             if (!exists($readonly_files{$file_name})) {
                   9302:                                 $readonly_files{$file_name} = 'locked';
                   9303:                             }
                   9304:                         }
1.745     raeburn  9305:                     }
1.750     banghart 9306:                 } 
1.577     banghart 9307:             }
                   9308:         } 
                   9309:     }
                   9310:     return %readonly_files;
                   9311: }
1.559     banghart 9312: # ------------------------------------------------------------ Unmark as Read Only
                   9313: 
                   9314: sub unmark_as_readonly {
1.629     banghart 9315:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   9316:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  9317:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 9318:     $file_name = &declutter_portfile($file_name);
1.634     albertel 9319:     my $symb_crs = $what;
                   9320:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  9321:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 9322:     my ($tmp)=keys(%current_permissions);
                   9323:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9324:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 9325:     foreach my $file (@readonly_files) {
1.759     albertel 9326: 	my $clean_file = &declutter_portfile($file);
                   9327: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 9328: 	my $current_locks = $current_permissions{$file};
1.563     banghart 9329:         my @new_locks;
                   9330:         my @del_keys;
                   9331:         if (ref($current_locks) eq "ARRAY"){
                   9332:             foreach my $locker (@{$current_locks}) {
1.632     albertel 9333:                 my $compare=$locker;
1.749     raeburn  9334:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  9335:                     $compare=join('',@{$locker});
1.746     raeburn  9336:                     if ($compare ne $symb_crs) {
                   9337:                         push(@new_locks, $locker);
                   9338:                     }
1.563     banghart 9339:                 }
                   9340:             }
1.650     albertel 9341:             if (scalar(@new_locks) > 0) {
1.563     banghart 9342:                 $current_permissions{$file} = \@new_locks;
                   9343:             } else {
                   9344:                 push(@del_keys, $file);
1.613     albertel 9345:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 9346:                 delete($current_permissions{$file});
1.563     banghart 9347:             }
                   9348:         }
1.561     banghart 9349:     }
1.613     albertel 9350:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9351:     return;
                   9352: }
1.512     banghart 9353: 
1.17      www      9354: # ------------------------------------------------------------ Directory lister
                   9355: 
                   9356: sub dirlist {
1.955     raeburn  9357:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      9358:     $uri=~s/^\///;
                   9359:     $uri=~s/\/$//;
1.253     stredwic 9360:     my ($udom, $uname);
1.955     raeburn  9361:     if ($getuserdir) {
1.253     stredwic 9362:         $udom = $userdomain;
                   9363:         $uname = $username;
1.955     raeburn  9364:     } else {
                   9365:         (undef,$udom,$uname)=split(/\//,$uri);
                   9366:         if(defined($userdomain)) {
                   9367:             $udom = $userdomain;
                   9368:         }
                   9369:         if(defined($username)) {
                   9370:             $uname = $username;
                   9371:         }
1.253     stredwic 9372:     }
1.955     raeburn  9373:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 9374: 
1.955     raeburn  9375:     $dirRoot = $perlvar{'lonDocRoot'};
                   9376:     if (defined($getpropath)) {
                   9377:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 9378:         $dirRoot =~ s/\/$//;
1.955     raeburn  9379:     } elsif (defined($getuserdir)) {
                   9380:         my $subdir=$uname.'__';
                   9381:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   9382:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   9383:                    ."/$udom/$subdir/$uname";
                   9384:     } elsif (defined($alternateRoot)) {
                   9385:         $dirRoot = $alternateRoot;
1.751     banghart 9386:     }
1.253     stredwic 9387: 
                   9388:     if($udom) {
                   9389:         if($uname) {
1.1135    raeburn  9390:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  9391:             if ($uhome eq 'no_host') {
                   9392:                 return ([],'no_host');
                   9393:             }
1.955     raeburn  9394:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  9395:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  9396:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  9397:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9398:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  9399:             } else {
                   9400:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9401:             }
1.605     matthew  9402:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9403:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  9404:                 @listing_results = split(/:/,$listing);
                   9405:             } else {
                   9406:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9407:             }
1.1135    raeburn  9408:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  9409:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9410:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9411:                 return ([],$listing);
                   9412:             } else {
                   9413:                 return (\@listing_results);
1.1135    raeburn  9414:             }
1.955     raeburn  9415:         } elsif(!$alternateRoot) {
1.1136    raeburn  9416:             my (%allusers,%listerror);
1.841     albertel 9417: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  9418:  	    foreach my $tryserver (keys(%servers)) {
                   9419:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   9420:                                   &escape($udom),$tryserver);
                   9421:                 if ($listing eq 'unknown_cmd') {
                   9422: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9423: 				      $udom, $tryserver);
                   9424:                 } else {
                   9425:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9426:                 }
1.841     albertel 9427: 		if ($listing eq 'unknown_cmd') {
                   9428: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9429: 				      $udom, $tryserver);
                   9430: 		    @listing_results = split(/:/,$listing);
                   9431: 		} else {
                   9432: 		    @listing_results =
                   9433: 			map { &unescape($_); } split(/:/,$listing);
                   9434: 		}
1.1136    raeburn  9435:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   9436:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9437:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9438:                     $listerror{$tryserver} = $listing;
                   9439:                 } else {
1.841     albertel 9440: 		    foreach my $line (@listing_results) {
                   9441: 			my ($entry) = split(/&/,$line,2);
                   9442: 			$allusers{$entry} = 1;
                   9443: 		    }
                   9444: 		}
1.253     stredwic 9445:             }
1.1136    raeburn  9446:             my @alluserslist=();
1.800     albertel 9447:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  9448:                 push(@alluserslist,$user.'&user');
1.253     stredwic 9449:             }
1.1136    raeburn  9450:             return (\@alluserslist);
1.253     stredwic 9451:         } else {
1.1136    raeburn  9452:             return ([],'missing username');
1.253     stredwic 9453:         }
1.955     raeburn  9454:     } elsif(!defined($getpropath)) {
1.1136    raeburn  9455:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   9456:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   9457:         return (\@all_domains);
1.955     raeburn  9458:     } else {
1.1136    raeburn  9459:         return ([],'missing domain');
1.275     stredwic 9460:     }
                   9461: }
                   9462: 
                   9463: # --------------------------------------------- GetFileTimestamp
                   9464: # This function utilizes dirlist and returns the date stamp for
                   9465: # when it was last modified.  It will also return an error of -1
                   9466: # if an error occurs
                   9467: 
                   9468: sub GetFileTimestamp {
1.955     raeburn  9469:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 9470:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   9471:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  9472:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   9473:                                     undef,$getuserdir);
                   9474:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9475:         return -1;
                   9476:     }
                   9477:     if (ref($fileref) eq 'ARRAY') {
                   9478:         my @stats = split('&',$fileref->[0]);
1.375     matthew  9479:         # @stats contains first the filename, then the stat output
                   9480:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 9481:     } else {
                   9482:         return -1;
1.253     stredwic 9483:     }
1.26      www      9484: }
                   9485: 
1.712     albertel 9486: sub stat_file {
                   9487:     my ($uri) = @_;
1.787     albertel 9488:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 9489: 
1.955     raeburn  9490:     my ($udom,$uname,$file);
1.712     albertel 9491:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   9492: 	($udom,$uname,$file) =
1.811     albertel 9493: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 9494: 	$file = 'userfiles/'.$file;
                   9495:     }
                   9496:     if ($uri =~ m-^/res/-) {
                   9497: 	($udom,$uname) = 
1.807     albertel 9498: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 9499: 	$file = $uri;
                   9500:     }
                   9501: 
                   9502:     if (!$udom || !$uname || !$file) {
                   9503: 	# unable to handle the uri
                   9504: 	return ();
                   9505:     }
1.956     raeburn  9506:     my $getpropath;
                   9507:     if ($file =~ /^userfiles\//) {
                   9508:         $getpropath = 1;
                   9509:     }
1.1136    raeburn  9510:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   9511:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9512:         return ();
                   9513:     } else {
                   9514:         if (ref($listref) eq 'ARRAY') {
                   9515:             my @stats = split('&',$listref->[0]);
                   9516: 	    shift(@stats); #filename is first
                   9517: 	    return @stats;
                   9518:         }
1.712     albertel 9519:     }
                   9520:     return ();
                   9521: }
                   9522: 
1.26      www      9523: # -------------------------------------------------------- Value of a Condition
                   9524: 
1.713     albertel 9525: # gets the value of a specific preevaluated condition
                   9526: #    stored in the string  $env{user.state.<cid>}
                   9527: # or looks up a condition reference in the bighash and if if hasn't
                   9528: # already been evaluated recurses into docondval to get the value of
                   9529: # the condition, then memoizing it to 
                   9530: #   $env{user.state.<cid>.<condition>}
1.40      www      9531: sub directcondval {
                   9532:     my $number=shift;
1.620     albertel 9533:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 9534: 	&Apache::lonuserstate::evalstate();
                   9535:     }
1.713     albertel 9536:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   9537: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   9538:     } elsif ($number =~ /^_/) {
                   9539: 	my $sub_condition;
                   9540: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9541: 		&GDBM_READER(),0640)) {
                   9542: 	    $sub_condition=$bighash{'conditions'.$number};
                   9543: 	    untie(%bighash);
                   9544: 	}
                   9545: 	my $value = &docondval($sub_condition);
1.949     raeburn  9546: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 9547: 	return $value;
                   9548:     }
1.620     albertel 9549:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   9550:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      9551:     } else {
                   9552:        return 2;
                   9553:     }
                   9554: }
                   9555: 
1.713     albertel 9556: # get the collection of conditions for this resource
1.26      www      9557: sub condval {
                   9558:     my $condidx=shift;
1.54      www      9559:     my $allpathcond='';
1.713     albertel 9560:     foreach my $cond (split(/\|/,$condidx)) {
                   9561: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   9562: 	    $allpathcond.=
                   9563: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   9564: 	}
1.191     harris41 9565:     }
1.54      www      9566:     $allpathcond=~s/\|$//;
1.713     albertel 9567:     return &docondval($allpathcond);
                   9568: }
                   9569: 
                   9570: #evaluates an expression of conditions
                   9571: sub docondval {
                   9572:     my ($allpathcond) = @_;
                   9573:     my $result=0;
                   9574:     if ($env{'request.course.id'}
                   9575: 	&& defined($allpathcond)) {
                   9576: 	my $operand='|';
                   9577: 	my @stack;
                   9578: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   9579: 	    if ($chunk eq '(') {
                   9580: 		push @stack,($operand,$result);
                   9581: 	    } elsif ($chunk eq ')') {
                   9582: 		my $before=pop @stack;
                   9583: 		if (pop @stack eq '&') {
                   9584: 		    $result=$result>$before?$before:$result;
                   9585: 		} else {
                   9586: 		    $result=$result>$before?$result:$before;
                   9587: 		}
                   9588: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   9589: 		$operand=$chunk;
                   9590: 	    } else {
                   9591: 		my $new=directcondval($chunk);
                   9592: 		if ($operand eq '&') {
                   9593: 		    $result=$result>$new?$new:$result;
                   9594: 		} else {
                   9595: 		    $result=$result>$new?$result:$new;
                   9596: 		}
                   9597: 	    }
                   9598: 	}
1.26      www      9599:     }
                   9600:     return $result;
1.421     albertel 9601: }
                   9602: 
                   9603: # ---------------------------------------------------- Devalidate courseresdata
                   9604: 
                   9605: sub devalidatecourseresdata {
                   9606:     my ($coursenum,$coursedomain)=@_;
                   9607:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9608:     &devalidate_cache_new('courseres',$hashid);
1.28      www      9609: }
                   9610: 
1.763     www      9611: 
1.200     www      9612: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     9613: #
                   9614: #  Parameters:
                   9615: #      $coursenum    - Number of the course.
                   9616: #      $coursedomain - Domain at which the course was created.
                   9617: #  Returns:
                   9618: #     A hash of the course parameters along (I think) with timestamps
                   9619: #     and version info.
1.877     foxr     9620: 
1.624     albertel 9621: sub get_courseresdata {
                   9622:     my ($coursenum,$coursedomain)=@_;
1.200     www      9623:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   9624:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9625:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 9626:     my %dumpreply;
1.417     albertel 9627:     unless (defined($cached)) {
1.624     albertel 9628: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 9629: 	$result=\%dumpreply;
1.251     albertel 9630: 	my ($tmp) = keys(%dumpreply);
                   9631: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 9632: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 9633: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   9634: 	    return $tmp;
1.416     albertel 9635: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 9636: 	    $result=undef;
1.599     albertel 9637: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 9638: 	}
                   9639:     }
1.624     albertel 9640:     return $result;
                   9641: }
                   9642: 
1.633     albertel 9643: sub devalidateuserresdata {
                   9644:     my ($uname,$udom)=@_;
                   9645:     my $hashid="$udom:$uname";
                   9646:     &devalidate_cache_new('userres',$hashid);
                   9647: }
                   9648: 
1.624     albertel 9649: sub get_userresdata {
                   9650:     my ($uname,$udom)=@_;
                   9651:     #most student don\'t have any data set, check if there is some data
                   9652:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   9653: 
                   9654:     my $hashid="$udom:$uname";
                   9655:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   9656:     if (!defined($cached)) {
                   9657: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   9658: 	$result=\%resourcedata;
                   9659: 	&do_cache_new('userres',$hashid,$result,600);
                   9660:     }
                   9661:     my ($tmp)=keys(%$result);
                   9662:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   9663: 	return $result;
                   9664:     }
                   9665:     #error 2 occurs when the .db doesn't exist
                   9666:     if ($tmp!~/error: 2 /) {
1.672     albertel 9667: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 9668: 		 " Trying to get resource data for ".
                   9669: 		 $uname." at ".$udom.": ".
                   9670: 		 $tmp."</font>");
                   9671:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 9672: 	#&EXT_cache_set($udom,$uname);
                   9673: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 9674: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 9675:     }
                   9676:     return $tmp;
                   9677: }
1.879     foxr     9678: #----------------------------------------------- resdata - return resource data
                   9679: #  Purpose:
                   9680: #    Return resource data for either users or for a course.
                   9681: #  Parameters:
                   9682: #     $name      - Course/user name.
                   9683: #     $domain    - Name of the domain the user/course is registered on.
                   9684: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   9685: #     @which     - Array of names of resources desired.
                   9686: #  Returns:
                   9687: #     The value of the first reasource in @which that is found in the
                   9688: #     resource hash.
                   9689: #  Exceptional Conditions:
                   9690: #     If the $type passed in is not valid (not the string 'course' or 
                   9691: #     'user', an undefined  reference is returned.
                   9692: #     If none of the resources are found, an undef is returned
1.624     albertel 9693: sub resdata {
                   9694:     my ($name,$domain,$type,@which)=@_;
                   9695:     my $result;
                   9696:     if ($type eq 'course') {
                   9697: 	$result=&get_courseresdata($name,$domain);
                   9698:     } elsif ($type eq 'user') {
                   9699: 	$result=&get_userresdata($name,$domain);
                   9700:     }
                   9701:     if (!ref($result)) { return $result; }    
1.251     albertel 9702:     foreach my $item (@which) {
1.927     albertel 9703: 	if (defined($result->{$item->[0]})) {
                   9704: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 9705: 	}
1.250     albertel 9706:     }
1.291     albertel 9707:     return undef;
1.200     www      9708: }
                   9709: 
1.1172.2.31  raeburn  9710: sub get_numsuppfiles {
                   9711:     my ($cnum,$cdom,$ignorecache)=@_;
                   9712:     my $hashid=$cnum.':'.$cdom;
                   9713:     my ($suppcount,$cached);
                   9714:     unless ($ignorecache) {
                   9715:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   9716:     }
                   9717:     unless (defined($cached)) {
                   9718:         my $chome=&homeserver($cnum,$cdom);
                   9719:         unless ($chome eq 'no_host') {
                   9720:             ($suppcount,my $errors) = (0,0);
                   9721:             my $suppmap = 'supplemental.sequence';
                   9722:             ($suppcount,$errors) =
                   9723:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   9724:         }
                   9725:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   9726:     }
                   9727:     return $suppcount;
                   9728: }
                   9729: 
1.379     matthew  9730: #
                   9731: # EXT resource caching routines
                   9732: #
                   9733: 
                   9734: sub clear_EXT_cache_status {
1.383     albertel 9735:     &delenv('cache.EXT.');
1.379     matthew  9736: }
                   9737: 
                   9738: sub EXT_cache_status {
                   9739:     my ($target_domain,$target_user) = @_;
1.383     albertel 9740:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 9741:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  9742:         # We know already the user has no data
                   9743:         return 1;
                   9744:     } else {
                   9745:         return 0;
                   9746:     }
                   9747: }
                   9748: 
                   9749: sub EXT_cache_set {
                   9750:     my ($target_domain,$target_user) = @_;
1.383     albertel 9751:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  9752:     #&appenv({$cachename => time});
1.379     matthew  9753: }
                   9754: 
1.28      www      9755: # --------------------------------------------------------- Value of a Variable
1.58      www      9756: sub EXT {
1.715     albertel 9757: 
1.1172.2.28  raeburn  9758:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      9759:     unless ($varname) { return ''; }
1.218     albertel 9760:     #get real user name/domain, courseid and symb
                   9761:     my $courseid;
1.359     albertel 9762:     my $publicuser;
1.427     www      9763:     if ($symbparm) {
                   9764: 	$symbparm=&get_symb_from_alias($symbparm);
                   9765:     }
1.218     albertel 9766:     if (!($uname && $udom)) {
1.790     albertel 9767:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 9768:       if (!$symbparm) {	$symbparm=$cursymb; }
                   9769:     } else {
1.620     albertel 9770: 	$courseid=$env{'request.course.id'};
1.218     albertel 9771:     }
1.48      www      9772:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   9773:     my $rest;
1.320     albertel 9774:     if (defined($therest[0])) {
1.48      www      9775:        $rest=join('.',@therest);
                   9776:     } else {
                   9777:        $rest='';
                   9778:     }
1.320     albertel 9779: 
1.57      www      9780:     my $qualifierrest=$qualifier;
                   9781:     if ($rest) { $qualifierrest.='.'.$rest; }
                   9782:     my $spacequalifierrest=$space;
                   9783:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      9784:     if ($realm eq 'user') {
1.48      www      9785: # --------------------------------------------------------------- user.resource
                   9786: 	if ($space eq 'resource') {
1.651     albertel 9787: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   9788: 		  || defined($Apache::lonhomework::parsing_a_task))
                   9789: 		 &&
1.744     albertel 9790: 		 ($symbparm eq &symbread()) ) {	
                   9791: 		# if we are in the middle of processing the resource the
                   9792: 		# get the value we are planning on committing
                   9793:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   9794:                     return $Apache::lonhomework::results{$qualifierrest};
                   9795:                 } else {
                   9796:                     return $Apache::lonhomework::history{$qualifierrest};
                   9797:                 }
1.335     albertel 9798: 	    } else {
1.359     albertel 9799: 		my %restored;
1.620     albertel 9800: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 9801: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   9802: 		} else {
                   9803: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   9804: 		}
1.335     albertel 9805: 		return $restored{$qualifierrest};
                   9806: 	    }
1.48      www      9807: # ----------------------------------------------------------------- user.access
                   9808:         } elsif ($space eq 'access') {
1.218     albertel 9809: 	    # FIXME - not supporting calls for a specific user
1.48      www      9810:             return &allowed($qualifier,$rest);
                   9811: # ------------------------------------------ user.preferences, user.environment
                   9812:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 9813: 	    if (($uname eq $env{'user.name'}) &&
                   9814: 		($udom eq $env{'user.domain'})) {
                   9815: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 9816: 	    } else {
1.359     albertel 9817: 		my %returnhash;
                   9818: 		if (!$publicuser) {
                   9819: 		    %returnhash=&userenvironment($udom,$uname,
                   9820: 						 $qualifierrest);
                   9821: 		}
1.218     albertel 9822: 		return $returnhash{$qualifierrest};
                   9823: 	    }
1.48      www      9824: # ----------------------------------------------------------------- user.course
                   9825:         } elsif ($space eq 'course') {
1.218     albertel 9826: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9827:             return $env{join('.',('request.course',$qualifier))};
1.48      www      9828: # ------------------------------------------------------------------- user.role
                   9829:         } elsif ($space eq 'role') {
1.218     albertel 9830: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9831:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      9832:             if ($qualifier eq 'value') {
                   9833: 		return $role;
                   9834:             } elsif ($qualifier eq 'extent') {
                   9835:                 return $where;
                   9836:             }
                   9837: # ----------------------------------------------------------------- user.domain
                   9838:         } elsif ($space eq 'domain') {
1.218     albertel 9839:             return $udom;
1.48      www      9840: # ------------------------------------------------------------------- user.name
                   9841:         } elsif ($space eq 'name') {
1.218     albertel 9842:             return $uname;
1.48      www      9843: # ---------------------------------------------------- Any other user namespace
1.29      www      9844:         } else {
1.359     albertel 9845: 	    my %reply;
                   9846: 	    if (!$publicuser) {
                   9847: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   9848: 	    }
                   9849: 	    return $reply{$qualifierrest};
1.48      www      9850:         }
1.236     www      9851:     } elsif ($realm eq 'query') {
                   9852: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 9853:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   9854: 						[$spacequalifierrest]);
1.620     albertel 9855: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      9856:    } elsif ($realm eq 'request') {
1.48      www      9857: # ------------------------------------------------------------- request.browser
                   9858:         if ($space eq 'browser') {
1.1145    bisitz   9859:             return $env{'browser.'.$qualifier};
1.57      www      9860: # ------------------------------------------------------------ request.filename
                   9861:         } else {
1.620     albertel 9862:             return $env{'request.'.$spacequalifierrest};
1.29      www      9863:         }
1.28      www      9864:     } elsif ($realm eq 'course') {
1.48      www      9865: # ---------------------------------------------------------- course.description
1.620     albertel 9866:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      9867:     } elsif ($realm eq 'resource') {
1.165     www      9868: 
1.620     albertel 9869: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 9870: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   9871: 	}
1.693     albertel 9872: 
1.1172.2.30  raeburn  9873:         if ($qualifier eq '') {
                   9874: 	    if ($space eq 'title') {
                   9875: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   9876: 	        return &gettitle($symbparm);
                   9877: 	    }
1.693     albertel 9878: 	
1.1172.2.30  raeburn  9879: 	    if ($space eq 'map') {
                   9880: 	        my ($map) = &decode_symb($symbparm);
                   9881: 	        return &symbread($map);
                   9882: 	    }
                   9883:             if ($space eq 'maptitle') {
                   9884:                 my ($map) = &decode_symb($symbparm);
                   9885:                 return &gettitle($map);
                   9886:             }
                   9887: 	    if ($space eq 'filename') {
                   9888: 	        if ($symbparm) {
                   9889: 		    return &clutter((&decode_symb($symbparm))[2]);
                   9890: 	        }
                   9891: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 9892: 	    }
1.1172.2.30  raeburn  9893: 
                   9894:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   9895:                 if ($space eq 'visibleparts') {
                   9896:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9897:                     my $item;
                   9898:                     if (ref($navmap)) {
                   9899:                         my $res = $navmap->getBySymb($symbparm);
                   9900:                         my $parts = $res->parts();
                   9901:                         if (ref($parts) eq 'ARRAY') {
                   9902:                             $item = join(',',@{$parts});
                   9903:                         }
                   9904:                         undef($navmap);
                   9905:                     }
                   9906:                     return $item;
                   9907:                 }
                   9908:             }
                   9909:         }
1.693     albertel 9910: 
                   9911: 	my ($section, $group, @groups);
1.593     albertel 9912: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  9913:         if (($courseid eq '') && ($cid)) {
                   9914:             $courseid = $cid;
                   9915:         }
                   9916: 	if (($symbparm && $courseid) && 
                   9917: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      9918: 
1.218     albertel 9919: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      9920: 
1.60      www      9921: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 9922: 	    my $symbp=$symbparm;
1.735     albertel 9923: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 9924: 
                   9925: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   9926: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   9927: 
1.620     albertel 9928: 	    if (($env{'user.name'} eq $uname) &&
                   9929: 		($env{'user.domain'} eq $udom)) {
                   9930: 		$section=$env{'request.course.sec'};
1.733     raeburn  9931:                 @groups = split(/:/,$env{'request.course.groups'});  
                   9932:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 9933: 	    } else {
1.539     albertel 9934: 		if (! defined($usection)) {
1.551     albertel 9935: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 9936: 		} else {
                   9937: 		    $section = $usection;
                   9938: 		}
1.733     raeburn  9939:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 9940: 	    }
                   9941: 
                   9942: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   9943: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   9944: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   9945: 
1.593     albertel 9946: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 9947: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 9948: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      9949: 
1.60      www      9950: # ----------------------------------------------------------- first, check user
1.624     albertel 9951: 
                   9952: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 9953: 				       ([$courselevelr,'resource'],
                   9954: 					[$courselevelm,'map'     ],
                   9955: 					[$courselevel, 'course'  ]));
1.931     albertel 9956: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      9957: 
1.594     albertel 9958: # ------------------------------------------------ second, check some of course
1.684     raeburn  9959:             my $coursereply;
1.691     raeburn  9960:             if (@groups > 0) {
                   9961:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   9962:                                        $mapparm,$spacequalifierrest);
1.927     albertel 9963:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  9964:             }
1.96      www      9965: 
1.684     raeburn  9966: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 9967: 				  $env{'course.'.$courseid.'.domain'},
                   9968: 				  'course',
                   9969: 				  ([$seclevelr,   'resource'],
                   9970: 				   [$seclevelm,   'map'     ],
                   9971: 				   [$seclevel,    'course'  ],
                   9972: 				   [$courselevelr,'resource']));
                   9973: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      9974: 
1.60      www      9975: # ------------------------------------------------------ third, check map parms
1.218     albertel 9976: 	    my %parmhash=();
                   9977: 	    my $thisparm='';
                   9978: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 9979: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 9980: 		    &GDBM_READER(),0640)) {
1.218     albertel 9981: 		$thisparm=$parmhash{$symbparm};
                   9982: 		untie(%parmhash);
                   9983: 	    }
1.927     albertel 9984: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 9985: 	}
1.594     albertel 9986: # ------------------------------------------ fourth, look in resource metadata
1.71      www      9987: 
1.218     albertel 9988: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 9989: 	my $filename;
                   9990: 	if (!$symbparm) { $symbparm=&symbread(); }
                   9991: 	if ($symbparm) {
1.409     www      9992: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 9993: 	} else {
1.620     albertel 9994: 	    $filename=$env{'request.filename'};
1.282     albertel 9995: 	}
                   9996: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 9997: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 9998: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 9999: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      10000: 
1.927     albertel 10001: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 10002: 	if ($symbparm && defined($courseid) && 
1.620     albertel 10003: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 10004: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   10005: 				     $env{'course.'.$courseid.'.domain'},
                   10006: 				     'course',
1.927     albertel 10007: 				     ([$courselevelm,'map'   ],
                   10008: 				      [$courselevel, 'course']));
                   10009: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 10010: 	}
1.145     www      10011: # ------------------------------------------------------------------ Cascade up
1.218     albertel 10012: 	unless ($space eq '0') {
1.336     albertel 10013: 	    my @parts=split(/_/,$space);
                   10014: 	    my $id=pop(@parts);
                   10015: 	    my $part=join('_',@parts);
                   10016: 	    if ($part eq '') { $part='0'; }
1.927     albertel 10017: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 10018: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  10019: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 10020: 	}
1.395     albertel 10021: 	if ($recurse) { return undef; }
                   10022: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 10023: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      10024: # ---------------------------------------------------- Any other user namespace
                   10025:     } elsif ($realm eq 'environment') {
                   10026: # ----------------------------------------------------------------- environment
1.620     albertel 10027: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   10028: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 10029: 	} else {
1.770     albertel 10030: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   10031: 		return '';
                   10032: 	    }
1.219     albertel 10033: 	    my %returnhash=&userenvironment($udom,$uname,
                   10034: 					    $spacequalifierrest);
                   10035: 	    return $returnhash{$spacequalifierrest};
                   10036: 	}
1.28      www      10037:     } elsif ($realm eq 'system') {
1.48      www      10038: # ----------------------------------------------------------------- system.time
                   10039: 	if ($space eq 'time') {
                   10040: 	    return time;
                   10041:         }
1.696     albertel 10042:     } elsif ($realm eq 'server') {
                   10043: # ----------------------------------------------------------------- system.time
                   10044: 	if ($space eq 'name') {
                   10045: 	    return $ENV{'SERVER_NAME'};
                   10046:         }
1.28      www      10047:     }
1.48      www      10048:     return '';
1.61      www      10049: }
                   10050: 
1.927     albertel 10051: sub get_reply {
                   10052:     my ($reply_value) = @_;
1.940     raeburn  10053:     if (ref($reply_value) eq 'ARRAY') {
                   10054:         if (wantarray) {
                   10055: 	    return @$reply_value;
                   10056:         }
                   10057:         return $reply_value->[0];
                   10058:     } else {
                   10059:         return $reply_value;
1.927     albertel 10060:     }
                   10061: }
                   10062: 
1.691     raeburn  10063: sub check_group_parms {
                   10064:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   10065:     my @groupitems = ();
                   10066:     my $resultitem;
1.927     albertel 10067:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  10068:     foreach my $group (@{$groups}) {
                   10069:         foreach my $level (@levels) {
1.927     albertel 10070:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   10071:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  10072:         }
                   10073:     }
                   10074:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   10075:                             $env{'course.'.$courseid.'.domain'},
                   10076:                                      'course',@groupitems);
                   10077:     return $coursereply;
                   10078: }
                   10079: 
                   10080: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  10081:     my ($courseid,@groups) = @_;
                   10082:     @groups = sort(@groups);
1.691     raeburn  10083:     return @groups;
                   10084: }
                   10085: 
1.395     albertel 10086: sub packages_tab_default {
                   10087:     my ($uri,$varname)=@_;
                   10088:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 10089: 
                   10090:     my (@extension,@specifics,$do_default);
                   10091:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 10092: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 10093: 	if ($pack_type eq 'default') {
                   10094: 	    $do_default=1;
                   10095: 	} elsif ($pack_type eq 'extension') {
                   10096: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 10097: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 10098: 	    # only look at packages defaults for packages that this id is
1.738     albertel 10099: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   10100: 	}
                   10101:     }
                   10102:     # first look for a package that matches the requested part id
                   10103:     foreach my $package (@specifics) {
                   10104: 	my (undef,$pack_type,$pack_part)=@{$package};
                   10105: 	next if ($pack_part ne $part);
                   10106: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10107: 	    return $packagetab{"$pack_type&$name&default"};
                   10108: 	}
                   10109:     }
                   10110:     # look for any possible matching non extension_ package
                   10111:     foreach my $package (@specifics) {
                   10112: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 10113: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10114: 	    return $packagetab{"$pack_type&$name&default"};
                   10115: 	}
1.585     albertel 10116: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 10117: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   10118: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 10119: 	}
                   10120:     }
1.738     albertel 10121:     # look for any posible extension_ match
                   10122:     foreach my $package (@extension) {
                   10123: 	my ($package,$pack_type)=@{$package};
                   10124: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10125: 	    return $packagetab{"$pack_type&$name&default"};
                   10126: 	}
                   10127: 	if (defined($packagetab{$package."&$name&default"})) {
                   10128: 	    return $packagetab{$package."&$name&default"};
                   10129: 	}
                   10130:     }
                   10131:     # look for a global default setting
                   10132:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   10133: 	return $packagetab{"default&$name&default"};
                   10134:     }
1.395     albertel 10135:     return undef;
                   10136: }
                   10137: 
1.334     albertel 10138: sub add_prefix_and_part {
                   10139:     my ($prefix,$part)=@_;
                   10140:     my $keyroot;
                   10141:     if (defined($prefix) && $prefix !~ /^__/) {
                   10142: 	# prefix that has a part already
                   10143: 	$keyroot=$prefix;
                   10144:     } elsif (defined($prefix)) {
                   10145: 	# prefix that is missing a part
                   10146: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   10147:     } else {
                   10148: 	# no prefix at all
                   10149: 	if (defined($part)) { $keyroot='_'.$part; }
                   10150:     }
                   10151:     return $keyroot;
                   10152: }
                   10153: 
1.71      www      10154: # ---------------------------------------------------------------- Get metadata
                   10155: 
1.599     albertel 10156: my %metaentry;
1.1070    www      10157: my %importedpartids;
1.71      www      10158: sub metadata {
1.176     www      10159:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      10160:     $uri=&declutter($uri);
1.288     albertel 10161:     # if it is a non metadata possible uri return quickly
1.529     albertel 10162:     if (($uri eq '') || 
                   10163: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  10164: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  10165:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 10166: 	return undef;
                   10167:     }
1.1140    www      10168:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
1.924     albertel 10169: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 10170: 	return undef;
1.288     albertel 10171:     }
1.73      www      10172:     my $filename=$uri;
                   10173:     $uri=~s/\.meta$//;
1.172     www      10174: #
                   10175: # Is the metadata already cached?
1.177     www      10176: # Look at timestamp of caching
1.172     www      10177: # Everything is cached by the main uri, libraries are never directly cached
                   10178: #
1.428     albertel 10179:     if (!defined($liburi)) {
1.599     albertel 10180: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 10181: 	if (defined($cached)) { return $result->{':'.$what}; }
                   10182:     }
                   10183:     {
1.1069    www      10184: # Imported parts would go here
1.1070    www      10185:         my %importedids=();
                   10186:         my @origfileimportpartids=();
1.1069    www      10187:         my $importedparts=0;
1.172     www      10188: #
                   10189: # Is this a recursive call for a library?
                   10190: #
1.599     albertel 10191: #	if (! exists($metacache{$uri})) {
                   10192: #	    $metacache{$uri}={};
                   10193: #	}
1.924     albertel 10194: 	my $cachetime = 60*60;
1.171     www      10195:         if ($liburi) {
                   10196: 	    $liburi=&declutter($liburi);
                   10197:             $filename=$liburi;
1.401     bowersj2 10198:         } else {
1.599     albertel 10199: 	    &devalidate_cache_new('meta',$uri);
                   10200: 	    undef(%metaentry);
1.401     bowersj2 10201: 	}
1.140     www      10202:         my %metathesekeys=();
1.73      www      10203:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 10204: 	my $metastring;
1.1140    www      10205: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 10206: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 10207: 	    $metastring = 
1.929     albertel 10208: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 10209: 					  ('grade_target' => 'meta'));
                   10210: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  10211: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   10212:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 10213: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 10214: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 10215: 	    $metastring=&getfile($file);
1.489     albertel 10216: 	}
1.208     albertel 10217:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      10218:         my $token;
1.140     www      10219:         undef %metathesekeys;
1.71      www      10220:         while ($token=$parser->get_token) {
1.339     albertel 10221: 	    if ($token->[0] eq 'S') {
                   10222: 		if (defined($token->[2]->{'package'})) {
1.172     www      10223: #
                   10224: # This is a package - get package info
                   10225: #
1.339     albertel 10226: 		    my $package=$token->[2]->{'package'};
                   10227: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10228: 		    if (defined($token->[2]->{'id'})) { 
                   10229: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   10230: 		    }
1.599     albertel 10231: 		    if ($metaentry{':packages'}) {
                   10232: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 10233: 		    } else {
1.599     albertel 10234: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 10235: 		    }
1.736     albertel 10236: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 10237: 			my $part=$keyroot;
                   10238: 			$part=~s/^\_//;
1.736     albertel 10239: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   10240: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   10241: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 10242: 			    # ignore package.tab specified default values
                   10243:                             # here &package_tab_default() will fetch those
                   10244: 			    if ($subp eq 'default') { next; }
1.736     albertel 10245: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 10246: 			    my $unikey;
                   10247: 			    if ($pack =~ /_0$/) {
                   10248: 				$unikey='parameter_0_'.$name;
                   10249: 				$part=0;
                   10250: 			    } else {
                   10251: 				$unikey='parameter'.$keyroot.'_'.$name;
                   10252: 			    }
1.339     albertel 10253: 			    if ($subp eq 'display') {
                   10254: 				$value.=' [Part: '.$part.']';
                   10255: 			    }
1.599     albertel 10256: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 10257: 			    $metathesekeys{$unikey}=1;
1.599     albertel 10258: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10259: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 10260: 			    }
1.599     albertel 10261: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   10262: 				$metaentry{':'.$unikey}=
                   10263: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 10264: 			    }
1.339     albertel 10265: 			}
                   10266: 		    }
                   10267: 		} else {
1.172     www      10268: #
                   10269: # This is not a package - some other kind of start tag
1.339     albertel 10270: #
                   10271: 		    my $entry=$token->[1];
1.1068    www      10272: 		    my $unikey='';
1.175     www      10273: 
1.339     albertel 10274: 		    if ($entry eq 'import') {
1.175     www      10275: #
                   10276: # Importing a library here
1.339     albertel 10277: #
1.1067    www      10278:                         my $location=$parser->get_text('/import');
                   10279:                         my $dir=$filename;
                   10280:                         $dir=~s|[^/]*$||;
                   10281:                         $location=&filelocation($dir,$location);
1.1069    www      10282:                        
1.1068    www      10283:                         my $importmode=$token->[2]->{'importmode'};
                   10284:                         if ($importmode eq 'problem') {
1.1069    www      10285: # Import as problem/response
1.1068    www      10286:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10287:                         } elsif ($importmode eq 'part') {
                   10288: # Import as part(s)
1.1069    www      10289:                            $importedparts=1;
                   10290: # We need to get the original file and the imported file to get the part order correct
                   10291: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   10292: # Load and inspect original file
1.1070    www      10293:                            if ($#origfileimportpartids<0) {
                   10294:                               undef(%importedpartids);
                   10295:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   10296:                               my $origfile=&getfile($origfilelocation);
                   10297:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10298:                            }
                   10299: 
1.1069    www      10300: # Load and inspect imported file
                   10301:                            my $impfile=&getfile($location);
                   10302:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10303:                            if ($#impfilepartids>=0) {
                   10304: # This problem had parts
1.1070    www      10305:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      10306:                            } else {
                   10307: # Importing by turning a single problem into a problem part
                   10308: # It gets the import-tags ID as part-ID
                   10309:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      10310:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      10311:                            }
1.1068    www      10312:                         } else {
                   10313: # Normal import
                   10314:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10315:                            if (defined($token->[2]->{'id'})) {
                   10316:                               $unikey.='_'.$token->[2]->{'id'};
                   10317:                            }
1.1067    www      10318:                         }
                   10319: 
1.339     albertel 10320: 			if ($depthcount<20) {
1.736     albertel 10321: 			    my $metadata = 
                   10322: 				&metadata($uri,'keys', $location,$unikey,
                   10323: 					  $depthcount+1);
                   10324: 			    foreach my $meta (split(',',$metadata)) {
                   10325: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   10326: 				$metathesekeys{$meta}=1;
1.339     albertel 10327: 			    }
1.1068    www      10328: 			
                   10329:                         }
1.1067    www      10330: 		    } else {
                   10331: #
                   10332: # Not importing, some other kind of non-package, non-library start tag
                   10333: # 
                   10334:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10335:                         if (defined($token->[2]->{'id'})) {
                   10336:                             $unikey.='_'.$token->[2]->{'id'};
                   10337:                         }
1.339     albertel 10338: 			if (defined($token->[2]->{'name'})) { 
                   10339: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   10340: 			}
                   10341: 			$metathesekeys{$unikey}=1;
1.736     albertel 10342: 			foreach my $param (@{$token->[3]}) {
                   10343: 			    $metaentry{':'.$unikey.'.'.$param} =
                   10344: 				$token->[2]->{$param};
1.339     albertel 10345: 			}
                   10346: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 10347: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 10348: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   10349: 		 # only ws inside the tag, and not in default, so use default
                   10350: 		 # as value
1.599     albertel 10351: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 10352: 			} elsif ( $internaltext =~ /\S/ ) {
                   10353: 		  # something interesting inside the tag
                   10354: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 10355: 			} else {
1.908     albertel 10356: 		  # no interesting values, don't set a default
1.339     albertel 10357: 			}
1.172     www      10358: # end of not-a-package not-a-library import
1.339     albertel 10359: 		    }
1.172     www      10360: # end of not-a-package start tag
1.339     albertel 10361: 		}
1.172     www      10362: # the next is the end of "start tag"
1.339     albertel 10363: 	    }
                   10364: 	}
1.483     albertel 10365: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 10366: 	$extension = lc($extension);
                   10367: 	if ($extension eq 'htm') { $extension='html'; }
                   10368: 
1.737     albertel 10369: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 10370: 	    #no specific packages #how's our extension
                   10371: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 10372: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 10373: 					 \%metathesekeys);
                   10374: 	}
1.883     albertel 10375: 
                   10376: 	if (!exists($metaentry{':packages'})
                   10377: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 10378: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 10379: 		#no specific packages well let's get default then
                   10380: 		if ($key!~/^default&/) { next; }
1.488     albertel 10381: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 10382: 					     \%metathesekeys);
                   10383: 	    }
                   10384: 	}
1.338     www      10385: # are there custom rights to evaluate
1.599     albertel 10386: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 10387: 
1.338     www      10388:     #
                   10389:     # Importing a rights file here
1.339     albertel 10390:     #
                   10391: 	    unless ($depthcount) {
1.599     albertel 10392: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 10393: 		my $dir=$filename;
                   10394: 		$dir=~s|[^/]*$||;
                   10395: 		$location=&filelocation($dir,$location);
1.736     albertel 10396: 		my $rights_metadata =
                   10397: 		    &metadata($uri,'keys',$location,'_rights',
                   10398: 			      $depthcount+1);
                   10399: 		foreach my $rights (split(',',$rights_metadata)) {
                   10400: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   10401: 		    $metathesekeys{$rights}=1;
1.339     albertel 10402: 		}
                   10403: 	    }
                   10404: 	}
1.737     albertel 10405: 	# uniqifiy package listing
                   10406: 	my %seen;
                   10407: 	my @uniq_packages =
                   10408: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   10409: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   10410: 
1.1070    www      10411:         if ($importedparts) {
                   10412: # We had imported parts and need to rebuild partorder
                   10413:            $metaentry{':partorder'}='';
                   10414:            $metathesekeys{'partorder'}=1;
                   10415:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   10416:                if ($origfileimportpartids[$index] eq 'part') {
                   10417: # original part, part of the problem
                   10418:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   10419:                } else {
                   10420: # we have imported parts at this position
                   10421:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   10422:                }
                   10423:            }
                   10424:            $metaentry{':partorder'}=~s/^\,//;
                   10425:         }
                   10426: 
1.737     albertel 10427: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 10428: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   10429: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 10430: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      10431: # this is the end of "was not already recently cached
1.71      www      10432:     }
1.599     albertel 10433:     return $metaentry{':'.$what};
1.261     albertel 10434: }
                   10435: 
1.488     albertel 10436: sub metadata_create_package_def {
1.483     albertel 10437:     my ($uri,$key,$package,$metathesekeys)=@_;
                   10438:     my ($pack,$name,$subp)=split(/\&/,$key);
                   10439:     if ($subp eq 'default') { next; }
                   10440:     
1.599     albertel 10441:     if (defined($metaentry{':packages'})) {
                   10442: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 10443:     } else {
1.599     albertel 10444: 	$metaentry{':packages'}=$package;
1.483     albertel 10445:     }
                   10446:     my $value=$packagetab{$key};
                   10447:     my $unikey;
                   10448:     $unikey='parameter_0_'.$name;
1.599     albertel 10449:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 10450:     $$metathesekeys{$unikey}=1;
1.599     albertel 10451:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10452: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 10453:     }
1.599     albertel 10454:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   10455: 	$metaentry{':'.$unikey}=
                   10456: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 10457:     }
                   10458: }
                   10459: 
1.261     albertel 10460: sub metadata_generate_part0 {
                   10461:     my ($metadata,$metacache,$uri) = @_;
                   10462:     my %allnames;
1.737     albertel 10463:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 10464: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 10465: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   10466: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 10467: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 10468: 	    $allnames{$name}=$part;
                   10469: 	  }
                   10470: 	}
                   10471:     }
                   10472:     foreach my $name (keys(%allnames)) {
                   10473:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 10474:       my $key=":parameter_0_$name";
1.261     albertel 10475:       $$metacache{"$key.part"}='0';
                   10476:       $$metacache{"$key.name"}=$name;
1.428     albertel 10477:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 10478: 					   $allnames{$name}.'_'.$name.
                   10479: 					   '.type'};
1.428     albertel 10480:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 10481: 			     '.display'};
1.644     www      10482:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 10483:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 10484:       $$metacache{"$key.display"}=$olddis;
                   10485:     }
1.71      www      10486: }
                   10487: 
1.764     albertel 10488: # ------------------------------------------------------ Devalidate title cache
                   10489: 
                   10490: sub devalidate_title_cache {
                   10491:     my ($url)=@_;
                   10492:     if (!$env{'request.course.id'}) { return; }
                   10493:     my $symb=&symbread($url);
                   10494:     if (!$symb) { return; }
                   10495:     my $key=$env{'request.course.id'}."\0".$symb;
                   10496:     &devalidate_cache_new('title',$key);
                   10497: }
                   10498: 
1.1014    droeschl 10499: # ------------------------------------------------- Get the title of a course
                   10500: 
                   10501: sub current_course_title {
                   10502:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   10503: }
1.301     www      10504: # ------------------------------------------------- Get the title of a resource
                   10505: 
                   10506: sub gettitle {
                   10507:     my $urlsymb=shift;
                   10508:     my $symb=&symbread($urlsymb);
1.534     albertel 10509:     if ($symb) {
1.620     albertel 10510: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 10511: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 10512: 	if (defined($cached)) { 
                   10513: 	    return $result;
                   10514: 	}
1.534     albertel 10515: 	my ($map,$resid,$url)=&decode_symb($symb);
                   10516: 	my $title='';
1.907     albertel 10517: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   10518: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   10519: 	} else {
                   10520: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10521: 		    &GDBM_READER(),0640)) {
                   10522: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   10523: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   10524: 		untie(%bighash);
                   10525: 	    }
1.534     albertel 10526: 	}
                   10527: 	$title=~s/\&colon\;/\:/gs;
                   10528: 	if ($title) {
1.1159    www      10529: # Remember both $symb and $title for dynamic metadata
                   10530:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      10531:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      10532: # Cache this title and then return it
1.599     albertel 10533: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 10534: 	}
                   10535: 	$urlsymb=$url;
                   10536:     }
                   10537:     my $title=&metadata($urlsymb,'title');
                   10538:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   10539:     return $title;
1.301     www      10540: }
1.613     albertel 10541: 
1.614     albertel 10542: sub get_slot {
                   10543:     my ($which,$cnum,$cdom)=@_;
                   10544:     if (!$cnum || !$cdom) {
1.790     albertel 10545: 	(undef,my $courseid)=&whichuser();
1.620     albertel 10546: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   10547: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 10548:     }
1.703     albertel 10549:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   10550:     my %slotinfo;
                   10551:     if (exists($remembered{$key})) {
                   10552: 	$slotinfo{$which} = $remembered{$key};
                   10553:     } else {
                   10554: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   10555: 	&Apache::lonhomework::showhash(%slotinfo);
                   10556: 	my ($tmp)=keys(%slotinfo);
                   10557: 	if ($tmp=~/^error:/) { return (); }
                   10558: 	$remembered{$key} = $slotinfo{$which};
                   10559:     }
1.616     albertel 10560:     if (ref($slotinfo{$which}) eq 'HASH') {
                   10561: 	return %{$slotinfo{$which}};
                   10562:     }
                   10563:     return $slotinfo{$which};
1.614     albertel 10564: }
1.1150    raeburn  10565: 
                   10566: sub get_reservable_slots {
                   10567:     my ($cnum,$cdom,$uname,$udom) = @_;
                   10568:     my $now = time;
                   10569:     my $reservable_info;
                   10570:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   10571:     if (exists($remembered{$key})) {
                   10572:         $reservable_info = $remembered{$key};
                   10573:     } else {
                   10574:         my %resv;
                   10575:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   10576:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   10577:         $reservable_info = \%resv;
                   10578:         $remembered{$key} = $reservable_info;
                   10579:     }
                   10580:     return $reservable_info;
                   10581: }
                   10582: 
                   10583: sub get_course_slots {
                   10584:     my ($cnum,$cdom) = @_;
                   10585:     my $hashid=$cnum.':'.$cdom;
                   10586:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   10587:     if (defined($cached)) {
                   10588:         if (ref($result) eq 'HASH') {
                   10589:             return %{$result};
                   10590:         }
                   10591:     } else {
                   10592:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   10593:         my ($tmp) = keys(%slots);
                   10594:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  10595:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  10596:             return %slots;
                   10597:         }
                   10598:     }
                   10599:     return;
                   10600: }
                   10601: 
                   10602: sub devalidate_slots_cache {
                   10603:     my ($cnum,$cdom)=@_;
                   10604:     my $hashid=$cnum.':'.$cdom;
                   10605:     &devalidate_cache_new('allslots',$hashid);
                   10606: }
                   10607: 
1.1172.2.8  raeburn  10608: sub get_coursechange {
                   10609:     my ($cdom,$cnum) = @_;
                   10610:     if ($cdom eq '' || $cnum eq '') {
                   10611:         return unless ($env{'request.course.id'});
                   10612:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10613:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10614:     }
                   10615:     my $hashid=$cdom.'_'.$cnum;
                   10616:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   10617:     if ((defined($cached)) && ($change ne '')) {
                   10618:         return $change;
                   10619:     } else {
                   10620:         my %crshash;
                   10621:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   10622:         if ($crshash{'internal.contentchange'} eq '') {
                   10623:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   10624:             if ($change eq '') {
                   10625:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   10626:                 $change = $crshash{'internal.created'};
                   10627:             }
                   10628:         } else {
                   10629:             $change = $crshash{'internal.contentchange'};
                   10630:         }
                   10631:         my $cachetime = 600;
                   10632:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   10633:     }
                   10634:     return $change;
                   10635: }
                   10636: 
                   10637: sub devalidate_coursechange_cache {
                   10638:     my ($cnum,$cdom)=@_;
                   10639:     my $hashid=$cnum.':'.$cdom;
                   10640:     &devalidate_cache_new('crschange',$hashid);
                   10641: }
                   10642: 
1.31      www      10643: # ------------------------------------------------- Update symbolic store links
                   10644: 
                   10645: sub symblist {
                   10646:     my ($mapname,%newhash)=@_;
1.438     www      10647:     $mapname=&deversion(&declutter($mapname));
1.31      www      10648:     my %hash;
1.620     albertel 10649:     if (($env{'request.course.fn'}) && (%newhash)) {
                   10650:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10651:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  10652: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 10653: 		next if ($url eq 'last_known'
                   10654: 			 && $env{'form.no_update_last_known'});
                   10655: 		$hash{declutter($url)}=&encode_symb($mapname,
                   10656: 						    $newhash{$url}->[1],
                   10657: 						    $newhash{$url}->[0]);
1.191     harris41 10658:             }
1.31      www      10659:             if (untie(%hash)) {
                   10660: 		return 'ok';
                   10661:             }
                   10662:         }
                   10663:     }
                   10664:     return 'error';
1.212     www      10665: }
                   10666: 
                   10667: # --------------------------------------------------------------- Verify a symb
                   10668: 
                   10669: sub symbverify {
1.1172.2.11  raeburn  10670:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      10671:     my $thisfn=$thisurl;
1.439     www      10672:     $thisfn=&declutter($thisfn);
1.215     www      10673: # direct jump to resource in page or to a sequence - will construct own symbs
                   10674:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   10675: # check URL part
1.409     www      10676:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      10677: 
1.431     www      10678:     unless ($url eq $thisfn) { return 0; }
1.213     www      10679: 
1.216     www      10680:     $symb=&symbclean($symb);
1.510     www      10681:     $thisurl=&deversion($thisurl);
1.439     www      10682:     $thisfn=&deversion($thisfn);
1.213     www      10683: 
                   10684:     my %bighash;
                   10685:     my $okay=0;
1.431     www      10686: 
1.620     albertel 10687:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10688:                             &GDBM_READER(),0640)) {
1.1172.2.13  raeburn  10689:         my $noclutter;
1.1032    raeburn  10690:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   10691:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  10692:             if ($map =~ m{^uploaded/.+\.page$}) {
                   10693:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   10694:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   10695:                 $noclutter = 1;
                   10696:             }
                   10697:         }
                   10698:         my $ids;
                   10699:         if ($noclutter) {
                   10700:             $ids=$bighash{'ids_'.$thisurl};
                   10701:         } else {
                   10702:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  10703:         }
1.1102    raeburn  10704:         unless ($ids) {
1.1172.2.13  raeburn  10705:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  10706:             $ids=$bighash{$idkey};
1.216     www      10707:         }
                   10708:         if ($ids) {
                   10709: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  10710:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   10711:                 $symb =~ s/\?.+$//;
                   10712:             }
1.800     albertel 10713: 	    foreach my $id (split(/\,/,$ids)) {
                   10714: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      10715:                if (
                   10716:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  10717:    eq $symb) {
1.1172.2.11  raeburn  10718:                    if (ref($encstate)) {
                   10719:                        $$encstate = $bighash{'encrypted_'.$id};
                   10720:                    }
1.1172.2.13  raeburn  10721:                    if (($env{'request.role.adv'}) ||
                   10722:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  10723:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  10724:                        $okay=1;
                   10725:                        last;
                   10726:                    }
                   10727:                }
                   10728:            }
1.216     www      10729:         }
1.213     www      10730: 	untie(%bighash);
                   10731:     }
                   10732:     return $okay;
1.31      www      10733: }
                   10734: 
1.210     www      10735: # --------------------------------------------------------------- Clean-up symb
                   10736: 
                   10737: sub symbclean {
                   10738:     my $symb=shift;
1.568     albertel 10739:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      10740: # remove version from map
                   10741:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      10742: 
1.210     www      10743: # remove version from URL
                   10744:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      10745: 
1.507     www      10746: # remove wrapper
                   10747: 
1.510     www      10748:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 10749:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      10750:     return $symb;
1.409     www      10751: }
                   10752: 
                   10753: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 10754: 
                   10755: sub encode_symb {
                   10756:     my ($map,$resid,$url)=@_;
                   10757:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   10758: }
1.409     www      10759: 
                   10760: sub decode_symb {
1.568     albertel 10761:     my $symb=shift;
                   10762:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   10763:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      10764:     return (&fixversion($map),$resid,&fixversion($url));
                   10765: }
                   10766: 
                   10767: sub fixversion {
                   10768:     my $fn=shift;
1.609     banghart 10769:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      10770:     my %bighash;
                   10771:     my $uri=&clutter($fn);
1.620     albertel 10772:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      10773: # is this cached?
1.599     albertel 10774:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      10775:     if (defined($cached)) { return $result; }
                   10776: # unfortunately not cached, or expired
1.620     albertel 10777:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      10778: 	    &GDBM_READER(),0640)) {
                   10779:  	if ($bighash{'version_'.$uri}) {
                   10780:  	    my $version=$bighash{'version_'.$uri};
1.444     www      10781:  	    unless (($version eq 'mostrecent') || 
                   10782: 		    ($version==&getversion($uri))) {
1.440     www      10783:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   10784:  	    }
                   10785:  	}
                   10786:  	untie %bighash;
1.413     www      10787:     }
1.599     albertel 10788:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      10789: }
                   10790: 
                   10791: sub deversion {
                   10792:     my $url=shift;
                   10793:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   10794:     return $url;
1.210     www      10795: }
                   10796: 
1.31      www      10797: # ------------------------------------------------------ Return symb list entry
                   10798: 
                   10799: sub symbread {
1.249     www      10800:     my ($thisfn,$donotrecurse)=@_;
1.1172.2.13  raeburn  10801:     my $cache_str;
                   10802:     if ($thisfn ne '') {
                   10803:         $cache_str='request.symbread.cached.'.$thisfn;
                   10804:         if ($env{$cache_str} ne '') {
1.1172.2.8  raeburn  10805:             return $env{$cache_str};
                   10806:         }
1.1172.2.13  raeburn  10807:    } else {
1.242     www      10808: # no filename provided? try from environment
1.620     albertel 10809:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  10810:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   10811:         }
                   10812:         $thisfn=$env{'request.filename'};
1.44      www      10813:     }
1.569     albertel 10814:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      10815: # is that filename actually a symb? Verify, clean, and return
                   10816:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 10817: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 10818: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 10819: 	}
1.242     www      10820:     }
1.44      www      10821:     $thisfn=declutter($thisfn);
1.31      www      10822:     my %hash;
1.37      www      10823:     my %bighash;
                   10824:     my $syval='';
1.620     albertel 10825:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  10826:         my $targetfn = $thisfn;
1.609     banghart 10827:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  10828:             $targetfn = 'adm/wrapper/'.$thisfn;
                   10829:         }
1.687     albertel 10830: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   10831: 	    $targetfn=$1;
                   10832: 	}
1.620     albertel 10833:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10834:                       &GDBM_READER(),0640)) {
1.481     raeburn  10835: 	    $syval=$hash{$targetfn};
1.37      www      10836:             untie(%hash);
                   10837:         }
                   10838: # ---------------------------------------------------------- There was an entry
                   10839:         if ($syval) {
1.601     albertel 10840: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 10841: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  10842: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10843: 		    #return $env{$cache_str}='';
1.601     albertel 10844: 		#}    
                   10845: 		#$syval.=$1;
                   10846: 	    #}
1.37      www      10847:         } else {
                   10848: # ------------------------------------------------------- Was not in symb table
1.620     albertel 10849:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10850:                             &GDBM_READER(),0640)) {
1.37      www      10851: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      10852:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      10853:               unless ($ids) { 
                   10854:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      10855:               }
                   10856:               unless ($ids) {
                   10857: # alias?
                   10858: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      10859:               }
1.37      www      10860:               if ($ids) {
                   10861: # ------------------------------------------------------------------- Has ID(s)
                   10862:                  my @possibilities=split(/\,/,$ids);
1.39      www      10863:                  if ($#possibilities==0) {
                   10864: # ----------------------------------------------- There is only one possibility
1.37      www      10865: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 10866: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10867: 						    $resid,$thisfn);
1.249     www      10868:                  } elsif (!$donotrecurse) {
1.39      www      10869: # ------------------------------------------ There is more than one possibility
                   10870:                      my $realpossible=0;
1.800     albertel 10871:                      foreach my $id (@possibilities) {
                   10872: 			 my $file=$bighash{'src_'.$id};
1.39      www      10873:                          if (&allowed('bre',$file)) {
1.800     albertel 10874:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      10875:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   10876: 				$realpossible++;
1.626     albertel 10877:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10878: 						    $resid,$thisfn);
1.39      www      10879:                             }
                   10880: 			 }
1.191     harris41 10881:                      }
1.39      www      10882: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      10883:                  } else {
                   10884:                      $syval='';
1.37      www      10885:                  }
                   10886: 	      }
                   10887:               untie(%bighash)
1.481     raeburn  10888:            }
1.31      www      10889:         }
1.62      www      10890:         if ($syval) {
1.620     albertel 10891: 	    return $env{$cache_str}=$syval;
1.62      www      10892:         }
1.31      www      10893:     }
1.949     raeburn  10894:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10895:     return $env{$cache_str}='';
1.31      www      10896: }
                   10897: 
                   10898: # ---------------------------------------------------------- Return random seed
                   10899: 
1.32      www      10900: sub numval {
                   10901:     my $txt=shift;
                   10902:     $txt=~tr/A-J/0-9/;
                   10903:     $txt=~tr/a-j/0-9/;
                   10904:     $txt=~tr/K-T/0-9/;
                   10905:     $txt=~tr/k-t/0-9/;
                   10906:     $txt=~tr/U-Z/0-5/;
                   10907:     $txt=~tr/u-z/0-5/;
                   10908:     $txt=~s/\D//g;
1.564     albertel 10909:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      10910:     return int($txt);
1.368     albertel 10911: }
                   10912: 
1.484     albertel 10913: sub numval2 {
                   10914:     my $txt=shift;
                   10915:     $txt=~tr/A-J/0-9/;
                   10916:     $txt=~tr/a-j/0-9/;
                   10917:     $txt=~tr/K-T/0-9/;
                   10918:     $txt=~tr/k-t/0-9/;
                   10919:     $txt=~tr/U-Z/0-5/;
                   10920:     $txt=~tr/u-z/0-5/;
                   10921:     $txt=~s/\D//g;
                   10922:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10923:     my $total;
                   10924:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 10925:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 10926:     return int($total);
                   10927: }
                   10928: 
1.575     albertel 10929: sub numval3 {
                   10930:     use integer;
                   10931:     my $txt=shift;
                   10932:     $txt=~tr/A-J/0-9/;
                   10933:     $txt=~tr/a-j/0-9/;
                   10934:     $txt=~tr/K-T/0-9/;
                   10935:     $txt=~tr/k-t/0-9/;
                   10936:     $txt=~tr/U-Z/0-5/;
                   10937:     $txt=~tr/u-z/0-5/;
                   10938:     $txt=~s/\D//g;
                   10939:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10940:     my $total;
                   10941:     foreach my $val (@txts) { $total+=$val; }
                   10942:     if ($_64bit) { $total=(($total<<32)>>32); }
                   10943:     return $total;
                   10944: }
                   10945: 
1.675     albertel 10946: sub digest {
                   10947:     my ($data)=@_;
                   10948:     my $digest=&Digest::MD5::md5($data);
                   10949:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   10950:     my ($e,$f);
                   10951:     {
                   10952:         use integer;
                   10953:         $e=($a+$b);
                   10954:         $f=($c+$d);
                   10955:         if ($_64bit) {
                   10956:             $e=(($e<<32)>>32);
                   10957:             $f=(($f<<32)>>32);
                   10958:         }
                   10959:     }
                   10960:     if (wantarray) {
                   10961: 	return ($e,$f);
                   10962:     } else {
                   10963: 	my $g;
                   10964: 	{
                   10965: 	    use integer;
                   10966: 	    $g=($e+$f);
                   10967: 	    if ($_64bit) {
                   10968: 		$g=(($g<<32)>>32);
                   10969: 	    }
                   10970: 	}
                   10971: 	return $g;
                   10972:     }
                   10973: }
                   10974: 
1.368     albertel 10975: sub latest_rnd_algorithm_id {
1.675     albertel 10976:     return '64bit5';
1.366     albertel 10977: }
1.32      www      10978: 
1.503     albertel 10979: sub get_rand_alg {
                   10980:     my ($courseid)=@_;
1.790     albertel 10981:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 10982:     if ($courseid) {
1.620     albertel 10983: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 10984:     }
                   10985:     return &latest_rnd_algorithm_id();
                   10986: }
                   10987: 
1.562     albertel 10988: sub validCODE {
                   10989:     my ($CODE)=@_;
                   10990:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   10991:     return 0;
                   10992: }
                   10993: 
1.491     albertel 10994: sub getCODE {
1.620     albertel 10995:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 10996:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   10997: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   10998: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 10999: 	return $Apache::lonhomework::history{'resource.CODE'};
                   11000:     }
                   11001:     return undef;
                   11002: }
1.1133    foxr     11003: #
                   11004: #  Determines the random seed for a specific context:
                   11005: #
                   11006: # parameters:
                   11007: #   symb      - in course context the symb for the seed.
                   11008: #   course_id - The course id of the form domain_coursenum.
                   11009: #   domain    - Domain for the user.
                   11010: #   course    - Course for the user.
                   11011: #   cenv      - environment of the course.
                   11012: #
                   11013: # NOTE:
                   11014: #   All parameters are picked out of the environment if missing
                   11015: #   or not defined.
                   11016: #   If a symb cannot be determined the current time is used instead.
                   11017: #
                   11018: #  For a given well defined symb, courside, domain, username,
                   11019: #  and course environment, the seed is reproducible.
                   11020: #
1.31      www      11021: sub rndseed {
1.1133    foxr     11022:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 11023:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 11024:     if (!defined($symb)) {
1.366     albertel 11025: 	unless ($symb=$wsymb) { return time; }
                   11026:     }
1.1146    foxr     11027:     if (!defined $courseid) { 
                   11028: 	$courseid=$wcourseid; 
                   11029:     }
                   11030:     if (!defined $domain) { $domain=$wdomain; }
                   11031:     if (!defined $username) { $username=$wusername }
1.1133    foxr     11032: 
                   11033:     my $which;
                   11034:     if (defined($cenv->{'rndseed'})) {
                   11035: 	$which = $cenv->{'rndseed'};
                   11036:     } else {
                   11037: 	$which =&get_rand_alg($courseid);
                   11038:     }
1.491     albertel 11039:     if (defined(&getCODE())) {
1.675     albertel 11040: 	if ($which eq '64bit5') {
                   11041: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   11042: 	} elsif ($which eq '64bit4') {
1.575     albertel 11043: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   11044: 	} else {
                   11045: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   11046: 	}
1.675     albertel 11047:     } elsif ($which eq '64bit5') {
                   11048: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 11049:     } elsif ($which eq '64bit4') {
                   11050: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 11051:     } elsif ($which eq '64bit3') {
                   11052: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 11053:     } elsif ($which eq '64bit2') {
                   11054: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 11055:     } elsif ($which eq '64bit') {
                   11056: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   11057:     }
                   11058:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   11059: }
                   11060: 
                   11061: sub rndseed_32bit {
                   11062:     my ($symb,$courseid,$domain,$username)=@_;
                   11063:     {
                   11064: 	use integer;
                   11065: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   11066: 	my $symbseed=numval($symb) << 22;
                   11067: 	my $namechck=unpack("%32C*",$username) << 17;
                   11068: 	my $nameseed=numval($username) << 12;
                   11069: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   11070: 	my $courseseed=unpack("%32C*",$courseid);
                   11071: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 11072: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11073: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11074: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 11075: 	return $num;
                   11076:     }
                   11077: }
                   11078: 
                   11079: sub rndseed_64bit {
                   11080:     my ($symb,$courseid,$domain,$username)=@_;
                   11081:     {
                   11082: 	use integer;
                   11083: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   11084: 	my $symbseed=numval($symb) << 10;
                   11085: 	my $namechck=unpack("%32S*",$username);
                   11086: 	
                   11087: 	my $nameseed=numval($username) << 21;
                   11088: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   11089: 	my $courseseed=unpack("%32S*",$courseid);
                   11090: 	
                   11091: 	my $num1=$symbchck+$symbseed+$namechck;
                   11092: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11093: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11094: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11095: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 11096: 	return "$num1,$num2";
1.155     albertel 11097:     }
1.366     albertel 11098: }
                   11099: 
1.443     albertel 11100: sub rndseed_64bit2 {
                   11101:     my ($symb,$courseid,$domain,$username)=@_;
                   11102:     {
                   11103: 	use integer;
                   11104: 	# strings need to be an even # of cahracters long, it it is odd the
                   11105:         # last characters gets thrown away
                   11106: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11107: 	my $symbseed=numval($symb) << 10;
                   11108: 	my $namechck=unpack("%32S*",$username.' ');
                   11109: 	
                   11110: 	my $nameseed=numval($username) << 21;
1.501     albertel 11111: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11112: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11113: 	
                   11114: 	my $num1=$symbchck+$symbseed+$namechck;
                   11115: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11116: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11117: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 11118: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 11119: 	return "$num1,$num2";
                   11120:     }
                   11121: }
                   11122: 
                   11123: sub rndseed_64bit3 {
                   11124:     my ($symb,$courseid,$domain,$username)=@_;
                   11125:     {
                   11126: 	use integer;
                   11127: 	# strings need to be an even # of cahracters long, it it is odd the
                   11128:         # last characters gets thrown away
                   11129: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11130: 	my $symbseed=numval2($symb) << 10;
                   11131: 	my $namechck=unpack("%32S*",$username.' ');
                   11132: 	
                   11133: 	my $nameseed=numval2($username) << 21;
1.443     albertel 11134: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11135: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11136: 	
                   11137: 	my $num1=$symbchck+$symbseed+$namechck;
                   11138: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11139: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11140: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 11141: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11142: 	
1.503     albertel 11143: 	return "$num1:$num2";
1.443     albertel 11144:     }
                   11145: }
                   11146: 
1.575     albertel 11147: sub rndseed_64bit4 {
                   11148:     my ($symb,$courseid,$domain,$username)=@_;
                   11149:     {
                   11150: 	use integer;
                   11151: 	# strings need to be an even # of cahracters long, it it is odd the
                   11152:         # last characters gets thrown away
                   11153: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11154: 	my $symbseed=numval3($symb) << 10;
                   11155: 	my $namechck=unpack("%32S*",$username.' ');
                   11156: 	
                   11157: 	my $nameseed=numval3($username) << 21;
                   11158: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11159: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11160: 	
                   11161: 	my $num1=$symbchck+$symbseed+$namechck;
                   11162: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11163: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11164: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 11165: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11166: 	
1.575     albertel 11167: 	return "$num1:$num2";
                   11168:     }
                   11169: }
                   11170: 
1.675     albertel 11171: sub rndseed_64bit5 {
                   11172:     my ($symb,$courseid,$domain,$username)=@_;
                   11173:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   11174:     return "$num1:$num2";
                   11175: }
                   11176: 
1.366     albertel 11177: sub rndseed_CODE_64bit {
                   11178:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 11179:     {
1.366     albertel 11180: 	use integer;
1.443     albertel 11181: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 11182: 	my $symbseed=numval2($symb);
1.491     albertel 11183: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11184: 	my $CODEseed=numval(&getCODE());
1.443     albertel 11185: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 11186: 	my $num1=$symbseed+$CODEchck;
                   11187: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11188: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11189: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 11190: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11191: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 11192: 	return "$num1:$num2";
1.366     albertel 11193:     }
                   11194: }
                   11195: 
1.575     albertel 11196: sub rndseed_CODE_64bit4 {
                   11197:     my ($symb,$courseid,$domain,$username)=@_;
                   11198:     {
                   11199: 	use integer;
                   11200: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   11201: 	my $symbseed=numval3($symb);
                   11202: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11203: 	my $CODEseed=numval3(&getCODE());
                   11204: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11205: 	my $num1=$symbseed+$CODEchck;
                   11206: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11207: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11208: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 11209: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11210: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   11211: 	return "$num1:$num2";
                   11212:     }
                   11213: }
                   11214: 
1.675     albertel 11215: sub rndseed_CODE_64bit5 {
                   11216:     my ($symb,$courseid,$domain,$username)=@_;
                   11217:     my $code = &getCODE();
                   11218:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   11219:     return "$num1:$num2";
                   11220: }
                   11221: 
1.366     albertel 11222: sub setup_random_from_rndseed {
                   11223:     my ($rndseed)=@_;
1.503     albertel 11224:     if ($rndseed =~/([,:])/) {
                   11225: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 11226: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   11227:     } else {
                   11228: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 11229:     }
1.36      albertel 11230: }
                   11231: 
1.474     albertel 11232: sub latest_receipt_algorithm_id {
1.835     albertel 11233:     return 'receipt3';
1.474     albertel 11234: }
                   11235: 
1.480     www      11236: sub recunique {
                   11237:     my $fucourseid=shift;
                   11238:     my $unique;
1.835     albertel 11239:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   11240: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11241: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      11242:     } else {
                   11243: 	$unique=$perlvar{'lonReceipt'};
                   11244:     }
                   11245:     return unpack("%32C*",$unique);
                   11246: }
                   11247: 
                   11248: sub recprefix {
                   11249:     my $fucourseid=shift;
                   11250:     my $prefix;
1.835     albertel 11251:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   11252: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11253: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      11254:     } else {
                   11255: 	$prefix=$perlvar{'lonHostID'};
                   11256:     }
                   11257:     return unpack("%32C*",$prefix);
                   11258: }
                   11259: 
1.76      www      11260: sub ireceipt {
1.474     albertel 11261:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 11262: 
                   11263:     my $return =&recprefix($fucourseid).'-';
                   11264: 
                   11265:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   11266: 	$env{'request.state'} eq 'construct') {
                   11267: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   11268: 	return $return;
                   11269:     }
                   11270: 
1.76      www      11271:     my $cuname=unpack("%32C*",$funame);
                   11272:     my $cudom=unpack("%32C*",$fudom);
                   11273:     my $cucourseid=unpack("%32C*",$fucourseid);
                   11274:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      11275:     my $cunique=&recunique($fucourseid);
1.474     albertel 11276:     my $cpart=unpack("%32S*",$part);
1.835     albertel 11277:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   11278: 
1.790     albertel 11279: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 11280: 			       
                   11281: 	$return.= ($cunique%$cuname+
                   11282: 		   $cunique%$cudom+
                   11283: 		   $cusymb%$cuname+
                   11284: 		   $cusymb%$cudom+
                   11285: 		   $cucourseid%$cuname+
                   11286: 		   $cucourseid%$cudom+
                   11287: 		   $cpart%$cuname+
                   11288: 		   $cpart%$cudom);
                   11289:     } else {
                   11290: 	$return.= ($cunique%$cuname+
                   11291: 		   $cunique%$cudom+
                   11292: 		   $cusymb%$cuname+
                   11293: 		   $cusymb%$cudom+
                   11294: 		   $cucourseid%$cuname+
                   11295: 		   $cucourseid%$cudom);
                   11296:     }
                   11297:     return $return;
1.76      www      11298: }
                   11299: 
                   11300: sub receipt {
1.474     albertel 11301:     my ($part)=@_;
1.790     albertel 11302:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 11303:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      11304: }
1.260     ng       11305: 
1.790     albertel 11306: sub whichuser {
                   11307:     my ($passedsymb)=@_;
                   11308:     my ($symb,$courseid,$domain,$name,$publicuser);
                   11309:     if (defined($env{'form.grade_symb'})) {
                   11310: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   11311: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   11312: 	if (!$allowed &&
                   11313: 	    exists($env{'request.course.sec'}) &&
                   11314: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   11315: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   11316: 			      '/'.$env{'request.course.sec'});
                   11317: 	}
                   11318: 	if ($allowed) {
                   11319: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   11320: 	    $courseid=$tmp_courseid;
                   11321: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   11322: 	    ($name)=&get_env_multiple('form.grade_username');
                   11323: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   11324: 	}
                   11325:     }
                   11326:     if (!$passedsymb) {
                   11327: 	$symb=&symbread();
                   11328:     } else {
                   11329: 	$symb=$passedsymb;
                   11330:     }
                   11331:     $courseid=$env{'request.course.id'};
                   11332:     $domain=$env{'user.domain'};
                   11333:     $name=$env{'user.name'};
                   11334:     if ($name eq 'public' && $domain eq 'public') {
                   11335: 	if (!defined($env{'form.username'})) {
                   11336: 	    $env{'form.username'}.=time.rand(10000000);
                   11337: 	}
                   11338: 	$name.=$env{'form.username'};
                   11339:     }
                   11340:     return ($symb,$courseid,$domain,$name,$publicuser);
                   11341: 
                   11342: }
                   11343: 
1.36      albertel 11344: # ------------------------------------------------------------ Serves up a file
1.472     albertel 11345: # returns either the contents of the file or 
                   11346: # -1 if the file doesn't exist
1.481     raeburn  11347: #
                   11348: # if the target is a file that was uploaded via DOCS, 
                   11349: # a check will be made to see if a current copy exists on the local server,
                   11350: # if it does this will be served, otherwise a copy will be retrieved from
                   11351: # the home server for the course and stored in /home/httpd/html/userfiles on
                   11352: # the local server.   
1.472     albertel 11353: 
1.36      albertel 11354: sub getfile {
1.538     albertel 11355:     my ($file) = @_;
1.609     banghart 11356:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 11357:     &repcopy($file);
                   11358:     return &readfile($file);
                   11359: }
                   11360: 
                   11361: sub repcopy_userfile {
                   11362:     my ($file)=@_;
1.1142    raeburn  11363:     my $londocroot = $perlvar{'lonDocRoot'};
                   11364:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  11365:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 11366:     my ($cdom,$cnum,$filename) = 
1.811     albertel 11367: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 11368:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   11369:     if (-e "$file") {
1.828     www      11370: # we already have a local copy, check it out
1.538     albertel 11371: 	my @fileinfo = stat($file);
1.828     www      11372: 	my $rtncode;
                   11373: 	my $info;
1.538     albertel 11374: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 11375: 	if ($lwpresp ne 'ok') {
1.828     www      11376: # there is no such file anymore, even though we had a local copy
1.482     albertel 11377: 	    if ($rtncode eq '404') {
1.538     albertel 11378: 		unlink($file);
1.482     albertel 11379: 	    }
                   11380: 	    return -1;
                   11381: 	}
                   11382: 	if ($info < $fileinfo[9]) {
1.828     www      11383: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  11384: 	    return 'ok';
1.828     www      11385: 	} else {
                   11386: # the file is outdated, get rid of it
                   11387: 	    unlink($file);
1.482     albertel 11388: 	}
1.828     www      11389:     }
                   11390: # one way or the other, at this point, we don't have the file
                   11391: # construct the correct path for the file
                   11392:     my @parts = ($cdom,$cnum); 
                   11393:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   11394: 	push @parts, split(/\//,$1);
                   11395:     }
                   11396:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   11397:     foreach my $part (@parts) {
                   11398: 	$path .= '/'.$part;
                   11399: 	if (!-e $path) {
                   11400: 	    mkdir($path,0770);
1.482     albertel 11401: 	}
                   11402:     }
1.828     www      11403: # now the path exists for sure
                   11404: # get a user agent
                   11405:     my $ua=new LWP::UserAgent;
                   11406:     my $transferfile=$file.'.in.transfer';
                   11407: # FIXME: this should flock
                   11408:     if (-e $transferfile) { return 'ok'; }
                   11409:     my $request;
                   11410:     $uri=~s/^\///;
1.980     raeburn  11411:     my $homeserver = &homeserver($cnum,$cdom);
                   11412:     my $protocol = $protocol{$homeserver};
                   11413:     $protocol = 'http' if ($protocol ne 'https');
                   11414:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      11415:     my $response=$ua->request($request,$transferfile);
                   11416: # did it work?
                   11417:     if ($response->is_error()) {
                   11418: 	unlink($transferfile);
                   11419: 	&logthis("Userfile repcopy failed for $uri");
                   11420: 	return -1;
                   11421:     }
                   11422: # worked, rename the transfer file
                   11423:     rename($transferfile,$file);
1.607     raeburn  11424:     return 'ok';
1.481     raeburn  11425: }
                   11426: 
1.517     albertel 11427: sub tokenwrapper {
                   11428:     my $uri=shift;
1.980     raeburn  11429:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 11430:     $uri=~s|^/||;
1.620     albertel 11431:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 11432:     my $token=$1;
1.552     albertel 11433:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   11434:     if ($udom && $uname && $file) {
                   11435: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  11436:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  11437:         my $homeserver = &homeserver($uname,$udom);
                   11438:         my $protocol = $protocol{$homeserver};
                   11439:         $protocol = 'http' if ($protocol ne 'https');
                   11440:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 11441:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   11442:                                '&tokenissued='.$perlvar{'lonHostID'};
                   11443:     } else {
                   11444:         return '/adm/notfound.html';
                   11445:     }
                   11446: }
                   11447: 
1.828     www      11448: # call with reqtype HEAD: get last modification time
                   11449: # call with reqtype GET: get the file contents
                   11450: # Do not call this with reqtype GET for large files! It loads everything into memory
                   11451: #
1.481     raeburn  11452: sub getuploaded {
                   11453:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   11454:     $uri=~s/^\///;
1.980     raeburn  11455:     my $homeserver = &homeserver($cnum,$cdom);
                   11456:     my $protocol = $protocol{$homeserver};
                   11457:     $protocol = 'http' if ($protocol ne 'https');
                   11458:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  11459:     my $ua=new LWP::UserAgent;
                   11460:     my $request=new HTTP::Request($reqtype,$uri);
                   11461:     my $response=$ua->request($request);
                   11462:     $$rtncode = $response->code;
1.482     albertel 11463:     if (! $response->is_success()) {
                   11464: 	return 'failed';
                   11465:     }      
                   11466:     if ($reqtype eq 'HEAD') {
1.486     www      11467: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 11468:     } elsif ($reqtype eq 'GET') {
                   11469: 	$$info = $response->content;
1.472     albertel 11470:     }
1.482     albertel 11471:     return 'ok';
1.36      albertel 11472: }
                   11473: 
1.481     raeburn  11474: sub readfile {
                   11475:     my $file = shift;
                   11476:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   11477:     my $fh;
                   11478:     open($fh,"<$file");
                   11479:     my $a='';
1.800     albertel 11480:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  11481:     return $a;
                   11482: }
                   11483: 
1.36      albertel 11484: sub filelocation {
1.590     banghart 11485:     my ($dir,$file) = @_;
                   11486:     my $location;
                   11487:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 11488: 
                   11489:     if ($file =~ m-^/adm/-) {
                   11490: 	$file=~s-^/adm/wrapper/-/-;
                   11491: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   11492:     }
1.882     albertel 11493: 
1.1139    www      11494:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  11495:         $location = $file;
1.609     banghart 11496:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 11497:         my ($udom,$uname,$filename)=
1.811     albertel 11498:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 11499:         my $home=&homeserver($uname,$udom);
                   11500:         my $is_me=0;
                   11501:         my @ids=&current_machine_ids();
                   11502:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   11503:         if ($is_me) {
1.1117    foxr     11504:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 11505:         } else {
                   11506:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   11507:   	      $udom.'/'.$uname.'/'.$filename;
                   11508:         }
1.882     albertel 11509:     } elsif ($file =~ m-^/adm/-) {
                   11510: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 11511:     } else {
                   11512:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      11513:         $file=~s:^/(res|priv)/:/:;
                   11514:         my $space=$1;
1.590     banghart 11515:         if ( !( $file =~ m:^/:) ) {
                   11516:             $location = $dir. '/'.$file;
                   11517:         } else {
1.1142    raeburn  11518:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 11519:         }
1.59      albertel 11520:     }
1.590     banghart 11521:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 11522:     while ($location=~m{/\.\./}) {
                   11523: 	if ($location =~ m{/[^/]+/\.\./}) {
                   11524: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   11525: 	} else {
                   11526: 	    $location=~ s{/\.\./}{/}g;
                   11527: 	}
                   11528:     } #remove dir/..
1.590     banghart 11529:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   11530:     return $location;
1.46      www      11531: }
1.36      albertel 11532: 
1.46      www      11533: sub hreflocation {
                   11534:     my ($dir,$file)=@_;
1.980     raeburn  11535:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 11536: 	$file=filelocation($dir,$file);
1.700     albertel 11537:     } elsif ($file=~m-^/adm/-) {
                   11538: 	$file=~s-^/adm/wrapper/-/-;
                   11539: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 11540:     }
                   11541:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   11542: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   11543:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  11544: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   11545: 	        {/uploaded/$1/$2/}x;
1.46      www      11546:     }
1.913     albertel 11547:     if ($file=~ m{^/userfiles/}) {
                   11548: 	$file =~ s{^/userfiles/}{/uploaded/};
                   11549:     }
1.462     albertel 11550:     return $file;
1.465     albertel 11551: }
                   11552: 
1.1139    www      11553: 
                   11554: 
                   11555: 
                   11556: 
1.465     albertel 11557: sub current_machine_domains {
1.853     albertel 11558:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   11559: }
                   11560: 
                   11561: sub machine_domains {
                   11562:     my ($hostname) = @_;
1.465     albertel 11563:     my @domains;
1.838     albertel 11564:     my %hostname = &all_hostnames();
1.465     albertel 11565:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  11566: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 11567: 	if ($hostname eq $name) {
1.844     albertel 11568: 	    push(@domains,&host_domain($id));
1.465     albertel 11569: 	}
                   11570:     }
                   11571:     return @domains;
                   11572: }
                   11573: 
                   11574: sub current_machine_ids {
1.853     albertel 11575:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   11576: }
                   11577: 
                   11578: sub machine_ids {
                   11579:     my ($hostname) = @_;
                   11580:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 11581:     my @ids;
1.888     albertel 11582:     my %name_to_host = &all_names();
1.889     albertel 11583:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   11584: 	return @{ $name_to_host{$hostname} };
                   11585:     }
                   11586:     return;
1.31      www      11587: }
                   11588: 
1.824     raeburn  11589: sub additional_machine_domains {
                   11590:     my @domains;
                   11591:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   11592:     while( my $line = <$fh>) {
                   11593:         $line =~ s/\s//g;
                   11594:         push(@domains,$line);
                   11595:     }
                   11596:     return @domains;
                   11597: }
                   11598: 
                   11599: sub default_login_domain {
                   11600:     my $domain = $perlvar{'lonDefDomain'};
                   11601:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   11602:     foreach my $posdom (&current_machine_domains(),
                   11603:                         &additional_machine_domains()) {
                   11604:         if (lc($posdom) eq lc($testdomain)) {
                   11605:             $domain=$posdom;
                   11606:             last;
                   11607:         }
                   11608:     }
                   11609:     return $domain;
                   11610: }
                   11611: 
1.31      www      11612: # ------------------------------------------------------------- Declutters URLs
                   11613: 
                   11614: sub declutter {
                   11615:     my $thisfn=shift;
1.569     albertel 11616:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 11617:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      11618:     $thisfn=~s/^\///;
1.697     albertel 11619:     $thisfn=~s|^adm/wrapper/||;
                   11620:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      11621:     $thisfn=~s/^res\///;
1.1172    bisitz   11622:     $thisfn=~s/^priv\///;
1.1032    raeburn  11623:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   11624:         $thisfn=~s/\?.+$//;
                   11625:     }
1.268     www      11626:     return $thisfn;
                   11627: }
                   11628: 
                   11629: # ------------------------------------------------------------- Clutter up URLs
                   11630: 
                   11631: sub clutter {
                   11632:     my $thisfn='/'.&declutter(shift);
1.887     albertel 11633:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 11634: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      11635:        $thisfn='/res'.$thisfn; 
                   11636:     }
1.1031    raeburn  11637:     if ($thisfn !~m|^/adm|) {
                   11638: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 11639: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 11640: 	} else {
                   11641: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   11642: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 11643: 	    if ($embstyle eq 'ssi'
                   11644: 		|| ($embstyle eq 'hdn')
                   11645: 		|| ($embstyle eq 'rat')
                   11646: 		|| ($embstyle eq 'prv')
                   11647: 		|| ($embstyle eq 'ign')) {
                   11648: 		#do nothing with these
                   11649: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 11650: 		|| ($embstyle eq 'emb')
                   11651: 		|| ($embstyle eq 'wrp')) {
                   11652: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 11653: 	    } elsif ($embstyle eq 'unk'
                   11654: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 11655: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 11656: 	    } else {
1.718     www      11657: #		&logthis("Got a blank emb style");
1.695     albertel 11658: 	    }
1.694     albertel 11659: 	}
                   11660:     }
1.31      www      11661:     return $thisfn;
1.12      www      11662: }
                   11663: 
1.787     albertel 11664: sub clutter_with_no_wrapper {
                   11665:     my $uri = &clutter(shift);
                   11666:     if ($uri =~ m-^/adm/-) {
                   11667: 	$uri =~ s-^/adm/wrapper/-/-;
                   11668: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   11669:     }
                   11670:     return $uri;
                   11671: }
                   11672: 
1.557     albertel 11673: sub freeze_escape {
                   11674:     my ($value)=@_;
                   11675:     if (ref($value)) {
                   11676: 	$value=&nfreeze($value);
                   11677: 	return '__FROZEN__'.&escape($value);
                   11678:     }
                   11679:     return &escape($value);
                   11680: }
                   11681: 
1.11      www      11682: 
1.557     albertel 11683: sub thaw_unescape {
                   11684:     my ($value)=@_;
                   11685:     if ($value =~ /^__FROZEN__/) {
                   11686: 	substr($value,0,10,undef);
                   11687: 	$value=&unescape($value);
                   11688: 	return &thaw($value);
                   11689:     }
                   11690:     return &unescape($value);
                   11691: }
                   11692: 
1.436     albertel 11693: sub correct_line_ends {
                   11694:     my ($result)=@_;
                   11695:     $$result =~s/\r\n/\n/mg;
                   11696:     $$result =~s/\r/\n/mg;
1.415     albertel 11697: }
1.1       albertel 11698: # ================================================================ Main Program
                   11699: 
1.184     www      11700: sub goodbye {
1.204     albertel 11701:    &logthis("Starting Shut down");
1.443     albertel 11702: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 11703:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 11704: #converted
1.599     albertel 11705: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 11706:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   11707: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   11708: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 11709: #1.1 only
1.870     albertel 11710: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   11711: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   11712: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   11713: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   11714:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 11715:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   11716:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      11717:    &flushcourselogs();
                   11718:    &logthis("Shutting down");
                   11719: }
                   11720: 
1.852     albertel 11721: sub get_dns {
1.1172.2.17  raeburn  11722:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 11723:     if (!$ignore_cache) {
                   11724: 	my ($content,$cached)=
                   11725: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   11726: 	if ($cached) {
1.1172.2.17  raeburn  11727: 	    &$func($content,$hashref);
1.869     albertel 11728: 	    return;
                   11729: 	}
                   11730:     }
                   11731: 
                   11732:     my %alldns;
1.852     albertel 11733:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11734:     foreach my $dns (<$config>) {
                   11735: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  11736:         my $line = $1;
                   11737:         my ($host,$protocol) = split(/:/,$line);
                   11738:         if ($protocol ne 'https') {
                   11739:             $protocol = 'http';
                   11740:         }
                   11741: 	$alldns{$host} = $protocol;
1.869     albertel 11742:     }
                   11743:     while (%alldns) {
                   11744: 	my ($dns) = keys(%alldns);
1.852     albertel 11745: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  11746:         $ua->timeout(30);
1.979     raeburn  11747: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 11748: 	my $response=$ua->request($request);
1.979     raeburn  11749:         delete($alldns{$dns});
1.852     albertel 11750: 	next if ($response->is_error());
                   11751: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  11752:         unless ($nocache) {
1.1172.2.23  raeburn  11753: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  11754:         }
                   11755: 	&$func(\@content,$hashref);
1.869     albertel 11756: 	return;
1.852     albertel 11757:     }
                   11758:     close($config);
1.871     albertel 11759:     my $which = (split('/',$url))[3];
                   11760:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   11761:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 11762:     my @content = <$config>;
1.1172.2.17  raeburn  11763:     &$func(\@content,$hashref);
                   11764:     return;
                   11765: }
                   11766: 
                   11767: # ------------------------------------------------------Get DNS checksums file
                   11768: sub parse_dns_checksums_tab {
                   11769:     my ($lines,$hashref) = @_;
                   11770:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
                   11771:     my $loncaparev = &get_server_loncaparev($machine_dom);
                   11772:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   11773:     my (%chksum,%revnum);
                   11774:     if (ref($lines) eq 'ARRAY') {
                   11775:         chomp(@{$lines});
                   11776:         my $versions = shift(@{$lines});
                   11777:         my %supported;
                   11778:         if ($versions =~ /^VERSIONS\:([\w\.\,]+)$/) {
                   11779:             my $releaseslist = $1;
                   11780:             if ($releaseslist =~ /,/) {
                   11781:                 map { $supported{$_} = 1; } split(/,/,$releaseslist);
                   11782:             } elsif ($releaseslist) {
                   11783:                 $supported{$releaseslist} = 1;
                   11784:             }
                   11785:         }
                   11786:         if ($supported{$release}) {
                   11787:             my $matchthis = 0;
                   11788:             foreach my $line (@{$lines}) {
                   11789:                 if ($line =~ /^(\d[\w\.]+)$/) {
                   11790:                     if ($matchthis) {
                   11791:                         last;
                   11792:                     } elsif ($1 eq $release) {
                   11793:                         $matchthis = 1;
                   11794:                     }
                   11795:                 } elsif ($matchthis) {
                   11796:                     my ($file,$version,$shasum) = split(/,/,$line);
                   11797:                     $chksum{$file} = $shasum;
                   11798:                     $revnum{$file} = $version;
                   11799:                 }
                   11800:             }
                   11801:             if (ref($hashref) eq 'HASH') {
                   11802:                 %{$hashref} = (
                   11803:                                 sums     => \%chksum,
                   11804:                                 versions => \%revnum,
                   11805:                               );
                   11806:             }
                   11807:         }
                   11808:     }
1.869     albertel 11809:     return;
1.852     albertel 11810: }
1.1172.2.17  raeburn  11811: 
                   11812: sub fetch_dns_checksums {
                   11813:     my %checksums;
                   11814:     &get_dns('/adm/dns/checksums',\&parse_dns_checksums_tab,1,1,
                   11815:              \%checksums);
                   11816:     return \%checksums;
                   11817: }
                   11818: 
1.327     albertel 11819: # ------------------------------------------------------------ Read domain file
                   11820: {
1.852     albertel 11821:     my $loaded;
1.846     albertel 11822:     my %domain;
                   11823: 
1.852     albertel 11824:     sub parse_domain_tab {
                   11825: 	my ($lines) = @_;
                   11826: 	foreach my $line (@$lines) {
                   11827: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      11828: 
1.846     albertel 11829: 	    chomp($line);
1.852     albertel 11830: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 11831: 	    my %this_domain;
                   11832: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   11833: 			       'lang_def', 'city', 'longi', 'lati',
                   11834: 			       'primary') {
                   11835: 		$this_domain{$field} = shift(@elements);
                   11836: 	    }
                   11837: 	    $domain{$name} = \%this_domain;
1.852     albertel 11838: 	}
                   11839:     }
1.864     albertel 11840: 
                   11841:     sub reset_domain_info {
                   11842: 	undef($loaded);
                   11843: 	undef(%domain);
                   11844:     }
                   11845: 
1.852     albertel 11846:     sub load_domain_tab {
1.869     albertel 11847: 	my ($ignore_cache) = @_;
                   11848: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 11849: 	my $fh;
                   11850: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   11851: 	    my @lines = <$fh>;
                   11852: 	    &parse_domain_tab(\@lines);
1.448     albertel 11853: 	}
1.852     albertel 11854: 	close($fh);
                   11855: 	$loaded = 1;
1.327     albertel 11856:     }
1.846     albertel 11857: 
                   11858:     sub domain {
1.852     albertel 11859: 	&load_domain_tab() if (!$loaded);
                   11860: 
1.846     albertel 11861: 	my ($name,$what) = @_;
                   11862: 	return if ( !exists($domain{$name}) );
                   11863: 
                   11864: 	if (!$what) {
                   11865: 	    return $domain{$name}{'description'};
                   11866: 	}
                   11867: 	return $domain{$name}{$what};
                   11868:     }
1.974     raeburn  11869: 
                   11870:     sub domain_info {
                   11871:         &load_domain_tab() if (!$loaded);
                   11872:         return %domain;
                   11873:     }
                   11874: 
1.327     albertel 11875: }
                   11876: 
                   11877: 
1.1       albertel 11878: # ------------------------------------------------------------- Read hosts file
                   11879: {
1.838     albertel 11880:     my %hostname;
1.844     albertel 11881:     my %hostdom;
1.845     albertel 11882:     my %libserv;
1.852     albertel 11883:     my $loaded;
1.888     albertel 11884:     my %name_to_host;
1.1074    raeburn  11885:     my %internetdom;
1.1107    raeburn  11886:     my %LC_dns_serv;
1.852     albertel 11887: 
                   11888:     sub parse_hosts_tab {
                   11889: 	my ($file) = @_;
                   11890: 	foreach my $configline (@$file) {
                   11891: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  11892:             chomp($configline);
                   11893: 	    if ($configline =~ /^\^/) {
                   11894:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   11895:                     $LC_dns_serv{$1} = 1;
                   11896:                 }
                   11897:                 next;
                   11898:             }
1.1074    raeburn  11899: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 11900: 	    $name=~s/\s//g;
                   11901: 	    if ($id && $domain && $role && $name) {
                   11902: 		$hostname{$id}=$name;
1.888     albertel 11903: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 11904: 		$hostdom{$id}=$domain;
                   11905: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  11906:                 if (defined($protocol)) {
                   11907:                     if ($protocol eq 'https') {
                   11908:                         $protocol{$id} = $protocol;
                   11909:                     } else {
                   11910:                         $protocol{$id} = 'http'; 
                   11911:                     }
1.968     raeburn  11912:                 } else {
1.969     raeburn  11913:                     $protocol{$id} = 'http';
1.968     raeburn  11914:                 }
1.1074    raeburn  11915:                 if (defined($intdom)) {
                   11916:                     $internetdom{$id} = $intdom;
                   11917:                 }
1.852     albertel 11918: 	    }
                   11919: 	}
                   11920:     }
1.864     albertel 11921:     
                   11922:     sub reset_hosts_info {
1.897     albertel 11923: 	&purge_remembered();
1.864     albertel 11924: 	&reset_domain_info();
                   11925: 	&reset_hosts_ip_info();
1.892     albertel 11926: 	undef(%name_to_host);
1.864     albertel 11927: 	undef(%hostname);
                   11928: 	undef(%hostdom);
                   11929: 	undef(%libserv);
                   11930: 	undef($loaded);
                   11931:     }
1.1       albertel 11932: 
1.852     albertel 11933:     sub load_hosts_tab {
1.869     albertel 11934: 	my ($ignore_cache) = @_;
                   11935: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 11936: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11937: 	my @config = <$config>;
                   11938: 	&parse_hosts_tab(\@config);
                   11939: 	close($config);
                   11940: 	$loaded=1;
1.1       albertel 11941:     }
1.852     albertel 11942: 
1.838     albertel 11943:     sub hostname {
1.852     albertel 11944: 	&load_hosts_tab() if (!$loaded);
                   11945: 
1.838     albertel 11946: 	my ($lonid) = @_;
                   11947: 	return $hostname{$lonid};
                   11948:     }
1.845     albertel 11949: 
1.838     albertel 11950:     sub all_hostnames {
1.852     albertel 11951: 	&load_hosts_tab() if (!$loaded);
                   11952: 
1.838     albertel 11953: 	return %hostname;
                   11954:     }
1.845     albertel 11955: 
1.888     albertel 11956:     sub all_names {
                   11957: 	&load_hosts_tab() if (!$loaded);
                   11958: 
                   11959: 	return %name_to_host;
                   11960:     }
                   11961: 
1.974     raeburn  11962:     sub all_host_domain {
                   11963:         &load_hosts_tab() if (!$loaded);
                   11964:         return %hostdom;
                   11965:     }
                   11966: 
1.845     albertel 11967:     sub is_library {
1.852     albertel 11968: 	&load_hosts_tab() if (!$loaded);
                   11969: 
1.845     albertel 11970: 	return exists($libserv{$_[0]});
                   11971:     }
                   11972: 
                   11973:     sub all_library {
1.852     albertel 11974: 	&load_hosts_tab() if (!$loaded);
                   11975: 
1.845     albertel 11976: 	return %libserv;
                   11977:     }
                   11978: 
1.1062    droeschl 11979:     sub unique_library {
                   11980: 	#2x reverse removes all hostnames that appear more than once
                   11981:         my %unique = reverse &all_library();
                   11982:         return reverse %unique;
                   11983:     }
                   11984: 
1.841     albertel 11985:     sub get_servers {
1.852     albertel 11986: 	&load_hosts_tab() if (!$loaded);
                   11987: 
1.841     albertel 11988: 	my ($domain,$type) = @_;
                   11989: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   11990: 	                                          : %hostname;
                   11991: 	my %result;
1.842     albertel 11992: 	if (ref($domain) eq 'ARRAY') {
                   11993: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 11994: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 11995: 		    $result{$host} = $hostname;
                   11996: 		}
                   11997: 	    }
                   11998: 	} else {
                   11999: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   12000: 		if ($hostdom{$host} eq $domain) {
                   12001: 		    $result{$host} = $hostname;
                   12002: 		}
1.841     albertel 12003: 	    }
                   12004: 	}
                   12005: 	return %result;
                   12006:     }
1.845     albertel 12007: 
1.1062    droeschl 12008:     sub get_unique_servers {
                   12009:         my %unique = reverse &get_servers(@_);
                   12010: 	return reverse %unique;
                   12011:     }
                   12012: 
1.844     albertel 12013:     sub host_domain {
1.852     albertel 12014: 	&load_hosts_tab() if (!$loaded);
                   12015: 
1.844     albertel 12016: 	my ($lonid) = @_;
                   12017: 	return $hostdom{$lonid};
                   12018:     }
                   12019: 
1.841     albertel 12020:     sub all_domains {
1.852     albertel 12021: 	&load_hosts_tab() if (!$loaded);
                   12022: 
1.841     albertel 12023: 	my %seen;
                   12024: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   12025: 	return @uniq;
                   12026:     }
1.1074    raeburn  12027: 
                   12028:     sub internet_dom {
                   12029:         &load_hosts_tab() if (!$loaded);
                   12030: 
                   12031:         my ($lonid) = @_;
                   12032:         return $internetdom{$lonid};
                   12033:     }
1.1107    raeburn  12034: 
                   12035:     sub is_LC_dns {
                   12036:         &load_hosts_tab() if (!$loaded);
                   12037: 
                   12038:         my ($hostname) = @_;
                   12039:         return exists($LC_dns_serv{$hostname});
                   12040:     }
                   12041: 
1.1       albertel 12042: }
                   12043: 
1.847     albertel 12044: { 
                   12045:     my %iphost;
1.856     albertel 12046:     my %name_to_ip;
                   12047:     my %lonid_to_ip;
1.869     albertel 12048: 
1.847     albertel 12049:     sub get_hosts_from_ip {
                   12050: 	my ($ip) = @_;
                   12051: 	my %iphosts = &get_iphost();
                   12052: 	if (ref($iphosts{$ip})) {
                   12053: 	    return @{$iphosts{$ip}};
                   12054: 	}
                   12055: 	return;
1.839     albertel 12056:     }
1.864     albertel 12057:     
                   12058:     sub reset_hosts_ip_info {
                   12059: 	undef(%iphost);
                   12060: 	undef(%name_to_ip);
                   12061: 	undef(%lonid_to_ip);
                   12062:     }
1.856     albertel 12063: 
                   12064:     sub get_host_ip {
                   12065: 	my ($lonid) = @_;
                   12066: 	if (exists($lonid_to_ip{$lonid})) {
                   12067: 	    return $lonid_to_ip{$lonid};
                   12068: 	}
                   12069: 	my $name=&hostname($lonid);
                   12070:    	my $ip = gethostbyname($name);
                   12071: 	return if (!$ip || length($ip) ne 4);
                   12072: 	$ip=inet_ntoa($ip);
                   12073: 	$name_to_ip{$name}   = $ip;
                   12074: 	$lonid_to_ip{$lonid} = $ip;
                   12075: 	return $ip;
                   12076:     }
1.847     albertel 12077:     
                   12078:     sub get_iphost {
1.869     albertel 12079: 	my ($ignore_cache) = @_;
1.894     albertel 12080: 
1.869     albertel 12081: 	if (!$ignore_cache) {
                   12082: 	    if (%iphost) {
                   12083: 		return %iphost;
                   12084: 	    }
                   12085: 	    my ($ip_info,$cached)=
                   12086: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   12087: 	    if ($cached) {
                   12088: 		%iphost      = %{$ip_info->[0]};
                   12089: 		%name_to_ip  = %{$ip_info->[1]};
                   12090: 		%lonid_to_ip = %{$ip_info->[2]};
                   12091: 		return %iphost;
                   12092: 	    }
                   12093: 	}
1.894     albertel 12094: 
                   12095: 	# get yesterday's info for fallback
                   12096: 	my %old_name_to_ip;
                   12097: 	my ($ip_info,$cached)=
                   12098: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   12099: 	if ($cached) {
                   12100: 	    %old_name_to_ip = %{$ip_info->[1]};
                   12101: 	}
                   12102: 
1.888     albertel 12103: 	my %name_to_host = &all_names();
                   12104: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 12105: 	    my $ip;
                   12106: 	    if (!exists($name_to_ip{$name})) {
                   12107: 		$ip = gethostbyname($name);
                   12108: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 12109: 		    if (defined($old_name_to_ip{$name})) {
                   12110: 			$ip = $old_name_to_ip{$name};
                   12111: 			&logthis("Can't find $name defaulting to old $ip");
                   12112: 		    } else {
                   12113: 			&logthis("Name $name no IP found");
                   12114: 			next;
                   12115: 		    }
                   12116: 		} else {
                   12117: 		    $ip=inet_ntoa($ip);
1.847     albertel 12118: 		}
                   12119: 		$name_to_ip{$name} = $ip;
                   12120: 	    } else {
                   12121: 		$ip = $name_to_ip{$name};
1.653     albertel 12122: 	    }
1.888     albertel 12123: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   12124: 		$lonid_to_ip{$id} = $ip;
                   12125: 	    }
                   12126: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 12127: 	}
1.1172.2.23  raeburn  12128: 	&do_cache_new('iphost','iphost',
                   12129: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   12130: 		      48*60*60);
1.869     albertel 12131: 
1.847     albertel 12132: 	return %iphost;
1.598     albertel 12133:     }
                   12134: 
1.992     raeburn  12135:     #
                   12136:     #  Given a DNS returns the loncapa host name for that DNS 
                   12137:     # 
                   12138:     sub host_from_dns {
                   12139:         my ($dns) = @_;
                   12140:         my @hosts;
                   12141:         my $ip;
                   12142: 
1.993     raeburn  12143:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  12144:             $ip = $name_to_ip{$dns};
                   12145:         }
                   12146:         if (!$ip) {
                   12147:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   12148:             if (length($ip) == 4) { 
                   12149: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   12150:             }
                   12151:         }
                   12152:         if ($ip) {
                   12153: 	    @hosts = get_hosts_from_ip($ip);
                   12154: 	    return $hosts[0];
                   12155:         }
                   12156:         return undef;
1.986     foxr     12157:     }
1.992     raeburn  12158: 
1.1074    raeburn  12159:     sub get_internet_names {
                   12160:         my ($lonid) = @_;
                   12161:         return if ($lonid eq '');
                   12162:         my ($idnref,$cached)=
                   12163:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   12164:         if ($cached) {
                   12165:             return $idnref;
                   12166:         }
                   12167:         my $ip = &get_host_ip($lonid);
                   12168:         my @hosts = &get_hosts_from_ip($ip);
                   12169:         my %iphost = &get_iphost();
                   12170:         my (@idns,%seen);
                   12171:         foreach my $id (@hosts) {
                   12172:             my $dom = &host_domain($id);
                   12173:             my $prim_id = &domain($dom,'primary');
                   12174:             my $prim_ip = &get_host_ip($prim_id);
                   12175:             next if ($seen{$prim_ip});
                   12176:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   12177:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   12178:                     my $intdom = &internet_dom($id);
                   12179:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   12180:                         push(@idns,$intdom);
                   12181:                     }
                   12182:                 }
                   12183:             }
                   12184:             $seen{$prim_ip} = 1;
                   12185:         }
1.1172.2.23  raeburn  12186:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  12187:     }
                   12188: 
1.986     foxr     12189: }
                   12190: 
1.1079    raeburn  12191: sub all_loncaparevs {
                   12192:     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);
                   12193: }
                   12194: 
1.1172.2.27  raeburn  12195: # ------------------------------------------------------- Read loncaparev table
                   12196: {
                   12197:     sub load_loncaparevs {
                   12198:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   12199:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   12200:                 while (my $configline=<$config>) {
                   12201:                     chomp($configline);
                   12202:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   12203:                     $loncaparevs{$hostid}=$loncaparev;
                   12204:                 }
                   12205:                 close($config);
                   12206:             }
                   12207:         }
                   12208:     }
                   12209: }
                   12210: 
                   12211: # ----------------------------------------------------- Read serverhostID table
                   12212: {
                   12213:     sub load_serverhomeIDs {
                   12214:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   12215:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   12216:                 while (my $configline=<$config>) {
                   12217:                     chomp($configline);
                   12218:                     my ($name,$id)=split(/:/,$configline);
                   12219:                     $serverhomeIDs{$name}=$id;
                   12220:                 }
                   12221:                 close($config);
                   12222:             }
                   12223:         }
                   12224:     }
                   12225: }
                   12226: 
                   12227: 
1.862     albertel 12228: BEGIN {
                   12229: 
                   12230: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   12231:     unless ($readit) {
                   12232: {
                   12233:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   12234:     %perlvar = (%perlvar,%{$configvars});
                   12235: }
                   12236: 
                   12237: 
1.1       albertel 12238: # ------------------------------------------------------ Read spare server file
                   12239: {
1.448     albertel 12240:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 12241: 
                   12242:     while (my $configline=<$config>) {
                   12243:        chomp($configline);
1.284     matthew  12244:        if ($configline) {
1.784     albertel 12245: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 12246: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 12247: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 12248:        }
                   12249:     }
1.448     albertel 12250:     close($config);
1.1       albertel 12251: }
1.11      www      12252: # ------------------------------------------------------------ Read permissions
                   12253: {
1.448     albertel 12254:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      12255: 
                   12256:     while (my $configline=<$config>) {
1.448     albertel 12257: 	chomp($configline);
                   12258: 	if ($configline) {
                   12259: 	    my ($role,$perm)=split(/ /,$configline);
                   12260: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   12261: 	}
1.11      www      12262:     }
1.448     albertel 12263:     close($config);
1.11      www      12264: }
                   12265: 
                   12266: # -------------------------------------------- Read plain texts for permissions
                   12267: {
1.448     albertel 12268:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      12269: 
                   12270:     while (my $configline=<$config>) {
1.448     albertel 12271: 	chomp($configline);
                   12272: 	if ($configline) {
1.742     raeburn  12273: 	    my ($short,@plain)=split(/:/,$configline);
                   12274:             %{$prp{$short}} = ();
                   12275: 	    if (@plain > 0) {
                   12276:                 $prp{$short}{'std'} = $plain[0];
                   12277:                 for (my $i=1; $i<@plain; $i++) {
                   12278:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   12279:                 }
                   12280:             }
1.448     albertel 12281: 	}
1.135     www      12282:     }
1.448     albertel 12283:     close($config);
1.135     www      12284: }
                   12285: 
                   12286: # ---------------------------------------------------------- Read package table
                   12287: {
1.448     albertel 12288:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      12289: 
                   12290:     while (my $configline=<$config>) {
1.483     albertel 12291: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 12292: 	chomp($configline);
                   12293: 	my ($short,$plain)=split(/:/,$configline);
                   12294: 	my ($pack,$name)=split(/\&/,$short);
                   12295: 	if ($plain ne '') {
                   12296: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   12297: 	    $packagetab{$short}=$plain; 
                   12298: 	}
1.11      www      12299:     }
1.448     albertel 12300:     close($config);
1.329     matthew  12301: }
                   12302: 
1.1172.2.27  raeburn  12303: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  12304: 
1.1172.2.27  raeburn  12305: &load_loncaparevs();
                   12306: 
                   12307: # ------------------------------------------------------- Read serverhostID table
                   12308: 
                   12309: &load_serverhomeIDs();
1.1074    raeburn  12310: 
1.1172.2.27  raeburn  12311: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  12312: {
                   12313:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   12314:     if (-e $file) {
                   12315:         my $parser = HTML::LCParser->new($file);
                   12316:         while (my $token = $parser->get_token()) {
                   12317:             if ($token->[0] eq 'S') {
                   12318:                 my $item = $token->[1];
                   12319:                 my $name = $token->[2]{'name'};
                   12320:                 my $value = $token->[2]{'value'};
                   12321:                 if ($item ne '' && $name ne '' && $value ne '') {
                   12322:                     my $release = $parser->get_text();
                   12323:                     $release =~ s/(^\s*|\s*$ )//gx;
                   12324:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   12325:                 }
                   12326:             }
                   12327:         }
                   12328:     }
1.1073    raeburn  12329: }
                   12330: 
1.1138    raeburn  12331: # ---------------------------------------------------------- Read managers table
                   12332: {
                   12333:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   12334:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   12335:             while (my $configline=<$config>) {
                   12336:                 chomp($configline);
                   12337:                 next if ($configline =~ /^\#/);
                   12338:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   12339:                     $managerstab{$configline} = 1;
                   12340:                 }
                   12341:             }
                   12342:             close($config);
                   12343:         }
                   12344:     }
                   12345: }
                   12346: 
1.329     matthew  12347: # ------------- set up temporary directory
                   12348: {
1.1117    foxr     12349:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  12350: 
1.11      www      12351: }
                   12352: 
1.794     albertel 12353: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   12354: 				'compress_threshold'=> 20_000,
                   12355:  			        });
1.185     www      12356: 
1.281     www      12357: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      12358: $dumpcount=0;
1.958     www      12359: $locknum=0;
1.22      www      12360: 
1.163     harris41 12361: &logtouch();
1.672     albertel 12362: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      12363: $readit=1;
1.564     albertel 12364:     {
                   12365: 	use integer;
                   12366: 	my $test=(2**32)+1;
1.568     albertel 12367: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 12368: 	&logthis(" Detected 64bit platform ($_64bit)");
                   12369:     }
1.1172.2.18  raeburn  12370: 
                   12371:     {
                   12372:         eval {
                   12373:             ($apache) =
                   12374:                 (Apache2::ServerUtil::get_server_version() =~ m{Apache/(\d+\.\d+)});
                   12375:         };
                   12376:         if ($@) {
                   12377:            $apache = 1.3;
                   12378:         }
                   12379:     }
                   12380: 
1.195     www      12381: }
1.1       albertel 12382: }
1.179     www      12383: 
1.1       albertel 12384: 1;
1.191     harris41 12385: __END__
                   12386: 
1.243     albertel 12387: =pod
                   12388: 
1.191     harris41 12389: =head1 NAME
                   12390: 
1.243     albertel 12391: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 12392: 
                   12393: =head1 SYNOPSIS
                   12394: 
1.243     albertel 12395: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 12396: 
                   12397:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   12398: 
1.243     albertel 12399: Common parameters:
                   12400: 
                   12401: =over 4
                   12402: 
                   12403: =item *
                   12404: 
                   12405: $uname : an internal username (if $cname expecting a course Id specifically)
                   12406: 
                   12407: =item *
                   12408: 
                   12409: $udom : a domain (if $cdom expecting a course's domain specifically)
                   12410: 
                   12411: =item *
                   12412: 
                   12413: $symb : a resource instance identifier
                   12414: 
                   12415: =item *
                   12416: 
                   12417: $namespace : the name of a .db file that contains the data needed or
                   12418: being set.
                   12419: 
                   12420: =back
                   12421: 
1.394     bowersj2 12422: =head1 OVERVIEW
1.191     harris41 12423: 
1.394     bowersj2 12424: lonnet provides subroutines which interact with the
                   12425: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   12426: about classes, users, and resources.
1.243     albertel 12427: 
                   12428: For many of these objects you can also use this to store data about
                   12429: them or modify them in various ways.
1.191     harris41 12430: 
1.394     bowersj2 12431: =head2 Symbs
1.191     harris41 12432: 
1.394     bowersj2 12433: To identify a specific instance of a resource, LON-CAPA uses symbols
                   12434: or "symbs"X<symb>. These identifiers are built from the URL of the
                   12435: map, the resource number of the resource in the map, and the URL of
                   12436: the resource itself. The latter is somewhat redundant, but might help
                   12437: if maps change.
                   12438: 
                   12439: An example is
                   12440: 
                   12441:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   12442: 
                   12443: The respective map entry is
                   12444: 
                   12445:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   12446:   title="Problem 2">
                   12447:  </resource>
                   12448: 
                   12449: Symbs are used by the random number generator, as well as to store and
                   12450: restore data specific to a certain instance of for example a problem.
                   12451: 
                   12452: =head2 Storing And Retrieving Data
                   12453: 
                   12454: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   12455: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   12456: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   12457: is is the non-critical message twin of cstore. These functions are for
                   12458: handlers to store a perl hash to a user's permanent data space in an
                   12459: easy manner, and to retrieve it again on another call. It is expected
                   12460: that a handler would use this once at the beginning to retrieve data,
                   12461: and then again once at the end to send only the new data back.
                   12462: 
                   12463: The data is stored in the user's data directory on the user's
                   12464: homeserver under the ID of the course.
                   12465: 
                   12466: The hash that is returned by restore will have all of the previous
                   12467: value for all of the elements of the hash.
                   12468: 
                   12469: Example:
                   12470: 
                   12471:  #creating a hash
                   12472:  my %hash;
                   12473:  $hash{'foo'}='bar';
                   12474: 
                   12475:  #storing it
                   12476:  &Apache::lonnet::cstore(\%hash);
                   12477: 
                   12478:  #changing a value
                   12479:  $hash{'foo'}='notbar';
                   12480: 
                   12481:  #adding a new value
                   12482:  $hash{'bar'}='foo';
                   12483:  &Apache::lonnet::cstore(\%hash);
                   12484: 
                   12485:  #retrieving the hash
                   12486:  my %history=&Apache::lonnet::restore();
                   12487: 
                   12488:  #print the hash
                   12489:  foreach my $key (sort(keys(%history))) {
                   12490:    print("\%history{$key} = $history{$key}");
                   12491:  }
                   12492: 
                   12493: Will print out:
1.191     harris41 12494: 
1.394     bowersj2 12495:  %history{1:foo} = bar
                   12496:  %history{1:keys} = foo:timestamp
                   12497:  %history{1:timestamp} = 990455579
                   12498:  %history{2:bar} = foo
                   12499:  %history{2:foo} = notbar
                   12500:  %history{2:keys} = foo:bar:timestamp
                   12501:  %history{2:timestamp} = 990455580
                   12502:  %history{bar} = foo
                   12503:  %history{foo} = notbar
                   12504:  %history{timestamp} = 990455580
                   12505:  %history{version} = 2
                   12506: 
                   12507: Note that the special hash entries C<keys>, C<version> and
                   12508: C<timestamp> were added to the hash. C<version> will be equal to the
                   12509: total number of versions of the data that have been stored. The
                   12510: C<timestamp> attribute will be the UNIX time the hash was
                   12511: stored. C<keys> is available in every historical section to list which
                   12512: keys were added or changed at a specific historical revision of a
                   12513: hash.
                   12514: 
                   12515: B<Warning>: do not store the hash that restore returns directly. This
                   12516: will cause a mess since it will restore the historical keys as if the
                   12517: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 12518: 
1.394     bowersj2 12519: Calling convention:
1.191     harris41 12520: 
1.1172.2.27  raeburn  12521:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
                   12522:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
1.191     harris41 12523: 
1.394     bowersj2 12524: For more detailed information, see lonnet specific documentation.
1.191     harris41 12525: 
1.394     bowersj2 12526: =head1 RETURN MESSAGES
1.191     harris41 12527: 
1.394     bowersj2 12528: =over 4
1.191     harris41 12529: 
1.394     bowersj2 12530: =item * B<con_lost>: unable to contact remote host
1.191     harris41 12531: 
1.394     bowersj2 12532: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   12533: when the connection is brought back up
1.191     harris41 12534: 
1.394     bowersj2 12535: =item * B<con_failed>: unable to contact remote host and unable to save message
                   12536: for later delivery
1.191     harris41 12537: 
1.967     bisitz   12538: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 12539: 
1.394     bowersj2 12540: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 12541: that was requested
1.191     harris41 12542: 
1.243     albertel 12543: =back
1.191     harris41 12544: 
1.243     albertel 12545: =head1 PUBLIC SUBROUTINES
1.191     harris41 12546: 
1.243     albertel 12547: =head2 Session Environment Functions
1.191     harris41 12548: 
1.243     albertel 12549: =over 4
1.191     harris41 12550: 
1.394     bowersj2 12551: =item * 
                   12552: X<appenv()>
1.949     raeburn  12553: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 12554: the user envirnoment file, and will be restored for each access this
1.620     albertel 12555: user makes during this session, also modifies the %env for the current
1.949     raeburn  12556: process. Optional rolesarrayref - if defined contains a reference to an array
                   12557: of roles which are exempt from the restriction on modifying user.role entries 
                   12558: in the user's environment.db and in %env.    
1.191     harris41 12559: 
                   12560: =item *
1.394     bowersj2 12561: X<delenv()>
1.987     raeburn  12562: B<delenv($delthis,$regexp)>: removes all items from the session
                   12563: environment file that begin with $delthis. If the 
                   12564: optional second arg - $regexp - is true, $delthis is treated as a 
                   12565: regular expression, otherwise \Q$delthis\E is used. 
                   12566: The values are also deleted from the current processes %env.
1.191     harris41 12567: 
1.795     albertel 12568: =item * get_env_multiple($name) 
                   12569: 
                   12570: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   12571: values may be defined and end up as an array ref.
                   12572: 
                   12573: returns an array of values
                   12574: 
1.243     albertel 12575: =back
                   12576: 
                   12577: =head2 User Information
1.191     harris41 12578: 
1.243     albertel 12579: =over 4
1.191     harris41 12580: 
                   12581: =item *
1.394     bowersj2 12582: X<queryauthenticate()>
                   12583: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 12584: authentication scheme
                   12585: 
                   12586: =item *
1.394     bowersj2 12587: X<authenticate()>
1.1073    raeburn  12588: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 12589: authenticate user from domain's lib servers (first use the current
                   12590: one). C<$upass> should be the users password.
1.1073    raeburn  12591: $checkdefauth is optional (value is 1 if a check should be made to
                   12592:    authenticate user using default authentication method, and allow
                   12593:    account creation if username does not have account in the domain).
                   12594: $clientcancheckhost is optional (value is 1 if checking whether the
                   12595:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 12596: 
                   12597: =item *
1.394     bowersj2 12598: X<homeserver()>
                   12599: B<homeserver($uname,$udom)>: find the server which has
                   12600: the user's directory and files (there must be only one), this caches
                   12601: the answer, and also caches if there is a borken connection.
1.191     harris41 12602: 
                   12603: =item *
1.394     bowersj2 12604: X<idget()>
                   12605: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   12606: (IDs are a unique resource in a domain, there must be only 1 ID per
                   12607: username, and only 1 username per ID in a specific domain) (returns
                   12608: hash: id=>name,id=>name)
1.191     harris41 12609: 
                   12610: =item *
1.394     bowersj2 12611: X<idrget()>
                   12612: B<idrget($udom,@unames)>: find the IDs behind a list of
                   12613: usernames (returns hash: name=>id,name=>id)
1.191     harris41 12614: 
                   12615: =item *
1.394     bowersj2 12616: X<idput()>
                   12617: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 12618: 
                   12619: =item *
1.394     bowersj2 12620: X<rolesinit()>
1.1169    droeschl 12621: B<rolesinit($udom,$username)>: get user privileges.
                   12622: returns user role, first access and timer interval hashes
1.243     albertel 12623: 
                   12624: =item *
1.1171    droeschl 12625: X<privileged()>
                   12626: B<privileged($username,$domain)>: returns a true if user has a
                   12627: privileged and active role (i.e. su or dc), false otherwise.
                   12628: 
                   12629: =item *
1.551     albertel 12630: X<getsection()>
                   12631: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 12632: course $cname, return section name/number or '' for "not in course"
                   12633: and '-1' for "no section"
                   12634: 
                   12635: =item *
1.394     bowersj2 12636: X<userenvironment()>
                   12637: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 12638: passed in @what from the requested user's environment, returns a hash
                   12639: 
1.858     raeburn  12640: =item * 
                   12641: X<userlog_query()>
1.859     albertel 12642: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   12643: activity.log file. %filters defines filters applied when parsing the
                   12644: log file. These can be start or end timestamps, or the type of action
                   12645: - log to look for Login or Logout events, check for Checkin or
                   12646: Checkout, role for role selection. The response is in the form
                   12647: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   12648: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  12649: 
1.243     albertel 12650: =back
                   12651: 
                   12652: =head2 User Roles
                   12653: 
                   12654: =over 4
                   12655: 
                   12656: =item *
                   12657: 
1.810     raeburn  12658: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 12659:  F: full access
                   12660:  U,I,K: authentication modes (cxx only)
                   12661:  '': forbidden
                   12662:  1: user needs to choose course
                   12663:  2: browse allowed
1.766     albertel 12664:  A: passphrase authentication needed
1.243     albertel 12665: 
                   12666: =item *
                   12667: 
1.1172.2.13  raeburn  12668: constructaccess($url,$setpriv) : check for access to construction space URL
                   12669: 
                   12670: See if the owner domain and name in the URL match those in the
                   12671: expected environment.  If so, return three element list
                   12672: ($ownername,$ownerdomain,$ownerhome).
                   12673: 
                   12674: Otherwise return the null string.
                   12675: 
                   12676: If second argument 'setpriv' is true, it assigns the privileges,
                   12677: and returns the same three element list, unless the owner has
                   12678: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   12679: in which case the null string is returned.
                   12680: 
                   12681: =item *
                   12682: 
1.243     albertel 12683: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   12684: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   12685: and course level
                   12686: 
                   12687: =item *
                   12688: 
1.988     raeburn  12689: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   12690: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  12691: $type is Course (default) or Community.
1.988     raeburn  12692: If $forcedefault evaluates to true, text returned will be default 
                   12693: text for $type. Otherwise, if this is a course, the text returned 
                   12694: will be a custom name for the role (if defined in the course's 
                   12695: environment).  If no custom name is defined the default is returned.
                   12696:    
1.832     raeburn  12697: =item *
                   12698: 
1.1172.2.23  raeburn  12699: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  12700: All arguments are optional. Returns a hash of a roles, either for
                   12701: co-author/assistant author roles for a user's Construction Space
1.906     albertel 12702: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  12703: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   12704: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   12705: For each key, value is set to colon-separated start and end times for
                   12706: the role.  If no username and domain are specified, will default to
1.934     raeburn  12707: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  12708: of role statuses (active, future or previous), roles 
                   12709: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   12710: to restrict the list of roles reported. If no array ref is 
                   12711: provided for types, will default to return only active roles.
1.834     albertel 12712: 
1.1172.2.13  raeburn  12713: =item *
                   12714: 
                   12715: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   12716: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   12717: 
                   12718: Additional optional arguments are: $type (if role checking is to be restricted
                   12719: to certain user status types -- previous (expired roles), active (currently
                   12720: available roles) or future (roles available in the future), and
                   12721: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  12722: have active Domain Coordinator role in course's domain or in additional
                   12723: domains (specified in 'Domains to check for privileged users' in course
                   12724: environment -- set via:  Course Settings -> Classlists and staff listing).
                   12725: 
                   12726: =item *
                   12727: 
                   12728: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   12729: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   12730: $possdomains and $possroles are optional array refs -- to domains to check and
                   12731: roles to check.  If $possdomains is not specified, a dump will be done of the
                   12732: users' roles.db to check for a dc or su role in any domain. This can be
                   12733: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   12734: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   12735: this then allows &privileged_by_domain() to be used, which caches the identity
                   12736: of privileged users, eliminating the need for repeated calls to &dump().
                   12737: 
                   12738: =item *
                   12739: 
                   12740: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   12741: where the outer hash keys are domains specified in the $possdomains array ref,
                   12742: next inner hash keys are privileged roles specified in the $roles array ref,
                   12743: and the innermost hash contains key = value pairs for username:domain = end:start
                   12744: for active or future "privileged" users with that role in that domain. To avoid
                   12745: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   12746: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  12747: 
1.243     albertel 12748: =back
                   12749: 
                   12750: =head2 User Modification
                   12751: 
                   12752: =over 4
                   12753: 
                   12754: =item *
                   12755: 
1.957     raeburn  12756: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 12757: user for the level given by URL.  Optional start and end dates (leave empty
                   12758: string or zero for "no date")
1.191     harris41 12759: 
                   12760: =item *
                   12761: 
1.243     albertel 12762: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   12763: change a users, password, possible return values are: ok,
                   12764: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   12765: refused
1.191     harris41 12766: 
                   12767: =item *
                   12768: 
1.243     albertel 12769: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 12770: 
                   12771: =item *
                   12772: 
1.1058    raeburn  12773: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   12774:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   12775: 
                   12776: will update user information (firstname,middlename,lastname,generation,
                   12777: permanentemail), and if forceid is true, student/employee ID also.
                   12778: A user's institutional affiliation(s) can also be updated.
                   12779: User information fields will not be overwritten with empty entries 
                   12780: unless the field is included in the $candelete array reference.
                   12781: This array is included when a single user is modified via "Manage Users",
                   12782: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 12783: 
                   12784: =item *
                   12785: 
1.286     matthew  12786: modifystudent
                   12787: 
1.957     raeburn  12788: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  12789: The course id is resolved based on the current user's environment.  
                   12790: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  12791: associated with a course.
                   12792: 
1.297     matthew  12793: This call is essentially a wrapper for lonnet::modifyuser and
                   12794: lonnet::modify_student_enrollment
1.286     matthew  12795: 
                   12796: Inputs: 
                   12797: 
                   12798: =over 4
                   12799: 
1.957     raeburn  12800: =item B<$udom> Student's loncapa domain
1.286     matthew  12801: 
1.957     raeburn  12802: =item B<$uname> Student's loncapa login name
1.286     matthew  12803: 
1.964     bisitz   12804: =item B<$uid> Student/Employee ID
1.286     matthew  12805: 
1.957     raeburn  12806: =item B<$umode> Student's authentication mode
1.286     matthew  12807: 
1.957     raeburn  12808: =item B<$upass> Student's password
1.286     matthew  12809: 
1.957     raeburn  12810: =item B<$first> Student's first name
1.286     matthew  12811: 
1.957     raeburn  12812: =item B<$middle> Student's middle name
1.286     matthew  12813: 
1.957     raeburn  12814: =item B<$last> Student's last name
1.286     matthew  12815: 
1.957     raeburn  12816: =item B<$gene> Student's generation
1.286     matthew  12817: 
1.957     raeburn  12818: =item B<$usec> Student's section in course
1.286     matthew  12819: 
                   12820: =item B<$end> Unix time of the roles expiration
                   12821: 
                   12822: =item B<$start> Unix time of the roles start date
                   12823: 
                   12824: =item B<$forceid> If defined, allow $uid to be changed
                   12825: 
                   12826: =item B<$desiredhome> server to use as home server for student
                   12827: 
1.957     raeburn  12828: =item B<$email> Student's permanent e-mail address
                   12829: 
                   12830: =item B<$type> Type of enrollment (auto or manual)
                   12831: 
1.963     raeburn  12832: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   12833: 
                   12834: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  12835: 
1.963     raeburn  12836: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  12837: 
1.963     raeburn  12838: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  12839: 
1.1172.2.19  raeburn  12840: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   12841: 
                   12842: =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  12843: 
1.286     matthew  12844: =back
1.297     matthew  12845: 
                   12846: =item *
                   12847: 
                   12848: modify_student_enrollment
                   12849: 
1.1172.2.31  raeburn  12850: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  12851: 'role.request.course' must be defined for this function to proceed.
                   12852: 
                   12853: Inputs:
                   12854: 
                   12855: =over 4
                   12856: 
1.1172.2.31  raeburn  12857: =item $udom, student's domain
1.297     matthew  12858: 
1.1172.2.31  raeburn  12859: =item $uname, student's name
1.297     matthew  12860: 
1.1172.2.31  raeburn  12861: =item $uid, student's user id
1.297     matthew  12862: 
1.1172.2.31  raeburn  12863: =item $first, student's first name
1.297     matthew  12864: 
                   12865: =item $middle
                   12866: 
                   12867: =item $last
                   12868: 
                   12869: =item $gene
                   12870: 
                   12871: =item $usec
                   12872: 
                   12873: =item $end
                   12874: 
                   12875: =item $start
                   12876: 
1.957     raeburn  12877: =item $type
                   12878: 
                   12879: =item $locktype
                   12880: 
                   12881: =item $cid
                   12882: 
                   12883: =item $selfenroll
                   12884: 
                   12885: =item $context
                   12886: 
1.1172.2.19  raeburn  12887: =item $credits, number of credits student will earn from this class
                   12888: 
1.297     matthew  12889: =back
                   12890: 
1.191     harris41 12891: 
                   12892: =item *
                   12893: 
1.243     albertel 12894: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   12895: custom role; give a custom role to a user for the level given by URL.  Specify
                   12896: name and domain of role author, and role name
1.191     harris41 12897: 
                   12898: =item *
                   12899: 
1.243     albertel 12900: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 12901: 
                   12902: =item *
                   12903: 
1.243     albertel 12904: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   12905: 
                   12906: =back
                   12907: 
                   12908: =head2 Course Infomation
                   12909: 
                   12910: =over 4
1.191     harris41 12911: 
                   12912: =item *
                   12913: 
1.1118    foxr     12914: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 12915: specified course id, including all environment settings for the
                   12916: course, the description of the course will be in the hash under the
                   12917: key 'description'
1.191     harris41 12918: 
1.1118    foxr     12919: $options is an optional parameter that if supplied is a hash reference that controls
                   12920: what how this function works.  It has the following key/values:
                   12921: 
                   12922: =over 4
                   12923: 
                   12924: =item freshen_cache
                   12925: 
                   12926: If defined, and the environment cache for the course is valid, it is 
                   12927: returned in the returned hash.
                   12928: 
                   12929: =item one_time
                   12930: 
                   12931: If defined, the last cache time is set to _now_
                   12932: 
                   12933: =item user
                   12934: 
                   12935: If defined, the supplied username is used instead of the current user.
                   12936: 
                   12937: 
                   12938: =back
                   12939: 
1.191     harris41 12940: =item *
                   12941: 
1.624     albertel 12942: resdata($name,$domain,$type,@which) : request for current parameter
                   12943: setting for a specific $type, where $type is either 'course' or 'user',
                   12944: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  12945: answers for 10 minutes.
1.243     albertel 12946: 
1.877     foxr     12947: =item *
                   12948: 
                   12949: get_courseresdata($courseid, $domain) : dump the entire course resource
                   12950: data base, returning a hash that is keyed by the resource name and has
                   12951: values that are the resource value.  I believe that the timestamps and
                   12952: versions are also returned.
                   12953: 
1.1172.2.31  raeburn  12954: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   12955: supplemental content area. This routine caches the number of files for
                   12956: 10 minutes.
                   12957: 
1.243     albertel 12958: =back
                   12959: 
                   12960: =head2 Course Modification
                   12961: 
                   12962: =over 4
1.191     harris41 12963: 
                   12964: =item *
                   12965: 
1.243     albertel 12966: writecoursepref($courseid,%prefs) : write preferences (environment
                   12967: database) for a course
1.191     harris41 12968: 
                   12969: =item *
                   12970: 
1.1011    raeburn  12971: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   12972: 
                   12973: =item *
                   12974: 
1.1038    raeburn  12975: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 12976: 
1.1167    droeschl 12977: =item *
                   12978: 
                   12979: is_course($courseid), is_course($cdom, $cnum)
                   12980: 
                   12981: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   12982: two component version $cdom, $cnum. It checks if the specified course exists.
                   12983: 
                   12984: Returns:
                   12985:     undef if the course doesn't exist, otherwise
                   12986:     in scalar context the combined courseid.
                   12987:     in list context the two components of the course identifier, domain and 
                   12988:     courseid.    
                   12989: 
1.243     albertel 12990: =back
                   12991: 
                   12992: =head2 Resource Subroutines
                   12993: 
                   12994: =over 4
1.191     harris41 12995: 
                   12996: =item *
                   12997: 
1.243     albertel 12998: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 12999: 
                   13000: =item *
                   13001: 
1.243     albertel 13002: repcopy($filename) : subscribes to the requested file, and attempts to
                   13003: replicate from the owning library server, Might return
1.607     raeburn  13004: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   13005: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 13006: resource. Expects the local filesystem pathname
                   13007: (/home/httpd/html/res/....)
                   13008: 
                   13009: =back
                   13010: 
                   13011: =head2 Resource Information
                   13012: 
                   13013: =over 4
1.191     harris41 13014: 
                   13015: =item *
                   13016: 
1.1172.2.28  raeburn  13017: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   13018: and returns the value of a variety of different possible values,
                   13019: $varname should be a request string, and the other parameters can be
                   13020: used to specify who and what one is asking about. Ordinarily, $cid 
                   13021: does not need to be specified, as it is retrived from 
                   13022: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   13023: within lonuserstate::loadmap() when initializing a course, before
                   13024: $env{'request.course.id'} has been set, so it needs to be provided
                   13025: in that one case.
1.243     albertel 13026: 
                   13027: Possible values for $varname are environment.lastname (or other item
                   13028: from the envirnment hash), user.name (or someother aspect about the
                   13029: user), resource.0.maxtries (or some other part and parameter of a
                   13030: resource)
1.204     albertel 13031: 
                   13032: =item *
                   13033: 
1.243     albertel 13034: directcondval($number) : get current value of a condition; reads from a state
                   13035: string
1.204     albertel 13036: 
                   13037: =item *
                   13038: 
1.243     albertel 13039: condval($condidx) : value of condition index based on state
1.204     albertel 13040: 
                   13041: =item *
                   13042: 
1.243     albertel 13043: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   13044: resource's metadata, $what should be either a specific key, or either
                   13045: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   13046: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   13047: 
                   13048: this function automatically caches all requests
1.191     harris41 13049: 
                   13050: =item *
                   13051: 
1.243     albertel 13052: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   13053: network of library servers; returns file handle of where SQL and regex results
                   13054: will be stored for query
1.191     harris41 13055: 
                   13056: =item *
                   13057: 
1.243     albertel 13058: symbread($filename) : return symbolic list entry (filename argument optional);
                   13059: returns the data handle
1.191     harris41 13060: 
                   13061: =item *
                   13062: 
1.1172.2.17  raeburn  13063: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  13064: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 13065: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  13066: on failure, user must be in a course, as it assumes the existence of
                   13067: the course initial hash, and uses $env('request.course.id'}.  The third
                   13068: arg is an optional reference to a scalar.  If this arg is passed in the
                   13069: call to symbverify, it will be set to 1 if the symb has been set to be 
                   13070: encrypted; otherwise it will be null.
1.243     albertel 13071: 
1.191     harris41 13072: =item *
                   13073: 
1.243     albertel 13074: symbclean($symb) : removes versions numbers from a symb, returns the
                   13075: cleaned symb
1.191     harris41 13076: 
                   13077: =item *
                   13078: 
1.243     albertel 13079: is_on_map($uri) : checks if the $uri is somewhere on the current
                   13080: course map, user must be in a course for it to work.
1.191     harris41 13081: 
                   13082: =item *
                   13083: 
1.243     albertel 13084: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 13085: 
                   13086: =item *
                   13087: 
1.243     albertel 13088: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   13089: a random seed, all arguments are optional, if they aren't sent it uses the
                   13090: environment to derive them. Note: if symb isn't sent and it can't get one
                   13091: from &symbread it will use the current time as its return value
1.191     harris41 13092: 
                   13093: =item *
                   13094: 
1.243     albertel 13095: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   13096: unfakeable, receipt
1.191     harris41 13097: 
                   13098: =item *
                   13099: 
1.620     albertel 13100: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 13101: 
                   13102: =item *
                   13103: 
1.243     albertel 13104: countacc($url) : count the number of accesses to a given URL
1.191     harris41 13105: 
                   13106: =item *
                   13107: 
1.243     albertel 13108: 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 13109: 
                   13110: =item *
                   13111: 
1.243     albertel 13112: 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 13113: 
                   13114: =item *
                   13115: 
1.243     albertel 13116: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 13117: 
                   13118: =item *
                   13119: 
1.243     albertel 13120: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   13121: forcing spreadsheet to reevaluate the resource scores next time.
                   13122: 
1.1172.2.13  raeburn  13123: =item *
                   13124: 
                   13125: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   13126: when viewing in course context.
                   13127: 
                   13128:  input: six args -- filename (decluttered), course number, course domain,
                   13129:                     url, symb (if registered) and group (if this is a
                   13130:                     group item -- e.g., bulletin board, group page etc.).
                   13131: 
                   13132:  output: array of five scalars --
                   13133:          $cfile -- url for file editing if editable on current server
                   13134:          $home -- homeserver of resource (i.e., for author if published,
                   13135:                                           or course if uploaded.).
                   13136:          $switchserver --  1 if server switch will be needed.
                   13137:          $forceedit -- 1 if icon/link should be to go to edit mode
                   13138:          $forceview -- 1 if icon/link should be to go to view mode
                   13139: 
                   13140: =item *
                   13141: 
                   13142: is_course_upload($file,$cnum,$cdom)
                   13143: 
                   13144: Used in course context to determine if current file was uploaded to
                   13145: the course (i.e., would be found in /userfiles/docs on the course's
                   13146: homeserver.
                   13147: 
                   13148:   input: 3 args -- filename (decluttered), course number and course domain.
                   13149:   output: boolean -- 1 if file was uploaded.
                   13150: 
1.243     albertel 13151: =back
                   13152: 
                   13153: =head2 Storing/Retreiving Data
                   13154: 
                   13155: =over 4
1.191     harris41 13156: 
                   13157: =item *
                   13158: 
1.243     albertel 13159: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   13160: for this url; hashref needs to be given and should be a \%hashname; the
                   13161: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 13162: be derived from the env
1.191     harris41 13163: 
                   13164: =item *
                   13165: 
1.243     albertel 13166: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   13167: uses critical subroutine
1.191     harris41 13168: 
                   13169: =item *
                   13170: 
1.243     albertel 13171: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   13172: all args are optional
1.191     harris41 13173: 
                   13174: =item *
                   13175: 
1.717     albertel 13176: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   13177: dumps the complete (or key matching regexp) namespace into a hash
                   13178: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   13179: normally &store()ed into
                   13180: 
                   13181: $range should be either an integer '100' (give me the first 100
                   13182:                                            matching records)
                   13183:               or be  two integers sperated by a - with no spaces
                   13184:                  '30-50' (give me the 30th through the 50th matching
                   13185:                           records)
                   13186: 
                   13187: 
                   13188: =item *
                   13189: 
                   13190: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   13191: replaces a &store() version of data with a replacement set of data
                   13192: for a particular resource in a namespace passed in the $storehash hash 
                   13193: reference
                   13194: 
                   13195: =item *
                   13196: 
1.243     albertel 13197: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   13198: works very similar to store/cstore, but all data is stored in a
                   13199: temporary location and can be reset using tmpreset, $storehash should
                   13200: be a hash reference, returns nothing on success
1.191     harris41 13201: 
                   13202: =item *
                   13203: 
1.243     albertel 13204: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   13205: similar to restore, but all data is stored in a temporary location and
                   13206: can be reset using tmpreset. Returns a hash of values on success,
                   13207: error string otherwise.
1.191     harris41 13208: 
                   13209: =item *
                   13210: 
1.243     albertel 13211: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   13212: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 13213: 
                   13214: =item *
                   13215: 
1.243     albertel 13216: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13217: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 13218: 
                   13219: =item *
                   13220: 
1.243     albertel 13221: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   13222: namesp ($udom and $uname are optional)
1.191     harris41 13223: 
                   13224: =item *
                   13225: 
1.702     albertel 13226: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 13227: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 13228: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  13229: 
1.702     albertel 13230: $range should be either an integer '100' (give me the first 100
                   13231:                                            matching records)
                   13232:               or be  two integers sperated by a - with no spaces
                   13233:                  '30-50' (give me the 30th through the 50th matching
                   13234:                           records)
1.449     matthew  13235: =item *
                   13236: 
                   13237: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   13238: $store can be a scalar, an array reference, or if the amount to be 
                   13239: incremented is > 1, a hash reference.
                   13240: 
                   13241: ($udom and $uname are optional)
1.191     harris41 13242: 
                   13243: =item *
                   13244: 
1.243     albertel 13245: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   13246: ($udom and $uname are optional)
1.191     harris41 13247: 
                   13248: =item *
                   13249: 
1.243     albertel 13250: cput($namespace,$storehash,$udom,$uname) : critical put
                   13251: ($udom and $uname are optional)
1.191     harris41 13252: 
                   13253: =item *
                   13254: 
1.748     albertel 13255: newput($namespace,$storehash,$udom,$uname) :
                   13256: 
                   13257: Attempts to store the items in the $storehash, but only if they don't
                   13258: currently exist, if this succeeds you can be certain that you have 
                   13259: successfully created a new key value pair in the $namespace db.
                   13260: 
                   13261: 
                   13262: Args:
                   13263:  $namespace: name of database to store values to
                   13264:  $storehash: hashref to store to the db
                   13265:  $udom: (optional) domain of user containing the db
                   13266:  $uname: (optional) name of user caontaining the db
                   13267: 
                   13268: Returns:
                   13269:  'ok' -> succeeded in storing all keys of $storehash
                   13270:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   13271:                         least <key> already existed in the db (other
                   13272:                         requested keys may also already exist)
1.967     bisitz   13273:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 13274:  'con_lost' -> unable to contact request server
                   13275:  'refused' -> action was not allowed by remote machine
                   13276: 
                   13277: 
                   13278: =item *
                   13279: 
1.243     albertel 13280: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13281: reference filled in from namesp (encrypts the return communication)
                   13282: ($udom and $uname are optional)
1.191     harris41 13283: 
                   13284: =item *
                   13285: 
1.243     albertel 13286: log($udom,$name,$home,$message) : write to permanent log for user; use
                   13287: critical subroutine
                   13288: 
1.806     raeburn  13289: =item *
                   13290: 
1.860     raeburn  13291: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   13292: array reference filled in from namespace found in domain level on either
                   13293: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  13294: 
                   13295: =item *
                   13296: 
1.860     raeburn  13297: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   13298: domain level either on specified domain server ($uhome) or primary domain 
                   13299: server ($udom and $uhome are optional)
1.806     raeburn  13300: 
1.943     raeburn  13301: =item * 
                   13302: 
                   13303: get_domain_defaults($target_domain) : returns hash with defaults for
                   13304: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   13305: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   13306: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   13307: Values are retrieved from cache (if current), or from domain's configuration.db
                   13308: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   13309: or lonTabs/domain.tab. 
                   13310: 
                   13311: %domdefaults = &get_auth_defaults($target_domain);
                   13312: 
1.243     albertel 13313: =back
                   13314: 
                   13315: =head2 Network Status Functions
                   13316: 
                   13317: =over 4
1.191     harris41 13318: 
                   13319: =item *
                   13320: 
1.1137    raeburn  13321: dirlist() : return directory list based on URI (first arg).
                   13322: 
                   13323: Inputs: 1 required, 5 optional.
                   13324: 
                   13325: =over
                   13326: 
                   13327: =item 
                   13328: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   13329: 
                   13330: =item
                   13331: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   13332: 
                   13333: =item
                   13334: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   13335: 
                   13336: =item
                   13337: $getpropath - boolean: 1 if prepend path using &propath(). 
                   13338: 
                   13339: =item
                   13340: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   13341: 
                   13342: =item 
                   13343: $alternateRoot - path to prepend in place of path from $uri.
                   13344: 
                   13345: =back
                   13346: 
                   13347: Returns: Array of up to two items.
                   13348: 
                   13349: =over
                   13350: 
                   13351: a reference to an array of files/subdirectories
                   13352: 
                   13353: =over
                   13354: 
                   13355: Each element in the array of files/subdirectories is a & separated list of
                   13356: item name and the result of running stat on the item.  If dirlist was requested
                   13357: for a file instead of a directory, the item name will be ''. For a directory 
                   13358: listing, if the item is a metadata file, the element will end &N&M 
                   13359: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   13360: default copyright set (1).  
                   13361: 
                   13362: =back
                   13363: 
                   13364: a scalar containing error condition (if encountered).
                   13365: 
                   13366: =over
                   13367: 
                   13368: =item 
                   13369: no_host (no homeserver identified for $username:$domain).
                   13370: 
                   13371: =item 
                   13372: no_such_host (server contacted for listing not identified as valid host).
                   13373: 
                   13374: =item 
                   13375: con_lost (connection to remote server failed).
                   13376: 
                   13377: =item 
                   13378: refused (invalid $username:$domain received on lond side).
                   13379: 
                   13380: =item 
                   13381: no_such_dir (directory at specified path on lond side does not exist). 
                   13382: 
                   13383: =item 
                   13384: empty (directory at specified path on lond side is empty).
                   13385: 
                   13386: =over
                   13387: 
                   13388: This is currently not encountered because the &ls3, &ls2, 
                   13389: &ls (_handler) routines on the lond side do not filter out
                   13390: . and .. from a directory listing. 
                   13391: 
                   13392: =back
                   13393: 
                   13394: =back
                   13395: 
                   13396: =back
1.191     harris41 13397: 
                   13398: =item *
                   13399: 
1.243     albertel 13400: spareserver() : find server with least workload from spare.tab
                   13401: 
1.986     foxr     13402: 
                   13403: =item *
                   13404: 
                   13405: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   13406: if there is no corresponding loncapa host.
                   13407: 
1.243     albertel 13408: =back
                   13409: 
1.986     foxr     13410: 
1.243     albertel 13411: =head2 Apache Request
                   13412: 
                   13413: =over 4
1.191     harris41 13414: 
                   13415: =item *
                   13416: 
1.243     albertel 13417: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   13418: localhost, posts hash
                   13419: 
                   13420: =back
                   13421: 
                   13422: =head2 Data to String to Data
                   13423: 
                   13424: =over 4
1.191     harris41 13425: 
                   13426: =item *
                   13427: 
1.243     albertel 13428: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   13429: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 13430: 
                   13431: =item *
                   13432: 
1.243     albertel 13433: hashref2str($hashref) : convert a hashref into a string complete with
                   13434: escaping and '=' and '&' separators, supports elements that are
                   13435: arrayrefs and hashrefs
1.191     harris41 13436: 
                   13437: =item *
                   13438: 
1.243     albertel 13439: arrayref2str($arrayref) : convert an arrayref into a string complete
                   13440: with escaping and '&' separators, supports elements that are arrayrefs
                   13441: and hashrefs
1.191     harris41 13442: 
                   13443: =item *
                   13444: 
1.243     albertel 13445: str2hash($string) : convert string to hash using unescaping and
                   13446: splitting on '=' and '&', supports elements that are arrayrefs and
                   13447: hashrefs
1.191     harris41 13448: 
                   13449: =item *
                   13450: 
1.243     albertel 13451: str2array($string) : convert string to hash using unescaping and
                   13452: splitting on '&', supports elements that are arrayrefs and hashrefs
                   13453: 
                   13454: =back
                   13455: 
                   13456: =head2 Logging Routines
                   13457: 
                   13458: 
                   13459: These routines allow one to make log messages in the lonnet.log and
                   13460: lonnet.perm logfiles.
1.191     harris41 13461: 
1.1119    foxr     13462: =over 4
                   13463: 
1.191     harris41 13464: =item *
                   13465: 
1.243     albertel 13466: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 13467: 
                   13468: =item *
                   13469: 
1.243     albertel 13470: logthis() : append message to the normal lonnet.log file, it gets
                   13471: preiodically rolled over and deleted.
1.191     harris41 13472: 
                   13473: =item *
                   13474: 
1.243     albertel 13475: logperm() : append a permanent message to lonnet.perm.log, this log
                   13476: file never gets deleted by any automated portion of the system, only
                   13477: messages of critical importance should go in here.
                   13478: 
1.1119    foxr     13479: 
1.243     albertel 13480: =back
                   13481: 
                   13482: =head2 General File Helper Routines
                   13483: 
                   13484: =over 4
1.191     harris41 13485: 
                   13486: =item *
                   13487: 
1.481     raeburn  13488: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   13489: (a) files in /uploaded
                   13490:   (i) If a local copy of the file exists - 
                   13491:       compares modification date of local copy with last-modified date for 
                   13492:       definitive version stored on home server for course. If local copy is 
                   13493:       stale, requests a new version from the home server and stores it. 
                   13494:       If the original has been removed from the home server, then local copy 
                   13495:       is unlinked.
                   13496:   (ii) If local copy does not exist -
                   13497:       requests the file from the home server and stores it. 
                   13498:   
                   13499:   If $caller is 'uploadrep':  
                   13500:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   13501:     for request for files originally uploaded via DOCS. 
                   13502:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   13503:   
                   13504:   Otherwise:
                   13505:      This indicates a call from the content generation phase of the request.
                   13506:      -  returns the entire contents of the file or -1.
                   13507:      
                   13508: (b) files in /res
                   13509:    - returns the entire contents of a file or -1; 
                   13510:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 13511: 
1.712     albertel 13512: 
                   13513: =item *
                   13514: 
                   13515: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   13516:                   reference
                   13517: 
                   13518: returns either a stat() list of data about the file or an empty list
                   13519: if the file doesn't exist or couldn't find out about it (connection
                   13520: problems or user unknown)
                   13521: 
1.191     harris41 13522: =item *
                   13523: 
1.243     albertel 13524: filelocation($dir,$file) : returns file system location of a file
                   13525: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   13526: directory that relative $file lookups are to looked in ($dir of /a/dir
                   13527: and a file of ../bob will become /a/bob)
1.191     harris41 13528: 
                   13529: =item *
                   13530: 
                   13531: hreflocation($dir,$file) : returns file system location or a URL; same as
                   13532: filelocation except for hrefs
                   13533: 
                   13534: =item *
                   13535: 
                   13536: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   13537: 
1.243     albertel 13538: =back
                   13539: 
1.608     albertel 13540: =head2 Usererfile file routines (/uploaded*)
                   13541: 
                   13542: =over 4
                   13543: 
                   13544: =item *
                   13545: 
                   13546: userfileupload(): main rotine for putting a file in a user or course's
                   13547:                   filespace, arguments are,
                   13548: 
1.620     albertel 13549:  formname - required - this is the name of the element in $env where the
1.608     albertel 13550:            filename, and the contents of the file to create/modifed exist
1.620     albertel 13551:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   13552:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  13553:  context - if coursedoc, store the file in the course of the active role
                   13554:              of the current user; 
                   13555:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   13556:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 13557:  subdir - required - subdirectory to put the file in under ../userfiles/
                   13558:          if undefined, it will be placed in "unknown"
                   13559: 
                   13560:  (This routine calls clean_filename() to remove any dangerous
                   13561:  characters from the filename, and then calls finuserfileupload() to
                   13562:  complete the transaction)
                   13563: 
                   13564:  returns either the url of the uploaded file (/uploaded/....) if successful
                   13565:  and /adm/notfound.html if unsuccessful
                   13566: 
                   13567: =item *
                   13568: 
                   13569: clean_filename(): routine for cleaing a filename up for storage in
                   13570:                  userfile space, argument is:
                   13571: 
                   13572:  filename - proposed filename
                   13573: 
                   13574: returns: the new clean filename
                   13575: 
                   13576: =item *
                   13577: 
1.1090    raeburn  13578: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 13579: userspace, probably shouldn't be called directly
                   13580: 
                   13581:   docuname: username or courseid of destination for the file
                   13582:   docudom: domain of user/course of destination for the file
                   13583:   formname: same as for userfileupload()
1.1090    raeburn  13584:   fname: filename (including subdirectories) for the file
                   13585:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   13586:   allfiles: reference to hash used to store objects found by parser
                   13587:   codebase: reference to hash used for codebases of java objects found by parser
                   13588:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   13589:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   13590:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   13591:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   13592:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   13593:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  13594:   mimetype: reference to scalar to accommodate mime type determined
                   13595:             from File::MMagic if $parser = parse.
1.608     albertel 13596: 
                   13597:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  13598:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   13599:  was 'overwrite').
                   13600:  
1.608     albertel 13601: 
                   13602: =item *
                   13603: 
                   13604: renameuserfile(): renames an existing userfile to a new name
                   13605: 
                   13606:   Args:
                   13607:    docuname: username or courseid of destination for the file
                   13608:    docudom: domain of user/course of destination for the file
                   13609:    old: current file name (including any subdirs under userfiles)
                   13610:    new: desired file name (including any subdirs under userfiles)
                   13611: 
                   13612: =item *
                   13613: 
                   13614: mkdiruserfile(): creates a directory is a userfiles dir
                   13615: 
                   13616:   Args:
                   13617:    docuname: username or courseid of destination for the file
                   13618:    docudom: domain of user/course of destination for the file
                   13619:    dir: dir to create (including any subdirs under userfiles)
                   13620: 
                   13621: =item *
                   13622: 
                   13623: removeuserfile(): removes a file that exists in userfiles
                   13624: 
                   13625:   Args:
                   13626:    docuname: username or courseid of destination for the file
                   13627:    docudom: domain of user/course of destination for the file
                   13628:    fname: filname to delete (including any subdirs under userfiles)
                   13629: 
                   13630: =item *
                   13631: 
                   13632: removeuploadedurl(): convience function for removeuserfile()
                   13633: 
                   13634:   Args:
                   13635:    url:  a full /uploaded/... url to delete
                   13636: 
1.747     albertel 13637: =item * 
                   13638: 
                   13639: get_portfile_permissions():
                   13640:   Args:
                   13641:     domain: domain of user or course contain the portfolio files
                   13642:     user: name of user or num of course contain the portfolio files
                   13643:   Returns:
                   13644:     hashref of a dump of the proper file_permissions.db
                   13645:    
                   13646: 
                   13647: =item * 
                   13648: 
                   13649: get_access_controls():
                   13650: 
                   13651: Args:
                   13652:   current_permissions: the hash ref returned from get_portfile_permissions()
                   13653:   group: (optional) the group you want the files associated with
                   13654:   file: (optional) the file you want access info on
                   13655: 
                   13656: Returns:
1.749     raeburn  13657:     a hash (keys are file names) of hashes containing
                   13658:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   13659:         values are XML containing access control settings (see below) 
1.747     albertel 13660: 
                   13661: Internal notes:
                   13662: 
1.749     raeburn  13663:  access controls are stored in file_permissions.db as key=value pairs.
                   13664:     key -> path to file/file_name\0uniqueID:scope_end_start
                   13665:         where scope -> public,guest,course,group,domains or users.
                   13666:               end -> UNIX time for end of access (0 -> no end date)
                   13667:               start -> UNIX time for start of access
                   13668: 
                   13669:     value -> XML description of access control
                   13670:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   13671:             <start></start>
                   13672:             <end></end>
                   13673: 
                   13674:             <password></password>  for scope type = guest
                   13675: 
                   13676:             <domain></domain>     for scope type = course or group
                   13677:             <number></number>
                   13678:             <roles id="">
                   13679:              <role></role>
                   13680:              <access></access>
                   13681:              <section></section>
                   13682:              <group></group>
                   13683:             </roles>
                   13684: 
                   13685:             <dom></dom>         for scope type = domains
                   13686: 
                   13687:             <users>             for scope type = users
                   13688:              <user>
                   13689:               <uname></uname>
                   13690:               <udom></udom>
                   13691:              </user>
                   13692:             </users>
                   13693:            </scope> 
                   13694:               
                   13695:  Access data is also aggregated for each file in an additional key=value pair:
                   13696:  key -> path to file/file_name\0accesscontrol 
                   13697:  value -> reference to hash
                   13698:           hash contains key = value pairs
                   13699:           where key = uniqueID:scope_end_start
                   13700:                 value = UNIX time record was last updated
                   13701: 
                   13702:           Used to improve speed of look-ups of access controls for each file.  
                   13703:  
                   13704:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   13705: 
1.1172.2.13  raeburn  13706: =item *
                   13707: 
1.749     raeburn  13708: modify_access_controls():
                   13709: 
                   13710: Modifies access controls for a portfolio file
                   13711: Args
                   13712: 1. file name
                   13713: 2. reference to hash of required changes,
                   13714: 3. domain
                   13715: 4. username
                   13716:   where domain,username are the domain of the portfolio owner 
                   13717:   (either a user or a course) 
                   13718: 
                   13719: Returns:
                   13720: 1. result of additions or updates ('ok' or 'error', with error message). 
                   13721: 2. result of deletions ('ok' or 'error', with error message).
                   13722: 3. reference to hash of any new or updated access controls.
                   13723: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   13724:    key = integer (inbound ID)
1.1172.2.13  raeburn  13725:    value = uniqueID
                   13726: 
                   13727: =item *
                   13728: 
                   13729: get_timebased_id():
                   13730: 
                   13731: Attempts to get a unique timestamp-based suffix for use with items added to a
                   13732: course via the Course Editor (e.g., folders, composite pages,
                   13733: group bulletin boards).
                   13734: 
                   13735: Args: (first three required; six others optional)
                   13736: 
                   13737: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   13738:    docssequence, or name of group
                   13739: 
                   13740: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   13741:    e.g., num, boardids
                   13742: 
                   13743: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   13744:    file will be named nohist_namespace.db
                   13745: 
                   13746: 4. cdom: domain of course; default is current course domain from %env
                   13747: 
                   13748: 5. cnum: course number; default is current course number from %env
                   13749: 
                   13750: 6. idtype: set to concat if an additional digit is to be appended to the
                   13751:    unix timestamp to form the suffix, if the plain timestamp is already
                   13752:    in use.  Default is to not do this, but simply increment the unix
                   13753:    timestamp by 1 until a unique key is obtained.
                   13754: 
                   13755: 7. who: holder of locking key; defaults to user:domain for user.
                   13756: 
                   13757: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   13758:    retrying); default is 3.
                   13759: 
                   13760: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   13761: 
                   13762: Returns:
                   13763: 
                   13764: 1. suffix obtained (numeric)
                   13765: 
                   13766: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   13767: 
                   13768: 3. error: contains (localized) error message if an error occurred.
                   13769: 
1.747     albertel 13770: 
1.608     albertel 13771: =back
                   13772: 
1.243     albertel 13773: =head2 HTTP Helper Routines
                   13774: 
                   13775: =over 4
                   13776: 
1.191     harris41 13777: =item *
                   13778: 
                   13779: escape() : unpack non-word characters into CGI-compatible hex codes
                   13780: 
                   13781: =item *
                   13782: 
                   13783: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   13784: 
1.243     albertel 13785: =back
                   13786: 
                   13787: =head1 PRIVATE SUBROUTINES
                   13788: 
                   13789: =head2 Underlying communication routines (Shouldn't call)
                   13790: 
                   13791: =over 4
                   13792: 
                   13793: =item *
                   13794: 
                   13795: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   13796: 
                   13797: =item *
                   13798: 
                   13799: reply() : uses subreply to send a message to remote machine, logs all failures
                   13800: 
                   13801: =item *
                   13802: 
                   13803: critical() : passes a critical message to another server; if cannot
                   13804: get through then place message in connection buffer directory and
                   13805: returns con_delayed, if incapable of saving message, returns
                   13806: con_failed
                   13807: 
                   13808: =item *
                   13809: 
                   13810: reconlonc() : tries to reconnect lonc client processes.
                   13811: 
                   13812: =back
                   13813: 
                   13814: =head2 Resource Access Logging
                   13815: 
                   13816: =over 4
                   13817: 
                   13818: =item *
                   13819: 
                   13820: flushcourselogs() : flush (save) buffer logs and access logs
                   13821: 
                   13822: =item *
                   13823: 
                   13824: courselog($what) : save message for course in hash
                   13825: 
                   13826: =item *
                   13827: 
                   13828: courseacclog($what) : save message for course using &courselog().  Perform
                   13829: special processing for specific resource types (problems, exams, quizzes, etc).
                   13830: 
1.191     harris41 13831: =item *
                   13832: 
                   13833: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   13834: as a PerlChildExitHandler
1.243     albertel 13835: 
                   13836: =back
                   13837: 
                   13838: =head2 Other
                   13839: 
                   13840: =over 4
                   13841: 
                   13842: =item *
                   13843: 
                   13844: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 13845: 
                   13846: =back
                   13847: 
                   13848: =cut
1.877     foxr     13849: 

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